index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
39,993,758
|
binaryeast/teablog
|
refs/heads/master
|
/blog/admin.py
|
from django.contrib import admin
from .models import TeaBlog, TeaPost, Comment
@admin.register(TeaBlog)
class TeaBlogAdmin(admin.ModelAdmin):
list_display = ["title", "owner", "is_public"]
list_display_link = ["title", "owner"]
@admin.register(TeaPost)
class TeaPostAdmin(admin.ModelAdmin):
list_display = ["posted_blog", "post_title"]
list_display_link = ["posted_blog", "post_title"]
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ["post", "writer", "comment_body"]
list_display_link = ["post", "writer", "comment_body"]
# @admin.register()
# class Admin(admin.ModelAdmin):
# list_display = [""]
# list_display_link = [""]
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,759
|
binaryeast/teablog
|
refs/heads/master
|
/blog/migrations/0002_auto_20210318_1750.py
|
# Generated by Django 3.1.6 on 2021-03-18 08:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='comment',
options={'verbose_name': '댓글', 'verbose_name_plural': '댓글'},
),
migrations.RenameField(
model_name='comment',
old_name='comment',
new_name='comment_body',
),
migrations.RenameField(
model_name='comment',
old_name='hanged_post',
new_name='post',
),
migrations.RemoveField(
model_name='teapost',
name='blog',
),
migrations.AddField(
model_name='teapost',
name='posted_blog',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='blog.teablog', verbose_name='포스트된 블로그'),
preserve_default=False,
),
migrations.AlterField(
model_name='comment',
name='writer',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='댓쓴이'),
),
migrations.AlterField(
model_name='teablog',
name='title',
field=models.CharField(max_length=500),
),
migrations.AlterField(
model_name='teapost',
name='post_body',
field=models.TextField(),
),
]
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,760
|
binaryeast/teablog
|
refs/heads/master
|
/blog/views.py
|
from django.http import Http404
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions, renderers, viewsets
from rest_framework.decorators import action
from .models import TeaBlog, TeaPost, Comment
from .serializers import UserSerializer, TeaBlogSerializer, TeaPostSerializer, CommentSerializer
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class BlogViewSet(viewsets.ReadOnlyModelViewSet):
queryset = TeaBlog.objects.all()
serializer_class = TeaBlogSerializer
permission_classes = (permissions.AllowAny,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,761
|
binaryeast/teablog
|
refs/heads/master
|
/blog/serializers.py
|
from rest_framework import serializers
from .models import TeaBlog, TeaPost, Comment
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
extra_kwargs = {'url': {'view_name': 'blog:user-detail'}}
# blogs
class TeaBlogSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source="Owner.username")
class Meta:
model = TeaBlog
fields = ["title", "owner", "is_public"]
depth = 1
class TeaPostSerializer(serializers.ModelSerializer):
class Meta:
model = TeaPost
fields = ["posted_blog", "post_title", "post_body"]
class CommentSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source="Owner.username")
class Meta:
model = Comment
fields = ["post", "writer", "comment_body"]
depth = 1
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,762
|
binaryeast/teablog
|
refs/heads/master
|
/blog/models.py
|
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class TimeStampModel(models.Model):
class Meta:
abstract = True
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class TeaBlog(models.Model):
title = models.CharField(max_length=500)
owner = models.ForeignKey(User, verbose_name="개최자", on_delete=models.CASCADE)
open_status = [
("PUB", "Public"),
("PRV", "Private")
]
is_public = models.CharField(
"공개 상태",
max_length = 3,
choices = open_status,
default = open_status[0][0]
)
def __str__(self):
return self.title
class TeaPost(TimeStampModel):
posted_blog = models.ForeignKey(TeaBlog, verbose_name="포스트된 블로그", on_delete=models.CASCADE)
post_title = models.CharField("포스트 제목", max_length=500)
post_body = models.TextField()
def __str__(self):
return self.post_title
class Comment(TimeStampModel):
"""
Blog post's comment.
It has time(created and modified), user, post foreignkey.
"""
class Meta:
verbose_name = "댓글"
verbose_name_plural = verbose_name
post = models.ForeignKey(TeaPost, verbose_name="달린 포스트", on_delete=models.CASCADE)
writer = models.ForeignKey(User, verbose_name="댓쓴이", null=True, on_delete=models.SET_NULL)
comment_body = models.TextField("댓글")
def __str__(self):
return str(self.post) + str(self.comment_body)
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,763
|
binaryeast/teablog
|
refs/heads/master
|
/blog/migrations/0001_initial.py
|
# Generated by Django 3.1.6 on 2021-03-14 07:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='TeaBlog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=500, verbose_name='블로그 제목')),
('is_public', models.CharField(choices=[('PUB', 'Public'), ('PRV', 'Private')], default='PUB', max_length=3, verbose_name='공개 상태')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='개최자')),
],
),
migrations.CreateModel(
name='TeaPost',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('post_title', models.CharField(max_length=500, verbose_name='포스트 제목')),
('post_body', models.TextField(verbose_name='글')),
('blog', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.teablog', verbose_name='블로그')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('comment', models.TextField(verbose_name='댓글')),
('hanged_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.teapost', verbose_name='달린 포스트')),
('writer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='댓글쓴이')),
],
options={
'abstract': False,
},
),
]
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
39,993,764
|
binaryeast/teablog
|
refs/heads/master
|
/blog/urls.py
|
from django.urls import include, path, re_path
from rest_framework.routers import DefaultRouter
from .views import UserViewSet, BlogViewSet
app_name = "blog"
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'blogs', BlogViewSet, basename="blog")
router.register(r'users', UserViewSet, basename="User")
# The API URLs are now determined automatically by the router.
# Additionally, we include the login URLs for the browsable API.
urlpatterns = [
re_path(r'^', include(router.urls))
]
|
{"/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py", "/blog/serializers.py"], "/blog/serializers.py": ["/blog/models.py"], "/blog/urls.py": ["/blog/views.py"]}
|
40,068,069
|
neldis93/Python-Mysql
|
refs/heads/master
|
/python-mysql/manager.py
|
def listclients(clients):
cont=1
for i in clients:
data= "{0}. DNI: {1} | First name: {2} | Last name: {3}"
print(data.format(cont, i[3], i[1], i[2] ))
cont +=1
print(" ")
def is_valid_client():
while True:
first_name= str(input('Please enter your first name: '))
last_name=str(input('Please enter your last name: '))
dni= str(input('Enter your DNI: ').upper())
print(" ")
if len(first_name) > 0 and len(last_name) > 0 and len(dni) > 0:
if len(dni) == 9:
break
else:
print('The DNI field cannot have more or less than 9 alphanumeric characters.')
print('Please login again\n')
else:
print('The first name, last name and DNI field cannot be empty.')
print('Please login again\n')
client= (first_name,last_name,dni)
return client
def data_deletion(clients):
listclients(clients)
exists_client=False
client_to_delete= input('Enter the DNI of the customer to remove: ')
for client in clients:
#print(c[3])
if client[3] == client_to_delete:
exists_client=True
break
if not exists_client:
client_to_delete= ""
return client_to_delete
# def data_update(clients):
# listclients(clients)
# exists_client=False
# client_to_update=input('Introduzca el first name del cliente que desea actualizar')
# for u in clients:
# if u[1] == client_to_update:
# exists_client=True
# break
# if not exists_client:
# client_to_update= ""
# clients_f=input()
|
{"/python-mysql/database/connection.py": ["/python-mysql/database/base.py"]}
|
40,068,070
|
neldis93/Python-Mysql
|
refs/heads/master
|
/python-mysql/database/connection.py
|
import mysql.connector
from mysql.connector import Error
from .base import get_secret
class DAO:
def __init__(self):
try:
self.myconnection= mysql.connector.connect(
port=get_secret('PORT'),
user=get_secret('USER'),
password=get_secret('PASSWORD'),
database=get_secret('DATABASE'),
auth_plugin=get_secret('AUTH_PLUGIN')
)
if self.myconnection.is_connected():
print('Successful connection')
except Error as ex:
print(f'Error during connection:{ex}')
# finally:
# if self.myconnection.is_connected():
# self.myconnection.close()
# print('the conexion to finalized')
def list_client(self):
if self.myconnection.is_connected():
try:
cursor= self.myconnection.cursor()
cursor.execute("SELECT * FROM Customer ORDER BY first_name ASC")
result=cursor.fetchall()
return result
except Error as ex:
print(f'Error during connection:{ex}')
def register_clients(self,values):
if self.myconnection.is_connected():
try:
cursor= self.myconnection.cursor()
sql= "INSERT INTO Customer (first_name,last_name,dni) VALUES ('{0}','{1}','{2}')"
cursor.execute(sql.format(values[0], values[1],values[2]))
self.myconnection.commit()
print("")
print("Successfully added customer\n")
except Error as ex:
print(f'Error during connection:{ex}')
# def update_client(self,new_f,new_l, new_dni):
# if self.myconnection.is_connected():
# try:
# cursor= self.myconnection.cursor()
# sql= "UPDATE Customer SET first_name='{0}',last_name='{1}',dni= '{2}' WHERE first_name='{0}',last_name='{1}' dni='{2}'"
# cursor.execute(sql.format(new_f,new_l,new_dni))
# self.myconnection.commit()
# print("Cliente actualizado\n")
# except Error as ex:
# print(f'Error durante la conexion:{ex}')
def delete_client(self,code_delete):
if self.myconnection.is_connected():
try:
cursor= self.myconnection.cursor()
sql= "DELETE FROM Customer WHERE dni= '{0}'"
cursor.execute(sql.format(code_delete))
self.myconnection.commit()
print("Customer removed\n")
except Error as ex:
print(f'Error during connection::{ex}')
|
{"/python-mysql/database/connection.py": ["/python-mysql/database/base.py"]}
|
40,075,091
|
SlBl286/kivy
|
refs/heads/main
|
/main.py
|
from config import *
from kivy.app import App
from kivy.properties import StringProperty,BooleanProperty
from kivy.uix.widget import Widget;
from kivy.uix.button import Button;
from kivy.uix.screenmanager import ScreenManager,Screen;
from kivy.lang import Builder
Builder.load_file('Screen/LayoutScreen.kv')
class LayoutScreen(Screen):
pass;
class WidgetScreen(Screen):
isEnable = BooleanProperty(False);
isSliderDisable = BooleanProperty(True);
text = StringProperty("0");
def on_button_click(self):
if(self.isEnable):
self.text = str(int(self.text)+1);
def on_toggle_button_click(self,widget):
if(widget.state == "normal"):
widget.text = "OFF";
self.isEnable = False;
else:
widget.text = "ON"
self.isEnable = True;
def on_switch_active(self,widget):
if(widget.active == "OFF"):
self.isSliderDisable = True
else:
self.isSliderDisable = False
class MenuScreen(Screen):
pass;
class TheLabApp(App):
def build(self):
screenManager = ScreenManager();
screenManager.add_widget(MenuScreen(name='MenuScreen'));
screenManager.add_widget(LayoutScreen(name='LayoutScreen'));
screenManager.add_widget(WidgetScreen(name='WidgetScreen'));
return screenManager;
if __name__ == '__main__':
TheLabApp().run();
|
{"/main.py": ["/config.py"]}
|
40,075,092
|
SlBl286/kivy
|
refs/heads/main
|
/config.py
|
from kivy.config import Config
Config.set('kivy', 'exit_on_escape', '0')
|
{"/main.py": ["/config.py"]}
|
40,304,800
|
abhik92/avicii
|
refs/heads/master
|
/main.py
|
from nadal import Slam
from datetime import datetime, timedelta
match_score = open("points.txt",'r')
score_board = open("scoresheet.txt",'w')
MAX_DAYS = 200
end = datetime.now()
start = end - timedelta(days=MAX_DAYS*7/5 + 50)
for points in match_score:
game = points.split()
tournament = game[0]
final = game[1]
debut = datetime.fromisoformat(final)
sell = end - debut
start_first = start
if debut < start_first:
start_first = debut
set_summary = Slam(tournament, 'yahoo', start_first.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
set_one = set_summary.serve(MAX_DAYS)
set_two = set_summary.serve(int(MAX_DAYS/2))
set_three = set_summary.serve(int(MAX_DAYS/4))
bounce = "The current price is {}".format(set_summary.lob(end.strftime("%Y-%m-%d"))) + '\n'
rolling = "The 200, 100, 50 day rolling averages are {},{},{}".format(set_one, set_two, set_three) + '\n'
history = "You bought this {} time units ago".format(sell) + '\n'
print(bounce, rolling, history)
|
{"/french.py": ["/nadal.py", "/hawkeye.py"], "/main.py": ["/nadal.py"]}
|
40,376,182
|
LaraM21/Vislice
|
refs/heads/master
|
/vislice.py
|
import bottle
import model
COOKIE_ID_IGRE = "ID_IGRE"
@bottle.get("/")
def index():
return bottle.template("index.tpl")
@bottle.get("/igra/")
def nova_igra():
vislice = model.Vislice.preberi_iz_datoteke()
id_igre = vislice.nova_igra()
print(vislice.igre)
vislice.zapisi_v_datoteko()
bottle.response.set_cookie(COOKIE_ID_IGRE,id_igre,
path = "/", secret = "SECRET" )
bottle.redirect("/igraj/")
@bottle.get("/igraj/")
def igraj_igro():
id_igre = int(bottle.request.get_cookie(COOKIE_ID_IGRE, secret = "SECRET"))
vislice = model.Vislice.preberi_iz_datoteke("podatki.json")
trenutna_igra, trenutno_stanje = \
vislice.igre[id_igre]
vislice.zapisi_v_datoteko()
return bottle.template("igra.tpl",
igra = trenutna_igra,
stanje = trenutno_stanje)
@bottle.get("/igra/<id_igre:int>/")
def pokazi_igro(id_igre):
vislice = model.Vislice.preberi_iz_datoteke("podatki.json")
trenutna_igra, trenutno_stanje = \
vislice.igre[id_igre]
vislice.zapisi_v_datoteko()
return bottle.template("igra.tpl",
igra = trenutna_igra,
stanje = trenutno_stanje)
@bottle.post("/igraj/")
def ugibaj_na_igri_igraj():
id_igre = int(bottle.request.get_cookie(COOKIE_ID_IGRE, secret = "SECRET"))
vislice = model.Vislice.preberi_iz_datoteke()
ugibana = bottle.request.forms["ugibana_crka"]
vislice.ugibaj(id_igre,ugibana)
vislice.zapisi_v_datoteko()
bottle.redirect(f"/igraj/")
"""
@bottle.get("/igra/<id_igre:int>/")
def poglej_igro(id_igre):
igra, stanje = vislice.igre[id_igre]
return bottle.template("igra.tpl", igra=igra, stanje = stanje)
@bottle.post("/igra/<id_igre:int>/")
def ugibaj_crko(id_igre):
ugibana_crka = bottle.request.forms["ugibana_crka"]
vislice.ugibaj(id_igre, ugibana_crka)
bottle.redirect("")
"""
#poženi miško
bottle.run(reloader=True, debug=True)
print("Tega se ne sme videt")
|
{"/vislice.py": ["/model.py"], "/tekstovni_vmesnik.py": ["/model.py"]}
|
40,376,183
|
LaraM21/Vislice
|
refs/heads/master
|
/tekstovni_vmesnik.py
|
import model
def izpis_igre(igra):
tekst = f"""#######################\n
Pravilni del gesla : {igra.pravilni_del_gesla()}\n
Število poskusov : {model.STEVILO_DOVOLJENIH_NAPAK + 1 - igra.stevilo_napak()}\n
Nepravilne črke : {igra.nepravilni.ugibi()}
#######################\n"""
return tekst
def izpis_zmage(igra):
tekst = """ ##################\n
Bravo! Zmagali ste! \n
Uganili ste geslo: {igra.pravilni_del_gesla()}\n
##################\n"""
return tekst
def izpis_poraza(igra):
tekst = """#############\n
Porabili ste vse poskuse.\n
Pravilno geslo : {igra.geslo}\n
#############\n"""
return tekst
def zahtevaj_vnos():
return input('Vnesite črko!')
def pozeni_vmesnik():
igra = model.nova_igra()
while True:
crka = zahtevaj_vnos()
odziv = igra.ugibaj(crka)
if odziv == model.ZMAGA:
print(izpis_zmage(igra))
break
elif odziv == model.PORAZ:
print(izpis_poraza(igra))
break
else:
print(izpis_igre(igra))
pozeni_vmesnik()
|
{"/vislice.py": ["/model.py"], "/tekstovni_vmesnik.py": ["/model.py"]}
|
40,376,184
|
LaraM21/Vislice
|
refs/heads/master
|
/model.py
|
import json
STEVILO_DOVOLJENIH_NAPAK = 10
PRAVILNA_CRKA = '+'
PONOVLJENA_CRKA = 'o'
NAPACNA_CRKA = '-'
ZMAGA = 'W'
PORAZ = 'X'
ZACETEK = 'A'
DATOTEKA_S_STANJEM= "podatki.json"
class Vislice:
"""
Krovni objekt, ki upravlja z vsemi igrami (baza vseh iger in kaj dogaja noter)
"""
def __init__(self,zacetne_igre, datoteka_s_stanjem = DATOTEKA_S_STANJEM):
self.igre = zacetne_igre
self.datoteka_s_stanjem = datoteka_s_stanjem
def prost_id_igre(self):
if not self.igre:
return 1
return max(self.igre.keys()) + 1
def nova_igra(self, ):
nov_id = self.prost_id_igre()
sveza = nova_igra(bazen_besed)
self.igre[nov_id] = (sveza,ZACETEK)
return nov_id
def ugibaj(self, id_igre,crka):
igra, stanje = self.igre[id_igre]
novo_stanje = igra.ugibaj(crka)
self.igre[id_igre] = (igra, novo_stanje)
def dobi_json_slovar(self):
slovar_iger = {}
for id_igre,(igra,stanje) in self.igre.items():
slovar_iger[id_igre] = [
igra.dobi_json_slovar(),
stanje,
]
return {
"igre": slovar_iger,
"datoteka_s_stanjem" : self.datoteka_s_stanjem,
}
@staticmethod
def preberi_iz_datoteke(ime_datoteke=DATOTEKA_S_STANJEM):
with open(ime_datoteke, "r") as in_file:
slovar = json.load(in_file) #slovar
return Vislice.dobi_vislice_iz_slovarja(slovar)
@staticmethod
def dobi_vislice_iz_slovarja(slovar):
slovar_iger = {} #slovar objektov - Igra
for id_igre, (igra_slovar,stanje) in slovar["igre"].items():
slovar_iger[int(id_igre)] = (
Igra.dobi_igro_iz_slovarja(igra_slovar),
stanje
)
print(slovar_iger)
return Vislice(
slovar_iger,
slovar["datoteka_s_stanjem"]
)
def zapisi_v_datoteko(self):
slovar = self.dobi_json_slovar()
with open(self.datoteka_s_stanjem,"w") as out_file:
json.dump(slovar,out_file)
class Igra:
def __init__(self, geslo, crke):
self.geslo = geslo.upper()
self.crke = crke[:]
def dobi_json_slovar(self):
return{
"geslo" : self.geslo,
"crke" : self.crke,
}
@staticmethod
def dobi_igro_iz_slovarja(slovar):
return Igra(
slovar["geslo"],slovar.get("crke","")
)
def napacne_crke(self):
return [crka for crka in self.crke if crka not in self.geslo]
def pravilne_crke(self):
return [crka for crka in self.crke if crka in self.geslo]
def stevilo_napak(self):
return len(self.napacne_crke())
def zmaga(self):
vse_crke = True
for crka in self.geslo:
if crka in self.pravilne_crke():
pass
else:
vse_crke = False
break
return vse_crke and STEVILO_DOVOLJENIH_NAPAK >= self.stevilo_napak()
def poraz(self):
return STEVILO_DOVOLJENIH_NAPAK < self.stevilo_napak()
def pravilni_del_gesla(self):
delni = ''
ugibanje = [crka.upper() for crka in self.crke]
for crka in self.geslo:
if crka.upper() in ugibanje:
delni += crka + ''
else:
delni += '_ '
return delni
def nepravilni_ugibi(self):
return ' '.join(self.napacne_crke())
def ugibaj(self,crka):
crka = crka.upper()
if crka in self.crke:
return PONOVLJENA_CRKA
elif crka in self.geslo:
self.crke.append(crka)
if self.zmaga():
return ZMAGA
else:
return PRAVILNA_CRKA
else:
self.crke.append(crka)
if self.poraz():
return PORAZ
else:
return NAPACNA_CRKA
import random
with open("besede.txt") as inp:
bazen_besed =inp.readlines()
def nova_igra(bazen):
return Igra(random.choice(bazen),[])
|
{"/vislice.py": ["/model.py"], "/tekstovni_vmesnik.py": ["/model.py"]}
|
40,459,277
|
vibrainium-analytics/ava
|
refs/heads/master
|
/User_Interface/Home_Page.py
|
import tkinter as tk
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
# File system access library
import glob, os
import json
class Home_Page(tk.Frame):
# Update page with new content every 1 second
def poll (self):
with open(directory['app_data'] + 'selected_vehicle.json','r') as f:
data = json.load(f)
f.close
# Update labels with latest data
self.label1['text'] = "Vehicle Name: {}".format(data['name'])
self.label2['text'] = "Vehicle Make: {}".format(data['make'])
self.label3['text'] = "Vehicle Model: {}".format(data['model'])
self.label4['text'] = "Vehicle Year: {}".format(data['year'])
# check for changes in data every 10 seconds
self.after(10000, self.poll)
def loadSavedVehicleProfile (self, event):
# Save to json file (in vehicle profiles folder)
with open(directory['veh_path'] + self.Saved_Profiles_Dropdown.get() + '.json','r') as f:
data = json.load(f)
f.close
# Write saved_vehicle status folder
with open(directory['app_data'] + 'selected_vehicle.json', 'w') as f:
json.dump(data,f)
f.close
# Update labels with latest data
self.label1['text'] = "Vehicle Name: {}".format(data['name'])
self.label2['text'] = "Vehicle Make: {}".format(data['make'])
self.label3['text'] = "Vehicle Model: {}".format(data['model'])
self.label4['text'] = "Vehicle Year: {}".format(data['year'])
def refresh(self):
# Load vehicles from vehicle directory
from os import listdir
vehicle_filenames = os.listdir(directory["veh_path"])
formatted_filenames = []
# Format filenames to remove .json extension
for filename in vehicle_filenames:
if filename.endswith(".json"):
formatted_filenames.append(str(('.'.join(filename.split('.')[:-1]))))
self.Saved_Profiles_Dropdown['values'] = formatted_filenames
def __init__(self,parent,controller):
# Global directory navigation file
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
veh_path = str(directory['veh_path'])
# AVA app controller (app_data access)
self.controller = controller
tk.Frame.__init__(self,parent)
self.pageLabelFrame=Frame(self, borderwidth=4, relief=GROOVE)
Label(self.pageLabelFrame, text='Home Page', width=35).pack(side=TOP)
self.pageLabelFrame.pack(pady = (5,5), ipadx = 2, ipady = 2, fill = "x")
# Load vehicles from vehicle directory
from os import listdir
vehicle_filenames = os.listdir(directory['veh_path'])
formatted_filenames = []
# Format filenames to remove .json extension
for filename in vehicle_filenames:
if filename.endswith(".json"):
formatted_filenames.append(str(('.'.join(filename.split('.')[:-1]))))
# Create saved vehicle profiles dropdown menu
self.Saved_Profiles_Frame = ttk.Labelframe(self, text='Load Saved Vehicle', width=40, height=30, borderwidth=5, relief=GROOVE)
self.Saved_Profiles_Dropdown = ttk.Combobox(self.Saved_Profiles_Frame, postcommand = self.refresh, state='readonly')
self.Saved_Profiles_Dropdown.bind('<<ComboboxSelected>>',self.loadSavedVehicleProfile)
self.Saved_Profiles_Dropdown.pack(pady = 5, padx=5)
self.Saved_Profiles_Frame.pack(side="top",pady=(4, 2), padx = 10, ipadx = 10, ipady = 15)
# Default settings for test_preferences.json
data = {
'test_type' : 'Baseline-Idle',
'delay_time' : '0',
'test_duration' : '0',
}
with open(directory['app_data'] + 'test_preferences.json','w') as f:
json.dump(data,f)
f.close
frame1 = tk.LabelFrame(self.Saved_Profiles_Frame, text="Active Vehicle Profile", width=30, height=25, bd=1, borderwidth=3, relief=GROOVE)
frame1.pack(padx = 3, pady = 1, ipadx = 10, ipady = 1)
frame2 = tk.LabelFrame(self, text="Control Center", width=25, height=35, bd=1, borderwidth=5, relief="groove")
frame2.pack(side = "top", pady = (8,8), ipadx = 5, ipady = 5)
frame3 = tk.LabelFrame(self, text="Extras", bd=1, borderwidth=4, relief=GROOVE)
frame3.pack(side = "bottom", pady = (25,5), ipadx = 10, ipady = 5)
self.label1 = ttk.Label(frame1, text="Vehicle Name: ")
self.label1.pack(pady = (10,2), padx = 1, side = "top", anchor = "n")
self.label2 = ttk.Label(frame1, text=str("Vehicle Make: "))
self.label2.pack(pady=2,padx=1, side = "top", anchor = "n")
self.label3 = ttk.Label(frame1, text=str("Vehicle Model: "))
self.label3.pack(pady=2,padx=1, side = "top", anchor = "n")
self.label4 = ttk.Label(frame1, text=str("Vehicle Year: " ))
self.label4.pack(pady=2,padx=1, side = "top", anchor = "n")
goToNewVehiclePage_button = ttk.Button(frame2, text="New Vehicle",
command=lambda: controller.show_page("New_Vehicle_Page"))
goToNewVehiclePage_button.pack(padx = 18, pady = 5, side = "left", expand = "yes", anchor = "n")
goToRunTestPage_button = ttk.Button(frame2, text="Configure/Run Test",command=lambda: controller.show_page("Configure_Test_Page"))
goToRunTestPage_button.pack(padx = 18, pady = 5, side = "left", expand = "no", anchor = "n")
goToPlotPage_button = ttk.Button(frame2, text="Plot",command=lambda: controller.show_page("Plot_Page"))
goToPlotPage_button.pack(padx = 18, pady = 5, side = "left", expand = "yes", anchor = "n")
Tutorial_Button = ttk.Button(frame3, text="AVA tutorial",
command=lambda: controller.show_page("Tutorial_Main_Page"))
Tutorial_Button.pack(padx = 25, pady = 7, side = "left", expand = "yes", anchor = "nw")
About_Button = ttk.Button(frame3, text="About Vibrainium Analytics...",
command=lambda: controller.show_page("About_Page"))
About_Button.pack(padx = 25, pady = 7, side = "right", expand = "yes", anchor = "ne")
self.poll()
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,459,278
|
vibrainium-analytics/ava
|
refs/heads/master
|
/User_Interface/Save_Test_Page.py
|
import tkinter as tk
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
from Signal_Processing.Signal_Process import Signal_Process
# File system access library
import glob, os
import json
class Save_Test_Page(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# AVA app controller (app_data access)
self.controller = controller
self.pageLabelFrame=Frame(self, borderwidth=4, relief=GROOVE)
Label(self.pageLabelFrame, text='Configure/Run Test Page', width=35).pack(side=TOP)
self.pageLabelFrame.pack(pady = (5,5), ipadx = 2, ipady = 2, fill = "x")
goToHomePage_button = ttk.Button(self, text="Go Back",
command=lambda: controller.show_page("Configure_Test_Page"))
goToHomePage_button.pack(pady=1,padx=5, side = "left", expand = "no", anchor = "n")
frame1 = tk.LabelFrame(self, text="Post-Test parameter entry", width=60, height=60, bd=1, borderwidth=3, relief=GROOVE)
frame1.place(rely = 0.5, relx = 0.5,anchor= CENTER)
AC_Status = ('AC Off', 'AC On')
self.AC_Status1 = ttk.Labelframe(self, text='AC Status')
self.AC_Status = ttk.Combobox(self.AC_Status1, values= AC_Status, state='readonly')
self.AC_Status.current(0) # set selection
self.AC_Status.pack(pady=5, padx=10)
self.AC_Status1.pack(side="top", pady=20, padx=10, ipady = 2, ipadx = 2)
Idle_Status = ('Yes', 'No')
self.Idle_Status1 = ttk.Labelframe(self, text='Under Idle?')
self.Idle_Status = ttk.Combobox(self.Idle_Status1, values=Idle_Status, state='readonly')
self.Idle_Status.current(0) # set selection
self.Idle_Status.pack(pady=5, padx=10)
self.Idle_Status1.pack(side="top", pady=20, padx=10, ipady = 2, ipadx = 2)
Speeds = ('10', '10', '30', '40', '50', '60', '70', '80')
self.Speeds1 = ttk.Labelframe(frame1, text='Speed')
self.Speeds = ttk.Combobox(self.Speeds1, values=Speeds, state='readonly')
self.Speeds.current(0) # set selection
self.Speeds.pack(pady=5, padx=10)
self.Speeds1.pack(side="top", pady = 20, padx = 10, ipady = 2, ipadx = 2)
goToResultsPage_button = ttk.Button(frame1, text="View Results",
command=lambda: self.saveTestSettings(controller))
goToResultsPage_button.pack(pady=15,padx=5, side = "top", expand = "no", anchor = "n")
def saveTestSettings (self,controller):
# Global directory navigation file
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
# if you are at idle the speed is 0. this makes it so that the speed cannot be above 0 at idle
if str(self.Idle_Status.get()) == 'Yes':
speed = 0
else:
speed = self.Speeds.get()
# if you are at idle the speed is 0. this makes it so that the speed cannot be above 0 at idle
if str(self.Idle_Status.get()) == 'Yes':
speed = 0
else:
speed = self.Speeds.get()
data = {
'ac_status' : str(self.AC_Status.get()),
'idle_status' :str(self.Idle_Status.get()),
'speed' : str(speed),
}
with open(directory['app_data'] + 'save_test.json','w') as f:
json.dump(data,f)
f.close
controller.show_page("Results_Page")
Signal_Process()
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,459,279
|
vibrainium-analytics/ava
|
refs/heads/master
|
/User_Interface/New_Vehicle_Page.py
|
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from tkinter import *
class New_Vehicle_Page(tk.Frame):
def entry(self,controller):
veh = self.name.get()
cylinders = self.cylnd.get()
tiresize = self.tire.get()
advanced = self.advnc.get()
print ("name " + str(veh))
print ("cylinders " + str(cylinders))
print ("tire " + str(tiresize))
print ("extra " + str(advanced))
if advanced == 'Y' or advanced == 'y':
#open sub window for advanced
controller.show_page("NewVehiclePage_Advanced")
elif advanced == 'N' or advanced == 'n':
controller.show_page("HomePage")
def __init__(self, parent, controller):
Name = ""
## Make = ""
## Model = ""
## Year = ""
##
##
## num_cylinders = 0
## first_gear_ratio = 0.0
## second_gear_ratio = 0.0
## third_gear_ratio = 0.0
## fourth_gear_ratio = 0.0
## fifth_gear_ratio = 0.0
## sixth_gear_ratio = 0.0
## reverse_ratio = 0.0
## converter_ratio = 0.0
## final_drive_ratio = 0.0
## wheel_circ_inches = 0.0
## wheel_dist_per_cycle = 0.0
tk.Frame.__init__(self, parent)
self.controller = controller
self.pageLabelFrame=Frame(self, borderwidth=4, relief=GROOVE)
Label(self.pageLabelFrame, text='New/Edit Vehicle Profile Page', width=35).pack(side=TOP)
self.pageLabelFrame.pack(pady = (5,5), ipadx = 2, ipady = 2, fill = "x")
goToHomePage_button = Button(self, text="Go Back",
command=lambda: controller.show_page("Home_Page"))
goToHomePage_button.pack(pady=1,padx=5, side = "left", expand = "no", anchor = "n")
frame1 = LabelFrame(self, text="General Vehicle Info", width=500, height=300, bd=1, borderwidth=4, relief=GROOVE)
frame1.place(relx=1,x = -5, rely=0.1, anchor=NE)
frame2 = LabelFrame(self, text="Drivetrain Info", width=250, height=300, bd=1, borderwidth=4, relief=GROOVE)
frame2.place(relx=0 ,x = 5, rely=0.2, anchor=NW)
frame3 = LabelFrame(self, text="Advanced - engine accessories (need all belt-driven accessory pulley diameters)", width=700, height=100, bd=5, borderwidth=3, relief=GROOVE)
frame3.place(relx=0,x = 5, rely=1, anchor=SW)
## Name_Label = Label(frame1, text="Enter your vehicle name\n (ex: Steve-Toyota)")
## Name_Label.pack(pady=5)
## Name_Entry = Entry(frame1)
## Name_Entry.pack(padx=5)
##
## num_Cylinders_Label = Label(frame1, text="Enter number of cylinders")
## num_Cylinders_Label.pack(pady=5)
## num_Cylinders_Entry = Entry(self)
## numCylinders_Entry.pack(padx=5)
##
## wheel_Circumference_Label = Label(self, text="Enter tire diameter in inches\n (Leave blank if unknown)")
## wheelCircumference.pack(padx=5)
## wheel_Circumference_Entry = Entry(self)
## wheel_Circumference_Entry.pack(padx=5)
##
## num_Cylinders_Label = Label(frame1, text="Enter number of cylinders")
## num_Cylinders_Label.pack(pady=5)
##
## num_Cylinders_Entry = Entry(frame1)
## numCylinders_Entry.pack(padx=5)
####
##
## first_gear_ratio = 0.0
## second_gear_ratio = 0.0
## third_gear_ratio = 0.0
## fourth_gear_ratio = 0.0
## fifth_gear_ratio = 0.0
## sixth_gear_ratio = 0.0
## reverse_ratio = 0.0
## converter_ratio = 0.0
## final_drive_ratio = 0.0
class New_Vehicle_Page_Advanced(tk.Frame):
def __init__(self, parent, controller):
# Global directory navigation file
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = ttk.Label(self, text="New Vehicle Page")
self.label.pack(pady=1,padx=1, side = "top", anchor = "n")
self.label1 = ttk.Label(self,text = 'Name: ')
self.label1.pack(side= "top")
self.entry1 = ttk.Entry(self)
self.entry1.pack(side = "top")
self.label2 = ttk.Label(self,text = 'Make: ')
self.label2.pack(side= "top")
self.entry2 = ttk.Entry(self)
self.entry2.pack(side = "top")
self.label3 = ttk.Label(self,text = 'Model: ')
self.label3.pack(side= "top")
self.entry3 = ttk.Entry(self)
self.entry3.pack(side = "top")
self.label4 = ttk.Label(self,text = 'Year: ')
self.label4.pack(side= "top")
self.entry4 = ttk.Entry(self)
self.entry4.pack(side = "top")
self.goToHomePage_button = ttk.Button(self, text="Home",
command=lambda: self.saveNewVehicleProfile(controller))
self.goToHomePage_button.pack(side = "left", expand = "no", anchor = "n")
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,459,280
|
vibrainium-analytics/ava
|
refs/heads/master
|
/User_Interface/Test_Is_Running_Page.py
|
import tkinter as tk
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
from Signal_Processing.Delay_Bar import Delay_Bar
# File system access library
import glob, os
import json
class Test_Is_Running_Page(tk.Frame):
# Update page with new content every 1 second
def poll (self):
# Global directory navigation file
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
# Read json file
with open(directory['app_data'] + 'test_preferences.json','r') as f:
data = json.load(f)
f.close
# Update labels with latest data
self.label1['text'] = "Test Type: {}".format(data['test_type'])
self.label2['text'] = "Test Duration: {}".format(data['test_duration'] + " minutes")
self.label3['text'] = "Delay Time: {}".format(data['delay_time'] + " minutes")
# check for changes in data every 100 seconds
self.after(100000, self.poll)
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# AVA app controller (app_data access)
self.controller = controller
self.pageLabelFrame=Frame(self, borderwidth=4, relief=GROOVE)
Label(self.pageLabelFrame, text='Test Is Running Page', width=35).pack(side=TOP)
self.pageLabelFrame.pack(pady = (5,20), ipadx = 2, ipady = 2, fill = "x")
goToRunTestPage_button = ttk.Button(self, text="Go Back",
command=lambda: controller.show_page("Configure_Test_Page"))
goToRunTestPage_button.pack(pady=1,padx=15, side = "left", expand = "no", anchor = "n")
self.label1 = ttk.Label(self, text=str("Test Type: "))
self.label1.pack(pady = 1, padx = 2, side = "top", anchor = "n")
self.label2 = ttk.Label(self, text=str("Test Duration: "))
self.label2.pack(pady=2,padx=2, side = "top", anchor = "n")
self.label3 = ttk.Label(self, text=str("Delay Time: " ))
self.label3.pack(pady=2,padx=2, side = "top", anchor = "n")
startTest_button = ttk.Button(self, text="Start Test", command = lambda:self.delay(controller))
startTest_button.pack(pady=1,padx=15,side="left",expand="no",anchor="n")
self.poll()
# the following two functions make it so that the save button only appears after the test has begun
# and then the save button dissapears after you press it.
def delay (self,controller):
Delay_Bar()
self.goToSaveTestPage_button = ttk.Button(self, text="Save Test",
command=lambda: self.save(controller))
self.goToSaveTestPage_button.pack(pady=1,padx=15, side = "left", expand = "no", anchor = "n")
def save (self, controller):
controller.show_page('Save_Test_Page')
self.goToSaveTestPage_button.pack_forget()
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,459,281
|
vibrainium-analytics/ava
|
refs/heads/master
|
/User_Interface/Plot_Page.py
|
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from tkinter import *
# File system access library
import glob, os
# Math functions library
import numpy as np
import matplotlib
# Plotting library canvas tool
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
# Import plotting libraries
import matplotlib.pyplot as pl
import matplotlib, sys
import matplotlib.animation as animation
from matplotlib import style
f = Figure(figsize=(5.65,2.6))
a = f.add_subplot(111)
from sys import argv
import json
# Plot Page
def animate(i):
data = np.genfromtxt(directory['app_data'] + 'DataPlotFile.txt',delimiter=' ')
number_cols = len(data[0])
# Clear subplot for new data
a.clear()
mag_max = 0 # maximum magnitude of magnitude lists
if number_cols > 1:
freq_List = data[:,0]
mag1_List = data[:,1]
plot1 = a.plot(freq_List, mag1_List,'r',label='Plot #1')
if number_cols > 2:
mag2_List = data[:,2]
plot2 = a.plot(freq_List, mag2_List,'g',label='Plot #2')
if number_cols > 3:
mag3_List = data[:,3]
plot3 = a.plot(freq_List, mag3_List,'b',label='Plot #3')
# Create legend from plot label values
a.legend()
class Plot_Page(tk.Frame):
def updatePlot(self, controller):
veh_path = str(directory['veh_path'])
home = str(directory['home'])
# Get selected resolution
resolution = str(self.PlotResolution_Dropdown.get())
# Format resolution to intended text file name based on user-selected input
if resolution == "250 Hz":
resolution = "fft 250Hz.txt"
elif resolution == "125 Hz":
resolution = "fft 125Hz.txt"
elif resolution == "62.5 Hz":
resolution = "fft 62.5Hz.txt"
# Find selected directories
data1_name = str(self.Plot1_Dropdown.get())
data2_name = str(self.Plot2_Dropdown.get())
# Tack on parent directory from current vehicle json file
with open(directory['app_data'] + 'selected_vehicle.json','r') as f:
selected_vehicle = json.load(f)
f.close
# Find directories for vehicles to compare
data1_directory = directory['veh_path'] + selected_vehicle["name"] + '_' + selected_vehicle['model'] + '_' + selected_vehicle['year'] + "/" + data1_name + "/"
data2_directory = directory['veh_path'] + selected_vehicle["name"] + '_' + selected_vehicle['model'] + '_' + selected_vehicle['year'] + "/" + data2_name + "/"
# Find file with specified resolution
for root, dirs, files in os.walk(data1_directory):
if resolution in files:
data1_file = os.path.join(root,resolution)
for root, dirs, files in os.walk(data2_directory):
if resolution in files:
data2_file = os.path.join(root,resolution)
# Extract file contents
data1 = np.loadtxt(data1_file)
data2 = np.loadtxt(data2_file)
# Save 1 x and 2 y terms in DataPlotFile
x1 = data1[:,0]
y1 = data1[:,1]
x2 = data2[:,0]
y2 = data2[:,1]
os.chdir(home)
np.savetxt(directory['app_data'] + 'DataPlotFile.txt', np.column_stack((x1,y1,y2)),fmt='%.3f %.3f %.3f')
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
veh_path = str(directory['veh_path'])
# AVA app controller (app_data access)
self.controller = controller
self.pageLabelFrame=Frame(self, borderwidth=4, relief=GROOVE)
Label(self.pageLabelFrame, text='Plot Page', width=35).pack(side=TOP)
self.pageLabelFrame.pack(pady = (5,5), ipadx = 2, ipady = 2, fill = "x")
goToHomePage_button = ttk.Button(self, text="Go Back",
command=lambda: controller.show_page("Home_Page"))
goToHomePage_button.pack(pady=1,padx=5, side = "left", expand = "no", anchor = "n")
frame1 = LabelFrame(self, text="Interactive Plotting", width=500, height=300, bd=1, borderwidth=4, relief=GROOVE)
frame1.place(relx=1,x = -5, rely=0.1, anchor=NE)
frame2 = LabelFrame(self, text="Plot controls", width=250, height=300, bd=1, borderwidth=4, relief=GROOVE)
frame2.place(relx=0 ,x = 5, rely=0.2, anchor=NW)
frame3 = LabelFrame(self, text="Diagnostics - Relevant Frequencies", width=700, height=100, bd=5, borderwidth=3, relief=GROOVE)
frame3.place(relx=0,x = 5, rely=1, anchor=SW)
canvas = FigureCanvasTkAgg(f, frame1)
canvas.show()
canvas.get_tk_widget().pack(side="right", fill=BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, frame1)
toolbar.update()
canvas._tkcanvas.pack(side=BOTTOM)##, fill=BOTH, expand=True)
# Read currently selected vehicle file
with open(directory['app_data'] + 'selected_vehicle.json','r') as file:
selected_vehicle = json.load(file)
file.close
# Load plots from test results directory
from os import listdir
current_vehicle_directory = directory['veh_path'] + selected_vehicle["name"] + "_" + selected_vehicle['model'] + '_' + selected_vehicle['year'] + '/'
try:
vehicle_filenames = os.listdir(current_vehicle_directory)
except:
os.makedirs(current_vehicle_directory)
vehicle_filenames = os.listdir(current_vehicle_directory)
self.Plot1_Dropdown_Frame = ttk.Labelframe(frame2, text='Plot 1')
self.Plot1_Dropdown = ttk.Combobox(self.Plot1_Dropdown_Frame, values = vehicle_filenames, state='readonly')
#self.Plot1_Dropdown.bind('<<ComboboxSelected>>',self.loadSavedVehicleProfile)
self.Plot1_Dropdown.pack(pady=5,padx=5)
self.Plot1_Dropdown_Frame.pack(side="top",pady=5,padx=5)
self.Plot2_Dropdown_Frame = ttk.Labelframe(frame2, text='Plot 2')
self.Plot2_Dropdown = ttk.Combobox(self.Plot2_Dropdown_Frame, values = vehicle_filenames, state='readonly')
#self.Plot1_Dropdown.bind('<<ComboboxSelected>>',self.loadSavedVehicleProfile)
self.Plot2_Dropdown.pack(pady=5,padx=10)
self.Plot2_Dropdown_Frame.pack(side="top",pady=5,padx=5)
self.PlotResolution_Dropdown_Frame = ttk.Labelframe(frame2, text='Plot Resolution')
self.PlotResolution_Dropdown = ttk.Combobox(self.PlotResolution_Dropdown_Frame, values = ["250 Hz", "125 Hz", "62.5 Hz"], state='readonly')
#self.Plot1_Dropdown.bind('<<ComboboxSelected>>',self.loadSavedVehicleProfile)
self.PlotResolution_Dropdown.pack(pady=5,padx=5)
self.PlotResolution_Dropdown_Frame.pack(side="top",pady=5,padx=5)
self.plot_button = ttk.Button(frame2, text = "Plot!",command = lambda: self.updatePlot(controller))
self.plot_button.pack(side = "top", padx = 5, pady = 5, expand = "no", anchor = "n")
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,459,282
|
vibrainium-analytics/ava
|
refs/heads/master
|
/Signal_Processing/Signal_Process.py
|
import tkinter as tk
from tkinter import ttk
from scipy import signal
import os, json, shutil, math, numpy
import datetime
class Signal_Process(tk.Tk):
with open('directory.json','r') as g:
global directory
directory = json.load(g)
g.close
# create a message box. This will only display if the signal processing takes more than one second
def __init__(self,*args):
tk.Tk.__init__(self,*args)
self.message = tk.Text(self, height=2, width=30)
self.message.pack()
self.message.insert(tk.INSERT, "Processing Data Please Wait")
self.title('Processing')
self.process()
# signal processing function
def process(self):
# get data from .json files
with open(directory['app_data'] + 'test_preferences.json','r') as f:
test_data = json.load(f)
f.close
with open(directory['app_data'] + 'selected_vehicle.json','r') as f:
data1 = json.load(f)
f.close
with open(directory['app_data'] + 'save_test.json','r') as f:
data2 = json.load(f)
f.close
# set AC status and speed status dependancies
if str(data2['idle_status']) == 'Yes':
testnm = '-Idle'
if str(data2['ac_status']) == 'AC On':
testnm = testnm + '-AC'
else:
testnm = 'SteadySpeed-' + str(data2['speed'])
# set directories using data from .json files
now = '{:%Y-%b-%d %H:%M}'.format(datetime.datetime.now())
veh_path = str(directory['veh_path'])
path = veh_path + str(data1['name']) + '_' + str(data1['model']) + '_' + str(data1['year'])
path1 = path + '/' + str(test_data['test_type']) + '/temp/'
path2 = path + '/' + str(test_data['test_type']) + testnm + '/'
if str(test_data['test_type']) == "Diagnostic":
path2 = path + '/unknown_trouble-' + now + '/'
if os.path.exists(path2):
shutil.rmtree(path2)
os.makedirs(path2)
# read magnitude values into array and move raw data to new directory
filename = path1 + 'Three Axes.txt'
filename2 = path2 + 'Three Axes.txt'
f=open(filename,'r')
data=f.readlines()
f.close()
shutil.move(filename,filename2)
shutil.rmtree(path + '/' + str(test_data['test_type']))
mag = numpy.zeros(len(data))
for i in range(0, len(data)-1):
row = data[i]
col = row.split()
mag[i] = col[3]
# calculate weighted average of fft
n = 256 # number of points in the FFT
strt = 1
fnsh = n
runav = 16 # number of FFT's in 8 second weighted average
smpl = mag[strt:fnsh]
# first FFT is outside the average loop so we aren't dividing by zero
freq=numpy.absolute(numpy.fft.rfft(smpl))
freq[0] = 0
# until we have done 16 FFT's it is a simple average
for j in range(1, runav):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*j) + freq1)/(j+1)
# weighted average until end of samples
while (fnsh+n) < len(mag):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*runav) + freq1)/(runav+1)
# normalize fft
s = numpy.sum(freq)
norm = s/(len(freq))
freq = freq / norm
# write output to file with frequency scale
filename2 = path2 + 'fft 250Hz.txt'
for i in range(0, int(n/2)):
j = i+1
hz = float("{0:.1f}".format(j * 500/n))
enrg = str(hz) + ' ' + str(float("{0:.2f}".format(freq[i]))) + '\n'
with open(filename2, 'a') as out:
out.write(enrg)
f.close
# create filter coefficients for zooming in by 2
b, a = signal.butter(20, .5)
# filter magnitude values that were read earlier
mag1 = signal.filtfilt(b, a, mag)
# downsample by 2 to avoid aliasing
stp = int(len(mag)/2)
mag = numpy.zeros(0)
for i in range(1, stp):
mag = numpy.append(mag,mag1[(2*i)-1])
# calculate weighted average of fft
n = 256 # number of points in the FFT
strt = 1
fnsh = n
runav = 8 # number of FFT's in 8 second weighted average
smpl = mag[strt:fnsh]
# first FFT is outside the average loop so we aren't dividing by zero
freq=numpy.absolute(numpy.fft.rfft(smpl))
freq[0] = 0
# until we have done 8 FFT's it is a simple average
for j in range(1, runav):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*j) + freq1)/(j+1)
# weighted average until end of samples
while (fnsh+n) < len(mag):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*runav) + freq1)/(runav+1)
# normalize fft
s = numpy.sum(freq)
norm = s/(len(freq))
freq = freq / norm
# write output to file with frequency scale
filename2 = path2 + 'fft 125Hz.txt'
for i in range(0, int(n/2)):
j = i+1
hz = float("{0:.1f}".format(j * 250/n))
enrg = str(hz) + ' ' + str(float("{0:.2f}".format(freq[i]))) + '\n'
with open(filename2, 'a') as out:
out.write(enrg)
f.close
# create filter coefficients for zooming in by 2
b, a = signal.butter(20, .5)
# filter magnitude values from the previously filtered data
mag1 = signal.filtfilt(b, a, mag)
# downsample by 2 to avoid aliasing
stp = int(len(mag)/2)
mag = numpy.zeros(0)
for i in range(1, stp):
mag = numpy.append(mag,mag1[(2*i)-1])
# calculate weighted average of fft
n = 256 # number of points in the FFT
strt = 1
fnsh = n
runav = 4 # number of FFT's in 8 second weighted average
smpl = mag[strt:fnsh]
# first FFT is outside the average loop so we aren't dividing by zero
freq=numpy.absolute(numpy.fft.rfft(smpl))
freq[0] = 0
# until we have done 4 FFT's it is a simple average
for j in range(1, runav):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*j) + freq1)/(j+1)
# weighted average until end of samples
while (fnsh+n) < len(mag):
strt = fnsh+1
fnsh = fnsh+n
smpl = mag[strt:fnsh]
freq1=numpy.absolute(numpy.fft.rfft(smpl))
freq1[0] = 0
freq = ((freq*runav) + freq1)/(runav+1)
# normalize fft
s = numpy.sum(freq)
norm = s/(len(freq))
freq = freq / norm
# write output to file with frequency scale
filename2 = path2 + 'fft 62.5Hz.txt'
for i in range(0, int(n/2)):
j = i+1
hz = float("{0:.1f}".format(j * 125/n))
enrg = str(hz) + ' ' + str(float("{0:.2f}".format(freq[i]))) + '\n'
with open(filename2, 'a') as out:
out.write(enrg)
f.close
self.destroy()
|
{"/ava.py": ["/User_Interface/Plot_Page.py", "/User_Interface/Home_Page.py", "/User_Interface/Configure_Test_Page.py", "/User_Interface/New_Vehicle_Page.py", "/User_Interface/Test_Is_Running_Page.py", "/User_Interface/Save_Test_Page.py", "/User_Interface/Results_Page.py", "/User_Interface/Tutorial_Main_Page.py", "/User_Interface/About_Page.py", "/User_Interface/Tutorial_Sample_Collection_Page.py"], "/User_Interface/Test_Is_Running_Page.py": ["/Signal_Processing/Delay_Bar.py"], "/Signal_Processing/Delay_Bar.py": ["/Signal_Processing/Sample_Bar.py"], "/User_Interface/Save_Test_Page.py": ["/Signal_Processing/Signal_Process.py"]}
|
40,560,970
|
solfamidasgroup/desarrollo-web
|
refs/heads/master
|
/module003/views.py
|
from application import get_app
from flask_login import login_required, login_user, logout_user, current_user
from flask import render_template, request, redirect, url_for, flash, Blueprint
from sqlalchemy import or_
from models import User, get_db, Course, Assignment
import datetime
db = get_db()
from module003.forms import *
module003 = Blueprint("module003", __name__,static_folder="static",template_folder="templates")
@module003.route('/')
def module003_index():
return render_template("module003_index.html",module='module003')
@module003.route('/create', methods=['GET', 'POST'])
def module003_create():
form = AssignmentCreateForm()
if request.method == 'POST':
try:
course = Course.query.get(form.course_id.data)
assignment = Assignment(title = form.title.data,
body = form.description.data,
date_expire = datetime.datetime.combine(form.date_expire.data, form.time_expire.data),
course_id = course.id,
course_name = course.name,
institution_name = course.institution_name,
user_id=current_user.id)
db.session.add(assignment)
db.session.commit()
flash("Tarea creda con exito")
except:
flash("Error creando tarea")
for course in Course.query.filter_by(user_id=current_user.id):
form.course_id.choices += [(course.id, str(course.id) + ' - ' + course.institution_name + ' - ' + course.name)]
assignments = Assignment.query.filter(Assignment.user_id==current_user.id)
return render_template("module003_create.html",module='module003', form=form, rows=assignments)
@module003.route('/test')
def module003_test():
return 'OK'
|
{"/module003/views.py": ["/module003/forms.py"], "/module002/views.py": ["/module002/forms.py"]}
|
40,665,698
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/Network/LSTM.py
|
import torch.nn as nn
class LSTM_Regression(nn.Module):
"""
使用LSTM进行回归
参数:
- input_size: feature size
- hidden_size: number of hidden units
- output_size: number of output
- num_layers: layers of LSTM to stack
"""
def __init__(self, input_size, hidden_size, output_size=1, num_layers=2):
super().__init__()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, bias=False)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, _x):
x, _ = self.lstm(_x) # _x is input, size (seq_len, batch, input_size)
s, b, h = x.shape # x is output, size (seq_len, batch, hidden_size)
x = x.view(s * b, h)
x = self.fc(x)
x = x.view(s, b, -1) # 把形状改回来
return x
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,665,699
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/Error.py
|
import pandas as pd
from math import sqrt
class pre_error():
'''该类实现计算误差函数'''
def __init__(self, pre_data, true_data):
self.pre_data = pre_data
self.true_data = true_data
def pre_RMSE(self):
dis = self.pre_data - self.true_data
RMSEP = sqrt(sum(sum(dis * dis))) / len(self.pre_data)
return RMSEP
def pre_Rp(self):
A = pd.Series(self.pre_data)
B = pd.Series(self.true_data)
Rp = B.corr(A, method='pearson')
return Rp
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,665,700
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/main.py
|
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import torch.optim as optim
import torch
from utils.dataloader import dataload
from Network.LSTM import LSTM_Regression
import torch.nn as nn
from test import predicate
from Error import pre_error
from torchvision import transforms
import pandas as pd
import numpy as np
from torch.utils.data import DataLoader
from torch.autograd import Variable
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
spilt_size = 0.2 # 训练集和测试集的分割比例
train_x, train_y, test_x, test_y = dataload(spilt_size) # 载入数据
'''训练参数设置'''
model = LSTM_Regression(3648, 8, output_size=1, num_layers=2)
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
train_x = train_x.type(torch.FloatTensor)
train_y = train_y.type(torch.FloatTensor)
'''开始训练'''
for i in range(1000):
out = model(train_x)
loss = loss_function(out, train_y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
if (i + 1) % 100 == 0:
print('Epoch: {}, Loss:{:.5f}'.format((i + 1), loss.item()))
predicate(model, test_x, test_y) # 测试
# def predicate(model, test_x, test_y):
# test_x = test_x.type(torch.FloatTensor)
# test_y = test_y.type(torch.FloatTensor)
# model = model.eval()
# pre_test = model(test_x)
# pre_test = pre_test.view(-1).data.numpy()
# print('预测结果:{}\n'.format(pre_test))
# # print('实际结果:{}'.format(test_y))
# '''数据读取部分'''
# input = pd.read_excel("E:\SeaFile\Grade2_Tsinghua\华慧芯实习\Test_data_total\Total data.xlsx")
# input_array = input.to_numpy()
# input_array = np.delete(input_array, [0, 1, 2, 3], 1)
#
# output = pd.read_excel("E:\SeaFile\Grade2_Tsinghua\华慧芯实习\Test_data_total\label_new_total.xlsx")
# output_array = output.to_numpy()
# output_array = np.delete(output_array, [1, 2], 0)
# # 测试用例
# x_train, x_test, y_train, y_test = train_test_split(input_array.T, output_array.T, test_size=0.2, random_state=0)
#
# scaler = StandardScaler() # 标准化转换
# scaler.fit(x_train) # 训练标准化对象
# x_train = scaler.transform(x_train) # 转换数据集
#
# scaler1 = StandardScaler() # 标准化转换
# scaler1.fit(x_test) # 训练标准化对象
# x_test = scaler1.transform(x_test) # 转换数据集
#
# x_train = x_train.reshape(-1, 1, 3648) # 3648是特征维度即光谱通道个数
# y_train = y_train.reshape(-1, 1, 1)
#
# x_test = x_test.reshape(-1, 1, 3648) # 3648是特征维度
# y_test = y_test.reshape(-1, 1, 1)
#
# train_x = torch.from_numpy(x_train)
# train_y = torch.from_numpy(y_train)
# test_x = torch.from_numpy(x_test)
# test_y = torch.from_numpy(y_test)
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,665,701
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/test.py
|
from torch import FloatTensor
from Error import pre_error
def predicate(model, test_x, test_y):
test_x = test_x.type(FloatTensor)
test_y = test_y.type(FloatTensor)
model = model.eval()
pre_test = model(test_x)
pre_test = pre_test.view(-1).data.numpy()
print('预测结果:{}\n'.format(pre_test))
# print('实际结果:{}'.format(test_y))
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,665,702
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/train.py
|
from Error import pre_error
def train(epoch,model,train_x,train_y,loss_function,optimizer):
out = model(train_x)
loss = loss_function(out, train_y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
if (epoch+ 1) % 100 == 0:
print('Epoch: {}, Loss:{:.5f}'.format((epoch + 1), loss.item()))
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,665,703
|
liuw20/LSTM_Fruit_simple
|
refs/heads/master
|
/utils/dataloader.py
|
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import torch
def dataload(spilt_size):
'''数据读取部分'''
input = pd.read_excel("E:\SeaFile\Grade2_Tsinghua\华慧芯实习\Test_data_total\Total data.xlsx")
input_array = input.to_numpy()
input_array = np.delete(input_array, [0, 1, 2, 3], 1)
output = pd.read_excel("E:\SeaFile\Grade2_Tsinghua\华慧芯实习\Test_data_total\label_new_total.xlsx")
output_array = output.to_numpy()
output_array = np.delete(output_array, [1, 2], 0)
# 测试用例
x_train, x_test, y_train, y_test = train_test_split(input_array.T, output_array.T, test_size=spilt_size, random_state=0)
scaler = StandardScaler() # 标准化转换
scaler.fit(x_train) # 训练标准化对象
x_train = scaler.transform(x_train) # 转换数据集
scaler1 = StandardScaler() # 标准化转换
scaler1.fit(x_test) # 训练标准化对象
x_test = scaler1.transform(x_test) # 转换数据集
x_train = x_train.reshape(-1, 1, 3648) # 3648是特征维度即光谱通道个数
y_train = y_train.reshape(-1, 1, 1)
x_test = x_test.reshape(-1, 1, 3648) # 3648是特征维度
y_test = y_test.reshape(-1, 1, 1)
train_x = torch.from_numpy(x_train) # 转换为Tensor
train_y = torch.from_numpy(y_train)
test_x = torch.from_numpy(x_test)
test_y = torch.from_numpy(y_test)
return train_x,train_y,test_x,test_y
|
{"/main.py": ["/utils/dataloader.py", "/Network/LSTM.py", "/test.py", "/Error.py"], "/test.py": ["/Error.py"], "/train.py": ["/Error.py"]}
|
40,671,526
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0008_auto_20171009_1903.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-10-09 10:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0007_auto_20171009_1842'),
]
operations = [
migrations.RemoveField(
model_name='follow',
name='full_name',
),
migrations.AlterField(
model_name='follow',
name='object_pk',
field=models.BigIntegerField(),
),
migrations.AlterField(
model_name='follow',
name='user_pk',
field=models.BigIntegerField(),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,527
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/web/models.py
|
# -*- coding: utf-8 -*-
import sys, os
reload(sys)
sys.setdefaultencoding('utf-8')
from django.db import models
from django.utils import timezone
from crawler.models import *
class Subscriber(models.Model):
product = models.CharField(max_length=200)
email = models.EmailField()
first_name = models.CharField(max_length=200)
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,528
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0021_auto_20171127_2155.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-27 12:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0020_auto_20171127_2152'),
]
operations = [
migrations.AlterField(
model_name='user',
name='count_DM_sent',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='user',
name='num_likes',
field=models.IntegerField(null=True),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,529
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0017_auto_20171114_2310.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-14 14:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0016_auto_20171103_2334'),
]
operations = [
migrations.AddField(
model_name='user',
name='engagement_rate',
field=models.DecimalField(decimal_places=20, max_digits=22, null=True),
),
migrations.AddField(
model_name='user',
name='num_commenters',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='user',
name='num_likes',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='user',
name='num_views',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='user',
name='remark',
field=models.TextField(null=True),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,530
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0014_auto_20171024_2159.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-24 12:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0013_auto_20171024_2157'),
]
operations = [
migrations.AlterField(
model_name='follow',
name='object_pk',
field=models.BigIntegerField(db_index=True),
),
migrations.AlterField(
model_name='follow',
name='user_pk',
field=models.BigIntegerField(db_index=True),
),
migrations.AlterField(
model_name='hashtag_dictionary',
name='user_pk',
field=models.BigIntegerField(db_index=True),
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(db_index=True, max_length=200),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,531
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/views.py
|
#-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from crawler.models import Influencer, Post, User, Follow, Hashtag_Dictionary, ScoreBoard
from django.db.models import Q
import pdb, datetime, csv, os, sys, requests, json, time, yaml
from django.utils import timezone
from auth import *
#from local_data import *
from langdetect import *
sys.path.append(os.path.abspath('./crawler/Instagram-API-python'))
from InstagramAPI import InstagramAPI
from DM_format import *
import networkx as nx
from networkx.readwrite import json_graph
#import http_server
#host_ip = str(requests.get('http://ip.42.pl/raw').text)
#crawler_domain = "http://"+host_ip + "/"
crawler_domain = "http://localhost:8000/"
api = InstagramAPI(api_id, api_pwd)
api.s.proxies = proxies
api.login() # login
# 2, 1, 3, 5, 4
def influencer_list(request):
influencers = Influencer.objects.order_by('created_date')
return render(request, 'crawler/influencer_list.html', {'influencers': influencers})
def export_hashtag_dic(request):
target_user_pk= request.GET.get('user_pk', '')
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="hashtag_dic.csv"'
writer = csv.writer(response)
writer.writerow(['user id', 'hashtag', 'count'])
influ_dic_list = Hashtag_Dictionary.objects.filter(user_pk = target_user_pk).order_by('-count')[:10]
for dic in influ_dic_list:
line_list = [dic.user_pk, dic.hashtag, dic.count]
line_list = [str(ele) for ele in line_list]
writer.writerow(line_list)
follows = Follow.objects.filter(follow_status='ed', object_pk = target_user_pk)
follower_pk_list = [follow.user_pk for follow in follows]
dic_list = Hashtag_Dictionary.objects.filter(user_pk__in=follower_pk_list)
print "query is finished. size is " + str(len(dic_list))
user_tag_count = {}
for dic in dic_list:
if dic.user_pk in user_tag_count:
user_tag_count[dic.user_pk][dic.hashtag] = dic.count
else:
user_tag_count[dic.user_pk] = {dic.hashtag: dic.count}
print "Start to write"
for user, tag_count in user_tag_count.iteritems():
sorted_tag = sorted(tag_count, key=tag_count.get, reverse=True)[:2]
for tag in sorted_tag:
line_list = [user, tag, tag_count[tag]]
line_list = [str(ele) for ele in line_list]
writer.writerow(line_list)
return response
def export_follow_csv(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="follow.csv"'
writer = csv.writer(response)
writer.writerow(['target user pk', 'ing/ed', 'by username', 'user pk', 'is verified', 'is private', 'is favorite'])
follows = Follow.objects.all()
for follow in follows:
line_list = [follow.object_pk, follow.follow_status, follow.username, follow.user_pk, follow.is_verified, follow.is_private, follow.is_favorite]
line_list = [str(ele) for ele in line_list]
writer.writerow(line_list)
return response
def user_follow(request):
target_username= request.GET.get('username', '')
target_user_pk= request.GET.get('target_user_pk', '')
max_id= request.GET.get('max_id', '')
next_function= request.GET.get('next_function', '')
recursive_step= request.GET.get('recursive_step', '1')
kor_check= request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '10000'))
# For develop in local.
if target_user_pk == "":
if target_username == "": return HttpResponseRedirect("/crawl/follow_list")
target_username_list = target_username.split(",")
target_user_pk_list = []
for target_username in target_username_list:
#target_user_pk = user_by_name(target_username).user_pk
response = requests.get(crawler_domain+"crawl/user_by_name?recursive=False&username={}&kor_check={}&influ_thresold={}".format(target_username, kor_check, influ_thresold))
json_response = json.loads(response.text)
if json_response["success"]:
target_user_pk = json_response["target_user_pk"]
target_user_pk_list.append(target_user_pk)
else:
target_user_pk_list = target_user_pk.split(",")
num_target_users = len(target_user_pk_list)
counter = 0
for target_user_pk in target_user_pk_list:
counter += 1
print counter, ' / ', num_target_users
while max_id != "end":
while True:
response = requests.get(crawler_domain+"crawl/followers/"+str(target_user_pk)+"/?max_id={}&recursive_step={}".format(max_id, recursive_step))
try:
json_response = json.loads(response.text)
break
except:
print "Some json data is wrong."
print response
print response.text
continue
max_id = json_response["max_id"]
max_id = ""
if next_function=='check_influencer': return HttpResponseRedirect('/crawl/check_influencer?object_pk={}&recursive_step={}&kor_check={}&influ_thresold={}'.format(target_user_pk, recursive_step, kor_check, influ_thresold))
else: return JsonResponse({'sucess': True})
def check_influencer(request):
object_pk= request.GET.get('object_pk', '')
recursive_step = request.GET.get('recursive_step', '1')
last_user_pk= request.GET.get('last_user_pk', '')
kor_check= request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '10000'))
skip_flag = False
if last_user_pk != '': skip_flag = True
followers = Follow.objects.filter(follow_status='ed', object_pk =object_pk)
num_followers = followers.count()
for index, follower in enumerate(followers):
if skip_flag:
if follower.user_pk == int(last_user_pk):
skip_flag = False
print follower.username
continue
request_counter = 0
while True:
response = requests.get(crawler_domain+"crawl/user_by_name?recursive_step={}&recursive={}&username={}&kor_check={}&influ_thresold={}".format(recursive_step, 'True',follower.username, kor_check, influ_thresold))
try:
json_response = json.loads(response.text)
break
except:
request_counter += 1
if request_counter > 5: break
print "Some json data is wrong."
print response.text
continue
if request_counter > 5: continue
print str(index)+ " / " + str(num_followers)
if json_response["success"] == False:
if json_response["target_user_pk"] == "Not Influencer": follower.delete()
continue
else:
print "Caught Influencer."
if recursive_step == '2': continue
recursive_step = str(int(recursive_step)+1)
requests.get(crawler_domain+"crawl/user_follow?next_function={}&target_user_pk={}&recursive_step={}&kor_check={}&influ_thresold={}".format("check_influencer", str(json_response["target_user_pk"]), recursive_step, kor_check, influ_thresold))
recursive_step = str(int(recursive_step)-1)
return JsonResponse({'success': True})
def start_hashtag_dictionary(request):
username = request.GET.get('username', '')
influencer = user_by_name(username)
hashtag_dictionary(username, influencer.user_pk)
curl_url = "https://www.instagram.com/"+username+"/?__a=1"
response = requests.get(curl_url, proxies=proxies)
media_json = response.json()["user"]["media"]
follower_set = set()
followers = Follow.objects.filter(follow_status='ed', object_pk = influencer.user_pk)
for follower in followers:
follower_set.add(follower.user_pk)
likers = set()
for node in media_json["nodes"]:
media_id = node["id"]
api.getMediaLikers(media_id)
response_json = api.LastJson
for user in response_json['users']:
if user['pk'] in follower_set: likers.add((user['username'], user['pk']))
total_liker_number = len(likers)
for num, liker in enumerate(likers):
print "/".join((str(num), str(total_liker_number)))
hashtag_dictionary(liker[0], liker[1])
# Take a follower to get hashtag list.
def hashtag_dictionary(username, user_pk):
curl_url = "https://www.instagram.com/"+username+"/?__a=1"
response = requests.get(curl_url, proxies=proxies)
try:
media_json = response.json()["user"]["media"]
except:
print response
return True
# It should be fixed if these code is very necessary.
for node in media_json["nodes"]:
media_id = node["id"]
url_code = node["code"]
#if "caption" in node: hash_tag_count = node["caption"].count("#")
if "caption" in node:
caption_hashtag_list = extract_hash_tags(node["caption"])
for hashtag in caption_hashtag_list:
save_hashtag_dic(user_pk, hashtag, url_code)
requests.get("{crawler_domain}crawl/api_hashtag_dic?media_id={media_id}&user_pk={user_pk}&url_code={url_code}".format(crawler_domain=crawler_domain, media_id=media_id, user_pk=user_pk, url_code=url_code))
def api_hashtag_dic(request):
media_id = request.GET.get('media_id', '')
user_pk = request.GET.get('user_pk', '')
url_code = request.GET.get('url_code', '')
api.getMediaComments(media_id)
response_json = api.LastJson
if not 'comments' in response_json: return JsonResponse({'success': 'no comments'})
comments = response_json['comments']
for comment in comments:
if user_pk == comment['user_id']:
influ_comments = comment['text']
comment_hashtag_list = extract_hash_tags(influ_comments)
for hashtag in comment_hashtag_list:
save_hashtag_dic(user_pk, hashtag, url_code)
return JsonResponse({'success': True})
def save_hashtag_dic(user_pk, hashtag, url_code):
if Hashtag_Dictionary.objects.filter(hashtag = hashtag, user_pk = user_pk).exists():
hashtag_dic = Hashtag_Dictionary.objects.get(hashtag = hashtag, user_pk = user_pk)
if not url_code in hashtag_dic.code_list:
hashtag_dic.add_count(1, url_code)
else:
hashtag_dic = Hashtag_Dictionary(created_date=timezone.now())
hashtag_dic.user_pk = user_pk
hashtag_dic.hashtag = hashtag
hashtag_dic.count = 1
hashtag_dic.code_list = url_code
try:
hashtag_dic.save()
except:
print '!!!!!!!!!!!!!!!!!!'
print hashtag
print '!!!!!!!!!!!!!!!!!!'
def extract_hash_tags(s):
hashtag_set = set()
word_list = s.split('#')
for word in word_list:
raw_hashtag = word.split()
if len(raw_hashtag) == 0: continue
hashtag_set.add(raw_hashtag[0])
return hashtag_set
def user_by_name(request):
username = request.GET.get("username", "")
recursive = request.GET.get("recursive", 'False')
kor_check = request.GET.get("kor_check", 't')
influ_thresold = int(request.GET.get("influ_thresold", '10000'))
if User.objects.count() > 400000: return JsonResponse({'success': False, 'target_user_pk':"FULL"})
if User.objects.filter(username = username).exists():
if recursive == 'False':
return JsonResponse({'success': True, 'target_user_pk':User.objects.get(username = username).user_pk})
else:
return JsonResponse({'success': False, 'target_user_pk':'already visited'})
else:
api.searchUsername(username)
try:
user_info = api.LastJson["user"]
except:
print api.LastJson
return JsonResponse({'success': False, 'target_user_pk':"API FAIL"})
if user_info["follower_count"] >= influ_thresold:
if kor_check == 't':
if not is_korean(username): return JsonResponse({'success': False, 'target_user_pk': 'Not korean'})
user = User(created_date=timezone.now())
user.username = user_info["username"]
user.usertags_count = user_info["usertags_count"]
user.media_count = user_info["media_count"]
user.following_count = user_info["following_count"]
user.follower_count = user_info["follower_count"]
user.is_business = user_info["is_business"]
user.has_chaining = user_info["has_chaining"]
if "geo_media_count" in user_info : user.geo_media_count = user_info["geo_media_count"]
else : user.geo_media_count = 0
user.user_pk = user_info["pk"]
user.is_verified = user_info["is_verified"]
user.is_private = user_info["is_private"]
if "is_favorite" in user_info: user.is_favorite = user_info["is_favorite"]
else: user.is_favorite = False
user.external_url = user_info["external_url"]
user.save()
print "Saved"
return JsonResponse({'success': True, 'target_user_pk':user.user_pk})
else:
return JsonResponse({'success': False, 'target_user_pk':"Not Influencer"})
def is_korean(username):
curl_url = "https://www.instagram.com/"+username+"/?__a=1"
response = requests.get(curl_url, proxies=proxies)
media_json = response.json()["user"]["media"]
for node in media_json["nodes"]:
try:
if detect(node["caption"]) == 'ko':
print 'korean'
return True
except:
continue
print 'not korean'
return False
def followers(request, target_user_pk):
max_id = request.GET.get('max_id', '')
try:
if max_id == "": api.getUserFollowers(target_user_pk)
else: api.getUserFollowers(target_user_pk, maxid=max_id)
followers = api.LastJson
except:
print "api response is wrong so return."
return JsonResponse({'max_id': max_id})
for follower in followers["users"]:
if Follow.objects.filter(user_pk = follower["pk"], object_pk = target_user_pk, follow_status='ed').exists(): continue
follow = Follow(created_date=timezone.now())
follow.object_pk = target_user_pk
follow.follow_status = 'ed'
follow.username = follower["username"]
follow.full_name = follower["full_name"]
follow.user_pk = follower["pk"]
follow.is_verified = follower["is_verified"]
follow.is_private = follower["is_private"]
if "is_favorite" in follower: follow.is_favorite = follower["is_favorite"]
else: follow.is_favorite = False
follow.save()
if "next_max_id" in followers:
max_id = followers["next_max_id"]
else:
max_id = "end"
return JsonResponse({'max_id': max_id})
def follow_list(request):
follow_list = Follow.objects.order_by('created_date')[:10]
return render(request, 'crawler/follow_list.html', {'follow_list': follow_list})
def start_hashtag_posts(request):
hashtag = request.GET.get("hashtag", '')
max_id = request.GET.get('max_id', '')
kor_check = request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '10000'))
post_count = int(request.GET.get("post_count", '0'))
hashtag_list = hashtag.split(',')
for hashtag in hashtag_list:
while max_id != 'end':
response = requests.get(crawler_domain+"crawl/hashtag_posts?hashtag={}&max_id={}&kor_check={}&influ_thresold={}&post_count={}".format(hashtag, max_id, kor_check, influ_thresold, post_count))
result = json.loads(response.text)
if result['success']: max_id = result["next_max_id"]
else: time.sleep(10)
post_count = result["post_count"]
print "post_count: ", post_count
max_id =""
print "post_count: ", post_count
return JsonResponse({'success':True})
def crawl_hashtag_posts(request):
hashtag = request.GET.get("hashtag", '')
max_id = request.GET.get('max_id', '')
kor_check = request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '10000'))
post_count = int(request.GET.get("post_count", '0'))
if max_id == "":
api.getHashtagFeed(hashtag)
else: api.getHashtagFeed(hashtag, maxid=max_id)
hashtag_metadata = api.LastJson
if api.LastResponse.status_code != 200:
return JsonResponse({'success':False, 'post_count': post_count})
if "ranked_items" in hashtag_metadata:
items = hashtag_metadata["ranked_items"]
post_count = parse_item(items, kor_check, influ_thresold, post_count)
if "items" in hashtag_metadata:
items = hashtag_metadata["items"]
post_count = parse_item(items, kor_check, influ_thresold, post_count)
if "next_max_id" in hashtag_metadata:
max_id = hashtag_metadata["next_max_id"]
return JsonResponse({'success':True, 'next_max_id': max_id, 'post_count': post_count})
else:
return JsonResponse({'success':True, 'next_max_id': 'end', 'post_count': post_count})
def parse_item(items, kor_check, influ_thresold, post_count):
for item in items:
# Only get 2017 data.
created_at = item['taken_at']
if datetime.datetime.fromtimestamp(created_at).year != 2017 :
print 'not in 2017, created_at: ',created_at
continue
post_count += 1
user_id = item["user"]["username"]
response = requests.get(crawler_domain+"crawl/user_by_name?recursive=False&username={}&kor_check={}&influ_thresold={}".format(user_id, kor_check, influ_thresold))
user_info = json.loads(response.text)
if not user_info["success"] : continue
if "comment_count" in item: comment_count = item["comment_count"]
else: comment_count = 0
if "view_count" in item: view_count = item["view_count"]
else: view_count = 0
if "like_count" in item: like_count = item["like_count"]
else: like_count = 0
if "code" in item: url = "https://www.instagram.com/p/"+item["code"]
else: url =""
influencer = User.objects.get(user_pk = user_info['target_user_pk'])
engagement_rate = float(comment_count + like_count) / influencer.follower_count
if engagement_rate > influencer.engagement_rate:
influencer.engagement_rate = engagement_rate
influencer.num_commenters = comment_count
influencer.num_views = view_count
influencer.num_likes = like_count
influencer.remark = url
influencer.save()
return post_count
def following(request):
username= request.GET.get('username', '')
target_user_pk= request.GET.get('target_user_pk', '')
max_id= request.GET.get('max_id', '')
kor_check= request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '0'))
campaign= request.GET.get('campaign', '')
# For develop in local.
if target_user_pk == "":
if username == "": return JsonResponse({'success': False})
username_list = username.split(",")
target_user_pk_list = []
for username in username_list:
while True:
response = requests.get(crawler_domain+"crawl/user_by_name?recursive=False&username={}&kor_check={}&influ_thresold={}".format(username, kor_check, influ_thresold))
json_response = json.loads(response.text)
if json_response["success"]:
target_user_pk = json_response["target_user_pk"]
target_user_pk_list.append(target_user_pk)
break
else:
target_user_pk_list = target_user_pk.split(",")
num_target_users = len(target_user_pk_list)
counter = 0
for target_user_pk in target_user_pk_list:
counter += 1
print counter, ' : ', num_target_users
if campaign != '':
user = User.objects.get(user_pk = target_user_pk)
user.campaign_kind = campaign
user.save()
while max_id != "end":
while True:
response = requests.get(crawler_domain+"crawl/api_following/"+str(target_user_pk)+"/?max_id={}".format(max_id))
try:
json_response = json.loads(response.text)
break
except:
print "Some json data is wrong."
print response
print response.text
continue
max_id = json_response["max_id"]
max_id = ''
return JsonResponse({"success": True})
def api_following(request, target_user_pk):
max_id = request.GET.get('max_id', '')
try:
if max_id == "": api.getUserFollowings(target_user_pk)
else: api.getUserFollowings(target_user_pk, maxid=max_id)
following = api.LastJson
except:
print "api response is wrong so return."
return JsonResponse({'max_id': max_id})
for each_following in following["users"]:
if Follow.objects.filter(user_pk = each_following["pk"], object_pk = target_user_pk, follow_status='ing').exists(): continue
follow = Follow(created_date=timezone.now())
follow.object_pk = target_user_pk
follow.follow_status = 'ing'
follow.username = each_following["username"]
follow.full_name = each_following["full_name"]
follow.user_pk = each_following["pk"]
follow.is_verified = each_following["is_verified"]
follow.is_private = each_following["is_private"]
if "is_favorite" in each_following: follow.is_favorite = each_following["is_favorite"]
else: follow.is_favorite = False
follow.save()
if "next_max_id" in following:
max_id = following["next_max_id"]
else:
max_id = "end"
return JsonResponse({'max_id': max_id})
def from_file_user_by_name(request):
kor_check= request.GET.get('kor_check', 't')
influ_thresold = int(request.GET.get("influ_thresold", '1000'))
file_path = "/Users/jack/roka/starlight/starlight/data/animal_hashtag_potential_influ.sort"
with open(file_path, 'r') as read_f:
counter = 0
############################
len_file = '207848'
############################
for line in read_f:
counter += 1
print counter, '/ '+len_file
line_list = line.strip().split(' ')
if len(line_list) < 2: continue
following_count = int(line_list[0])
username = line_list[1]
############################
if following_count < 5: continue
############################
request_counter = 0
while True:
response = requests.get(crawler_domain+"crawl/user_by_name?username={}&kor_check={}&influ_thresold={}".format(username, kor_check, influ_thresold))
try:
json_response = json.loads(response.text)
break
except:
request_counter += 1
if request_counter > 5: break
print "Some json data is wrong."
print response.text
continue
if request_counter > 5: continue
if json_response["success"]:
target_user_pk = json_response["target_user_pk"]
influencer = User.objects.get(user_pk = target_user_pk)
influencer.remark = 'animal_hashtag_potential_influencer'
influencer.save()
def calculate_engagement(request):
check_follow = request.GET.get('check_follow', 'f')
target_user_pk = request.GET.get('target_user_pk', '')
#users = User.objects.filter(Q(remark='animal_supporter') | Q(remark='animal_followed_influencer'))
#users = User.objects.filter(remark='animal_hashtag_potential_influencer')
user_pks = target_user_pk.split(',')
#num_users = users.count()
num_users = len(user_pks)
counter = 0
for user_pk in user_pks:
counter += 1
print counter , ' / ', num_users
request_counter = 0
while True:
response = requests.get(crawler_domain+"crawl/__a_engagement?user_pk={}&check_follow={}".format(user_pk, check_follow))
try:
json_response = json.loads(response.text)
break
except:
request_counter += 1
if request_counter > 5: break
print "Some json data is wrong."
print response.text
continue
if request_counter > 5: continue
return JsonResponse({"success":True})
def __a_engagement(request):
user_pk= int(request.GET.get('user_pk', ''))
check_follow = request.GET.get('check_follow', 'f')
user = User.objects.get(user_pk = user_pk)
if check_follow == 't':
followers = Follow.objects.filter(follow_status='ed', object_pk = user_pk)
follower_names = [follower.username for follower in followers]
if len(follower_names) == 0 :
return JsonResponse({"success":"no followers"})
curl_url = "https://www.instagram.com/"+user.username+"/?__a=1"
response = requests.get(curl_url, proxies=proxies)
media_json = response.json()["user"]["media"]
comment_count = 0
likes_count = 0
views_count = 0
video_count = 0
post_count = 0
num_follower_likers = 0
for node in media_json["nodes"]:
post_count += 1
if not "id" in node: continue
media_id = node["id"]
comment_count += node['comments']['count']
likes_count += node['likes']['count']
if node['is_video']:
video_count += 1
views_count += node['video_views']
if check_follow == 't':
api.getMediaLikers(str(media_id))
response_json = api.LastJson
# After using this code for handling exception.
#try:
# user_info = api.LastJson["user"]
#except:
# print api.LastJson
# return JsonResponse({'success': False, 'target_user_pk':"API FAIL"})
post_liker_set = set()
likers = response_json["users"]
for liker in likers:
post_liker_set.add(liker["username"])
follower_likers = post_liker_set.intersection(follower_names)
num_follower_likers += len(follower_likers)
if post_count > 0 :
num_commenters = float(comment_count) / post_count
num_likes = float(likes_count) / post_count
num_follower_likes = float(num_follower_likers) / post_count
else:
num_commenters = 0
num_likes = 0
num_follower_likes = 0
if video_count > 0 :
num_views = float(views_count) / video_count
else:
num_views = 0
user.num_commenters = num_commenters
user.num_likes = num_likes
user.num_views = num_views
user.num_follower_likes = num_follower_likes
user.engagement_rate = float(num_commenters + num_likes + num_views) / user.follower_count
user.save()
return JsonResponse({"success": True})
def posts(request):
username = request.GET.get('username', '')
do_crawl = True
max_id = ""
counter = 0
while do_crawl:
counter += 1
print "max_id counter: ", counter
curl_url = "https://www.instagram.com/"+username+"/?__a=1&max_id="+max_id
response = requests.get(curl_url, proxies=proxies)
media_json = response.json()["user"]["media"]
for node in media_json["nodes"]:
post = Post(created_date=timezone.now())
post.user_id = username
post.num_likes = node['likes']['count']
post.num_commenters = node['comments']['count']
if node['is_video']: post.num_views = node['video_views']
#post.captions = node["caption"]
post.save()
if media_json["page_info"]["has_next_page"]:
max_id = media_json["page_info"]["end_cursor"]
do_crawl = True
else:
print "Happy finished"
do_crawl = False
return JsonResponse({"success": True})
def SendDM(request):
user_pk_list = request.GET.get('user_pk_list', '')
by_hashtag = request.GET.get('by_hashtag', 'f')
user_pk_list = user_pk_list.split(',')
progress = 0
total_users = len(user_pk_list)
for user_pk in user_pk_list:
progress += 1
print 'Progress: ', progress, '/', total_users
user = User.objects.get(user_pk = user_pk)
if by_hashtag == 'f':
msg = graph_msg(user.username)
else:
msg = hastag_msg(user.username)
while True:
api.sendMessage(str(user_pk), msg)
if api.LastResponse.status_code != 200:
print(api.LastJson)
print "Fail to Send So We need to wait 20 min"
time.sleep(60*60*2)
continue
else:
user.count_DM_sent += 1
user.save()
time.sleep(15)
break
return JsonResponse({"success":True})
def make_graph(user_pk_set, graph_name="no-title.yaml", save=True):
G = nx.DiGraph()
counter = 0
for user_pk in user_pk_set:
counter += 1
print "progress: ", counter, '/', len(user_pk_set)
user = User.objects.get(user_pk = user_pk)
G.add_node(user_pk)
G.node[user_pk]['username'] = user.username
G.node[user_pk]['follower_count'] = user.follower_count
G.node[user_pk]['engagement_rate'] = float(user.num_commenters+user.num_likes) / user.follower_count
following_list = Follow.objects.filter(object_pk=user_pk, follow_status='ing').values_list('user_pk', flat=True)
meaningful_following_set = user_pk_set.intersection(following_list)
if len(meaningful_following_set) == 0: continue
edge_list = []
for followed_user_pk in meaningful_following_set:
edge_list.append((user_pk, followed_user_pk))
G.add_edges_from(edge_list)
if save:
nx.write_yaml(G, graph_name)
else: return G
def apply_dynamic_pagerank(G):
pk_username = nx.get_node_attributes(G, 'username')
pk_follower = nx.get_node_attributes(G, 'follower_count')
pk_engage_rate = {user_pk: float(engage_rate) for user_pk, engage_rate in nx.get_node_attributes(G, 'engagement_rate').iteritems()}
pagerank_dic = nx.pagerank(G)
ranked_list = sorted(pagerank_dic.items(), key=lambda x:-x[1])
ranked = [(pk_username[user_pk], user_pk, point, pk_follower[user_pk], pk_engage_rate[user_pk]) for user_pk, point in ranked_list[:100]]
follower_pagerank_dic = nx.pagerank(G, personalization=pk_follower, nstart=pk_follower)
follower_ranked_list = sorted(follower_pagerank_dic.items(), key=lambda x:-x[1])
follower_ranked = [(pk_username[user_pk], user_pk, point, pk_follower[user_pk], pk_engage_rate[user_pk]) for user_pk, point in follower_ranked_list[:100]]
engage_rate_pagerank_dic = nx.pagerank(G, personalization=pk_engage_rate, nstart=pk_engage_rate)
engage_rate_ranked_list = sorted(engage_rate_pagerank_dic.items(), key=lambda x:-x[1])
engage_rate_ranked = [(pk_username[user_pk], user_pk, point, pk_follower[user_pk], pk_engage_rate[user_pk]) for user_pk, point in engage_rate_ranked_list[:100]]
return ranked, follower_ranked, engage_rate_ranked
def register_on_scoreboard(score_list, graph_type, brandname):
for username, user_pk, point, follower, engage_rate in score_list:
if ScoreBoard.objects.filter(user_pk = user_pk, brandname=brandname, graph_type=graph_type).exists():
score_row = ScoreBoard.objects.get(user_pk = user_pk, brandname=brandname, graph_type=graph_type)
score_row.page_rank = float(point)
score_row.save()
else:
score_row = ScoreBoard(created_date=timezone.now())
score_row.user_pk = int(user_pk)
score_row.brandname = brandname
score_row.page_rank = float(point)
score_row.graph_type = graph_type
score_row.save()
def pagerank(request):
brandname = request.GET.get('brandname', 'dog')
user_pk_set = set(User.objects.filter(campaign_kind='dog').order_by('-follower_count')[:100].values_list('user_pk', flat=True))
# After log campaign in campaign_kind of user table such as 'dog_basic' or 'dog_hashtag'
hashtag_user_pk_set = set(User.objects.filter(campaign_kind='dog').order_by('-follower_count')[:100].values_list('user_pk', flat=True))
if not os.path.exists('dog_graph.yaml') : make_graph(user_pk_set, 'dog_graph.yaml')
if not os.path.exists('hashtag_dog_graph.yaml') : make_graph(hashtag_user_pk_set, 'hashtag_dog_graph.yaml')
G = nx.read_yaml('dog_graph.yaml')
hashtag_G = nx.read_yaml('hashtag_dog_graph.yaml')
ranked, follower_ranked, engage_rate_ranked = apply_dynamic_pagerank(G)
hashtag_ranked, hashtag_follower_ranked, hashtag_engage_rate_ranked = apply_dynamic_pagerank(hashtag_G)
register_on_scoreboard(ranked, 'basic', brandname)
register_on_scoreboard(hashtag_ranked, 'hashtag', brandname)
return JsonResponse({"success": True})
def diversity(request):
user_pk_list = request.GET.get('user_pk_list', '')
user_pk_list = [float(ele) for ele in user_pk_list.split(',')]
pk_pk_diversity = {}
counter = 0
for p in user_pk_list:
counter += 1
print counter, '/', len(user_pk_list)
for q in user_pk_list:
if p == q: continue
p_username = User.objects.get(user_pk=p).username
q_username = User.objects.get(user_pk=q).username
if p_username in pk_pk_diversity:
if q_username not in pk_pk_diversity[p_username]:
q_follower_set = set(Follow.objects.filter(object_pk=q, follow_status='ed').values_list('user_pk', flat=True))
p_follower_set = set(Follow.objects.filter(object_pk=p, follow_status='ed').values_list('user_pk', flat=True))
if len(p_follower_set) == 0 or len(q_follower_set) ==0: continue
union = p_follower_set.union(q_follower_set)
intersection = p_follower_set.intersection(q_follower_set)
diversity = float(len(intersection))/len(union)
pk_pk_diversity[p_username][q_username] = diversity
if q_username in pk_pk_diversity:
pk_pk_diversity[q_username][p_username] = diversity
else:
pk_pk_diversity[q_username] = dict()
pk_pk_diversity[q_username][p_username] = diversity
else:
p_follower_set = set(Follow.objects.filter(object_pk=p, follow_status='ed').values_list('user_pk', flat=True))
q_follower_set = set(Follow.objects.filter(object_pk=q, follow_status='ed').values_list('user_pk', flat=True))
if len(p_follower_set) == 0 or len(q_follower_set) ==0: continue
union = p_follower_set.union(q_follower_set)
intersection = p_follower_set.intersection(q_follower_set)
diversity = float(len(intersection))/len(union)
pk_pk_diversity[p_username] = dict()
pk_pk_diversity[p_username][q_username] = diversity
if q_username in pk_pk_diversity:
pk_pk_diversity[q_username][p_username] = diversity
else:
pk_pk_diversity[q_username] = dict()
pk_pk_diversity[q_username][p_username] = diversity
return JsonResponse({"success": True, "diversity":pk_pk_diversity})
def draw_graph(request):
user_pk_list = request.GET.get('user_pk_list', '')
user_pk_set = set(user_pk_list.split(','))
G = make_graph(user_pk_set, "no-title.yaml", True)
return JsonResponse({"success": True})
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,532
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0006_follow.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-10-09 08:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0005_user'),
]
operations = [
migrations.CreateModel(
name='Follow',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=200)),
('full_name', models.TextField(null=True)),
('user_pk', models.IntegerField()),
('is_verified', models.BooleanField()),
('is_private', models.BooleanField()),
('follow_status', models.CharField(max_length=5)),
('object_pk', models.IntegerField()),
('is_favorite', models.BooleanField()),
],
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,533
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0002_auto_20170917_0537.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-09-17 05:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='influencer',
name='num_followers',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='influencer',
name='num_followings',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AlterField(
model_name='influencer',
name='engagement_rate',
field=models.DecimalField(decimal_places=20, max_digits=22),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,534
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0004_post.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-09-23 06:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('crawler', '0003_auto_20170917_2014'),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_id', models.CharField(max_length=200)),
('engagement_rate', models.DecimalField(decimal_places=20, max_digits=22, null=True)),
('num_likes', models.IntegerField(null=True)),
('num_commenters', models.IntegerField(null=True)),
('num_views', models.IntegerField(null=True)),
('captions', models.TextField(null=True)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
],
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,535
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/web/views.py
|
#-*- coding: utf-8 -*-
import sys , os, pdb
reload(sys)
sys.setdefaultencoding('utf-8')
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
#sys.path.append(os.path.abspath('../crawler'))
from models import *
from .forms import WebForm
def landing(request):
return render(request, 'web/landing.html', {'influencers': 'nothing'})
def influencers(request):
company = request.GET.get('company', 'Bottega_Veneta')
company = company.replace('_', ' ')
influencers = User.objects.filter(campaign_kind='dog', follower_count__gte=10000)[:5]
return render(request, 'web/influencers.html', {'influencers': influencers, 'company': company})
def new_subscriber(request):
form = WebForm(request.POST)
if form.is_valid(): form.save()
return HttpResponseRedirect("/")
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,536
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0005_user.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-10-09 07:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0004_post'),
]
operations = [
migrations.CreateModel(
name='user',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=200)),
('usertags_count', models.IntegerField(null=True)),
('media_count', models.IntegerField(null=True)),
('following_count', models.IntegerField(null=True)),
('is_business', models.BooleanField()),
('has_chaining', models.BooleanField()),
('geo_media_count', models.IntegerField(null=True)),
('full_name', models.TextField(null=True)),
('user_pk', models.IntegerField()),
('is_verified', models.BooleanField()),
('is_private', models.BooleanField()),
('is_favorite', models.BooleanField()),
('external_url', models.TextField(null=True)),
],
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,537
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0011_hashtag_dictionary.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-22 14:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('crawler', '0010_auto_20171010_1105'),
]
operations = [
migrations.CreateModel(
name='Hashtag_Dictionary',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_pk', models.BigIntegerField()),
('hashtag', models.TextField(null=True)),
('count', models.IntegerField(null=True)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
],
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,538
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0012_hashtag_dictionary_code_list.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-22 15:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0011_hashtag_dictionary'),
]
operations = [
migrations.AddField(
model_name='hashtag_dictionary',
name='code_list',
field=models.TextField(null=True),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,539
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0025_auto_20171230_1613.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-30 07:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0024_scoreboard_created_date'),
]
operations = [
migrations.AlterField(
model_name='scoreboard',
name='graph_type',
field=models.CharField(db_index=True, max_length=10),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,540
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0018_auto_20171121_0612.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-20 21:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0017_auto_20171114_2310'),
]
operations = [
migrations.AddField(
model_name='user',
name='num_follower_commenters',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='user',
name='num_follower_likes',
field=models.IntegerField(null=True),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,541
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/models.py
|
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.utils import timezone
class ScoreBoard(models.Model):
user_pk = models.BigIntegerField(db_index=True)
brandname = models.CharField(max_length=200, db_index=True)
page_rank = models.DecimalField(max_digits=22, decimal_places=20, null=True)
graph_type = models.CharField(max_length=10, db_index=True) # hashtag or basic.
created_date = models.DateTimeField(default=timezone.now)
class User(models.Model):
username = models.CharField(max_length=200, db_index=True)
usertags_count = models.IntegerField(null=True)
media_count = models.IntegerField(null=True)
following_count = models.IntegerField(null=True)
follower_count = models.IntegerField(null=True, db_index=True)
is_business = models.BooleanField()
has_chaining = models.BooleanField()
geo_media_count = models.IntegerField(null=True)
user_pk = models.BigIntegerField()
is_verified = models.BooleanField()
is_private = models.BooleanField()
is_favorite = models.BooleanField()
external_url = models.TextField(null=True)
created_date = models.DateTimeField(default=timezone.now)
count_DM_sent = models.IntegerField(default=0)
engagement_rate = models.DecimalField(max_digits=22, decimal_places=20, null=True)
num_likes = models.IntegerField(null=True)
num_follower_likes = models.IntegerField(null=True)
num_commenters = models.IntegerField(null=True)
num_follower_commenters = models.IntegerField(null=True)
num_views = models.IntegerField(null=True)
remark = models.TextField(null=True)
campaign_kind = models.TextField(null=True)
class Follow(models.Model):
object_pk = models.BigIntegerField(db_index=True)
follow_status = models.CharField(max_length=5, db_index=True) # ing or ed.
username = models.CharField(max_length=200)
user_pk = models.BigIntegerField(db_index=True)
is_verified = models.BooleanField()
is_private = models.BooleanField()
is_favorite = models.BooleanField()
created_date = models.DateTimeField(default=timezone.now)
class Influencer(models.Model):
#author = models.ForeignKey('auth.User')
user_id = models.CharField(max_length=200)
engagement_rate = models.DecimalField(max_digits=22, decimal_places=20, null=True)
followers = models.TextField(null=True)
followings = models.TextField(null=True)
num_followers = models.IntegerField(null=True)
num_followings = models.IntegerField(null=True)
num_posts = models.IntegerField(null=True)
num_likes = models.IntegerField(null=True)
num_commenters = models.IntegerField(null=True)
num_views = models.IntegerField(null=True)
created_date = models.DateTimeField(
default=timezone.now)
#published_date = models.DateTimeField(
# blank=True, null=True)
def publish(self):
#self.published_date = timezone.now()
self.save()
def __str__(self):
return self.user_id
class Hashtag_Dictionary(models.Model):
user_pk = models.BigIntegerField(db_index=True)
hashtag = models.CharField(max_length=200, db_index=True, null=True)
count = models.IntegerField(null=True)
code_list = models.TextField(null=True)
created_date = models.DateTimeField(default=timezone.now)
def add_count(self, volume, code):
self.count += 1
self.code_list += ','+code
self.save()
def __str__(self):
return self.hashtag
class Post(models.Model):
user_id = models.CharField(max_length=200)
engagement_rate = models.DecimalField(max_digits=22, decimal_places=20, null=True)
num_likes = models.IntegerField(null=True)
num_commenters = models.IntegerField(null=True)
num_views = models.IntegerField(null=True)
captions = models.TextField(null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.user_id+"'s post"
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,542
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/admin.py
|
from django.contrib import admin
from .models import Influencer, Post
# Register your models here.
admin.site.register(Influencer)
admin.site.register(Post)
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,543
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0003_auto_20170917_2014.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-09-17 11:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0002_auto_20170917_0537'),
]
operations = [
migrations.RemoveField(
model_name='influencer',
name='published_date',
),
migrations.AlterField(
model_name='influencer',
name='engagement_rate',
field=models.DecimalField(decimal_places=20, max_digits=22, null=True),
),
migrations.AlterField(
model_name='influencer',
name='followers',
field=models.TextField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='followings',
field=models.TextField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_commenters',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_followers',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_followings',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_likes',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_posts',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='influencer',
name='num_views',
field=models.IntegerField(null=True),
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,544
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/web/forms.py
|
from django import forms
from .models import Subscriber
class WebForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ('product', 'email', 'first_name',)
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,545
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/web/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.landing, name='starlight_landing'),
url(r'^influencers$', views.influencers, name='show_influencers'),
url(r'^subscriber/add$', views.new_subscriber, name='save_new_subscriber'),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,546
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/migrations/0023_scoreboard.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-30 06:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0022_user_campaign_kind'),
]
operations = [
migrations.CreateModel(
name='ScoreBoard',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_pk', models.BigIntegerField(db_index=True)),
('brandname', models.CharField(db_index=True, max_length=200)),
('page_rank', models.DecimalField(decimal_places=20, max_digits=22, null=True)),
('graph_type', models.CharField(db_index=True, max_length=5)),
],
),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,671,547
|
pauluskim/StarLight
|
refs/heads/crawler-master
|
/starlight/crawler/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^$', views.influencer_list, name='influencer_list'),
url(r'^crawl/hashtag_posts$', views.crawl_hashtag_posts, name='crawl_hashtag_posts'),
url(r'^crawl/start_hashtag_posts$', views.start_hashtag_posts, name='start_hashtag_posts'),
url(r'^crawl/user_follow$', views.user_follow, name='user_follow'),
url(r'^crawl/followers/(?P<target_user_pk>[0-9]+)/$', views.followers, name='followers'),
url(r'^crawl/following$', views.following, name='crawl_following'),
url(r'^crawl/api_following/(?P<target_user_pk>[0-9]+)/$', views.api_following, name='following'),
url(r'^crawl/from_file_user_by_name$', views.from_file_user_by_name, name='crawl_from_file'),
url(r'^crawl/calculate_engagement$', views.calculate_engagement, name='calculate_engagement'),
url(r'^crawl/__a_engagement$', views.__a_engagement, name='__a_engagement'),
url(r'^crawl/posts$', views.posts, name='posts'),
url(r'^crawl/SendDM$', views.SendDM, name='SendDM'),
url(r'^crawl/pagerank$', views.pagerank, name='pagerank'),
url(r'^crawl/diversity', views.diversity, name='diversity'),
url(r'^crawl/draw_graph', views.draw_graph, name='draw_graph'),
#url(r'^crawl/manager$', views.crawl_manager, name='crawl_manager'),
url(r'^crawl/follow_list$', views.follow_list, name='follow_list'),
url(r'^crawl/export_follow_csv$', views.export_follow_csv, name='export_follow_csv'),
url(r'^crawl/hashtag_dic$', views.start_hashtag_dictionary, name='hashtag_dictionary'),
url(r'^crawl/api_hashtag_dic$', views.api_hashtag_dic, name='api_hashtag_dictionary'),
url(r'^crawl/export_hashtag_dic$', views.export_hashtag_dic, name='export_hashtag_dic'),
url(r'^crawl/check_influencer$', views.check_influencer, name='export_hashtag_dic'),
url(r'^crawl/user_by_name$', views.user_by_name, name='user_by_name'),
]
|
{"/starlight/web/models.py": ["/crawler/models.py"], "/starlight/web/views.py": ["/starlight/web/forms.py"], "/starlight/crawler/admin.py": ["/starlight/crawler/models.py"], "/starlight/web/forms.py": ["/starlight/web/models.py"]}
|
40,697,807
|
mingqianye/gym-vim
|
refs/heads/master
|
/gym_vim/envs/encoded_emulator.py
|
import numpy as np
from gym_vim.envs.emulator import Emulator, EmulatorState, ScreenString, EmulatorAction
from gym_vim.envs.encoder import Encoder
from gym_vim.envs.keys import keystrokes, displayable_chars, modes
from gym import spaces
from typing import NewType, Tuple, Dict, List
EncodedObservation = NewType("EncodedObservation", np.ndarray)
class EncodedEmulator:
def __init__(self,
start_string: str,
target_string: str,
max_steps: int,
max_string_len: int,
all_keystrokes: List[str] = keystrokes,
all_chars: List[str] = displayable_chars,
all_modes: List[str] = modes
):
self._emulator: Emulator = Emulator(start_string, target_string, max_steps)
self._action_encoder: Encoder = Encoder(all_keystrokes)
self._char_encoder: Encoder = Encoder(all_chars)
self._mode_encoder: Encoder = Encoder(all_modes)
self._max_string_len: int = max_string_len
def step(self, encoded_action) -> Tuple[EncodedObservation, int, bool, Dict]:
ob, reward, done, info = self._emulator.step(
self._action_encoder.decode(encoded_action))
return self.__encode_ob(ob), reward, done, info
def reset(self):
self._emulator.reset()
def render(self):
self._emulator.render()
def close(self):
self._emulator.close()
def encode_action(self, action: EmulatorAction) -> np.ndarray:
return self._action_encoder.encode(action)
def __encode_ob(self, ob: EmulatorState) -> EncodedObservation:
return np.concatenate([
self.encode_action(ob.last_action),
self._mode_encoder.encode(ob.mode),
ob.curpos,
self.__encode_string(ob.string)
])
def __encode_string(self, s: ScreenString) -> np.ndarray:
arrs = []
for c in s.ljust(self._max_string_len):
arrs.append(self._char_encoder.encode(c))
return np.concatenate(arrs)
def action_space(self):
return spaces.Discrete(self._action_encoder.size())
def observation_space(self):
ob = self._emulator.cur_observation()
encoded_ob = self.__encode_ob(ob)
return spaces.Box(
low=0,
high=5,
shape=(1, encoded_ob.size)
)
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,697,808
|
mingqianye/gym-vim
|
refs/heads/master
|
/tests/test_keys.py
|
import unittest
from gym_vim.envs.keys import keystrokes
class TestKeys(unittest.TestCase):
def test_keystrokes(self):
self.assertEqual(94, len(keystrokes))
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,697,809
|
mingqianye/gym-vim
|
refs/heads/master
|
/gym_vim/envs/emulator.py
|
import pynvim
from typing import NewType, List, Tuple, Dict
from dataclasses import dataclass
from gym_vim.envs.fs import get_state, is_valid, feedkeys, VimState
from gym_vim.envs.edit_distance import edit_distance
from gym_vim.envs.keys import esc
EmulatorAction = NewType("EmulatorAction", str)
NvimMode = NewType("NvimMode", str)
ScreenString = NewType("NvimScreenString", str)
@dataclass(eq=True, frozen=True)
class EmulatorState:
last_action: EmulatorAction
mode: NvimMode
curpos: List[int]
string: ScreenString
class NvimWrapper:
def __init__(self, start_string: ScreenString):
self._nvim: pynvim.api.nvim.Nvim = NvimWrapper.__new_nvim_instance(start_string)
self._state_string: ScreenString = start_string
def inital_state(self) -> EmulatorState:
return NvimWrapper.__state_with_action(self._nvim, "")
def send_action(self, action: EmulatorAction) -> EmulatorState:
feedkeys(self._nvim, action)
return NvimWrapper.__state_with_action(self._nvim, action)
def __state_with_action(nvim: pynvim.api.nvim.Nvim, action: EmulatorAction) -> EmulatorState:
vimstate = get_state(nvim)
return EmulatorState(
action,
vimstate.mode,
vimstate.curpos,
"".join(vimstate.strings))
def __new_nvim_instance(start_string: ScreenString) -> pynvim.api.nvim.Nvim:
nvim = pynvim.attach('child', argv=["/bin/env", "nvim", "--embed", "--headless", "--noplugin", "--clean", "-n"])
feedkeys(nvim, "i")
feedkeys(nvim, start_string)
feedkeys(nvim, esc)
feedkeys(nvim, "gg")
return nvim
def is_valid(self):
return is_valid(self._nvim)
def close(self):
self._nvim.quit()
self._nvim.close()
def reset(self):
self.close()
self._nvim = NvimWrapper.__new_nvim_instance(self._state_string)
class Emulator:
def __init__(self, start_string: ScreenString, target_string: ScreenString, max_steps: int):
self._nvim: NvimWrapper = NvimWrapper(start_string)
self._emulator_states: List[EmulatorState] = [self._nvim.inital_state()]
self._target_string: ScreenString = target_string
self._max_steps: int = max_steps
def cur_observation(self) -> EmulatorState:
return self._emulator_states[-1]
def step(self, action: EmulatorAction) -> Tuple[EmulatorState, int, bool, Dict]:
self._emulator_states.append(self._nvim.send_action(action))
reward = self.__reward()
done = self.__is_done()
info = {"states": self._emulator_states}
return self._emulator_states[-1], reward, done, info
def __reward(self):
prev_distance = edit_distance(
self._emulator_states[-2].string,
self._target_string)
new_distance = edit_distance(
self._emulator_states[-1].string,
self._target_string)
if new_distance == 0:
return 100
if new_distance == prev_distance:
return -1
if new_distance > prev_distance:
return -10
if new_distance < prev_distance:
return 10
def __is_done(self):
return self._emulator_states[-1].string == self._target_string \
or len(self._emulator_states) >= self._max_steps \
or not self._nvim.is_valid()
def reset(self):
self._nvim.reset()
self._emulator_states = [self._nvim.inital_state()]
def render(self) -> None:
print(self._emulator_states[-1])
def close(self):
self._nvim.close()
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,697,810
|
mingqianye/gym-vim
|
refs/heads/master
|
/gym_vim/envs/fs.py
|
import subprocess
import tempfile
import json
from dataclasses import dataclass
from pynvim import attach, api
from typing import Tuple, List
@dataclass(eq=True, frozen=True)
class VimState:
mode: str
curpos: List[int]
strings: List[str]
def get_state(nvim: api.nvim.Nvim) -> VimState:
return VimState(
get_mode(nvim),
get_curpos(nvim),
get_strings(nvim))
def get_mode(nvim: api.nvim.Nvim) -> str:
return nvim.command_output("echo mode()")
def get_strings(nvim: api.nvim.Nvim) -> List[str]:
return list(nvim.current.buffer)
def get_curpos(nvim: api.nvim.Nvim) -> List[int]:
s = nvim.command_output("echo getcurpos()")
#[bufnum, lnum, col, off, curswant]
return json.loads(s)
def is_valid(nvim: api.nvim.Nvim) -> bool:
return nvim.current.buffer.valid
def feedkeys(nvim: api.nvim.Nvim, s: str) -> None:
nvim.feedkeys(s)
# Not used
def sh(cmd: str) -> List[str]:
out, err = sh_unsafe(cmd)
if err != None:
raise RuntimeError(err)
return out.decode("utf-8").strip().split("\n")
def sh_unsafe(cmd: str) -> Tuple[str, str]:
out = subprocess.Popen(cmd.split(" "),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
return (stdout, stderr)
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,697,811
|
mingqianye/gym-vim
|
refs/heads/master
|
/gym_vim/envs/__init__.py
|
from gym_vim.envs.vim_env import VimEnv
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,697,812
|
mingqianye/gym-vim
|
refs/heads/master
|
/setup.py
|
from setuptools import setup
setup(name='gym_vim',
version='0.0.1',
install_requires=['gym', 'sklearn', 'numpy', 'pynvim'] # And any other dependencies foo needs
)
|
{"/tests/test_encoder.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoder.py"], "/gym_vim/envs/vim_env.py": ["/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/emulator.py": ["/gym_vim/envs/fs.py", "/gym_vim/envs/edit_distance.py", "/gym_vim/envs/keys.py"], "/tests/test_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/emulator.py"], "/gym_vim/envs/__init__.py": ["/gym_vim/envs/vim_env.py"], "/tests/test_fs.py": ["/gym_vim/__init__.py", "/gym_vim/envs/fs.py"], "/tests/test_edit_distance.py": ["/gym_vim/__init__.py", "/gym_vim/envs/edit_distance.py"], "/tests/test_keys.py": ["/gym_vim/envs/keys.py"], "/tests/test_encoded_emulator.py": ["/gym_vim/__init__.py", "/gym_vim/envs/encoded_emulator.py"], "/gym_vim/envs/encoded_emulator.py": ["/gym_vim/envs/emulator.py", "/gym_vim/envs/encoder.py", "/gym_vim/envs/action_encoder.py", "/gym_vim/envs/keys.py"]}
|
40,702,328
|
TooTiredOne/TatDFS
|
refs/heads/master
|
/namenode.py
|
from flask import Flask, Response, request, jsonify
import logging
from anytree import Node, RenderTree, Resolver
from datetime import datetime
from threading import Thread
import os, requests, random, time
from FileSystem import fs
ROOT_DIR = "root"
HOST = '0.0.0.0'
PORT = 8080
DATANODES = ["http://0.0.0.0:8085"]
# DATANODES = ["http://0.0.0.0:8085", "http://0.0.0.0:8086", "http://0.0.0.0:8087"]
HEARTBEAT_RATE = 5
app = Flask(__name__)
logging.basicConfig(filename='namenode.log', level=logging.DEBUG)
def heartbeat():
while True:
print("started heartbeat")
# go through each datanode
new_alive = [] # dead -> alive
new_dead = [] # alive -> dead
print(f"live_datanodes: {fs.live_datanodes}")
print(f"dead datanodes: {fs.dead_datanodes}")
# updating new_dead
for cur_node in fs.live_datanodes:
try:
response = requests.get(cur_node + '/ping') # pinging current datanode
if response.status_code // 100 != 2:
new_dead.append(cur_node)
print(f"new dead: {cur_node}")
except Exception as e:
new_dead.append(cur_node)
print(f"new dead: {cur_node}")
# updating new_alive
for cur_node in fs.dead_datanodes:
try:
response = requests.get(cur_node + '/ping')
if response.status_code // 100 == 2:
print(f"new alive: {cur_node}")
new_alive.append(cur_node)
except Exception as e:
print(f"FAILED to PING datanode {cur_node}")
# resurrecting nodes
for node in new_alive:
# request the datanode to format
response = requests.get(node + '/format')
if response.status_code // 100 != 2:
print(f"couldn't resurrect datanode: {node}")
else:
fs.live_datanodes.append(node)
fs.dead_datanodes.remove(node)
fs.datanodes_files[node] = []
# getting the up to date list of live and dead datanodes
for node in new_dead:
fs.live_datanodes.remove(node)
fs.dead_datanodes.append(node)
# replicating files from dead datanodes
for node in new_dead:
print(f"replica on dead for {node}")
fs.replicate_on_dead(node)
print(f"needs_replica: {fs.needs_replica}")
needs_repl = []
# try to replicate files that needs replication
for node in fs.needs_replica.keys():
file = node.file
needed = fs.replication - len(file['datanodes'])
new_datanodes = fs.choose_datanodes(n=needed, exclude=file['datanodes'])
for new_datanode in new_datanodes:
for datanode in file['datanodes']:
print(f"started replicating from {datanode}")
try:
response = requests.post(new_datanode + '/get-replica',
json={'file_id': file['id'], 'datanode': datanode})
except Exception as e:
print("couldn't replicate")
continue
if response.status_code // 100 == 2:
if new_datanode in fs.datanodes_files.keys():
fs.datanodes_files[new_datanode].append(file['id'])
else:
fs.datanodes_files[new_datanode] = [file['id']]
print(f"file was replicated")
file['datanodes'] += [new_datanode]
break
else:
print(f"file was NOT replicated")
node.file = file
needs_repl.append(node)
for node in needs_repl:
fs.update_needs_replica(node, remove=False)
print(f"needs replica: {fs.needs_replica}")
time.sleep(HEARTBEAT_RATE)
@app.route('/ping')
def ping():
return Response("ping from namenode", 200)
@app.route('/curdir')
def curdir():
return jsonify({'current_dir': fs.get_current_dirname()})
@app.route('/init')
def init():
print("starting INIT in NAMENODE")
# initialize FS
fs.__init__()
live_datanodes = []
dead_datanodes = []
# check whether nodes are alive
# if yes format them
for datanode in DATANODES:
# ping datanode
try:
response = requests.get(datanode + '/ping')
except Exception as e:
print(f"couldn't ping DATANODE {datanode} because of\n{e}")
# update dead datanodes
dead_datanodes.append(datanode)
continue
# if ok
if response.status_code // 100 == 2:
# formatting datanode
try:
response = requests.get(datanode + '/format')
except Exception as e:
print(f"couldn't FORMAT DATANODE {datanode} because of\n{e}\nAppending to dead datanodes")
dead_datanodes.append(datanode)
continue
if response.status_code // 100 != 2:
print(f"couldn't FORMAT DATANODE {datanode}\nAppending to dead datanodes")
dead_datanodes.append(datanode)
app.logger.info(f"couldn't FORMAT DATANODE {datanode}")
else:
# updating free space
spaces = response.json()
free = spaces['free']
fs.free_space = min(free, fs.free_space)
# updating live datanodes
live_datanodes.append(datanode)
else:
print(f"couldn't ping DATANODE {datanode}")
# app.logger.info(f"couldn't pind DATANODE {datanode}")
# check whether the FS initialized successfully
app.logger.info("checking len of live_datanodes")
print(f"LIVE DATANODES: {live_datanodes}")
print(f"DEAD DATANODES: {dead_datanodes}")
fs.dead_datanodes = dead_datanodes
fs.live_datanodes = live_datanodes
if len(live_datanodes) > 0:
app.logger.info(f"live datanodes: {live_datanodes}")
return jsonify({"free_space": fs.free_space})
else:
return Response("FAILED: couldn't INIT as no live datanodes", 418)
@app.route('/delete', methods=['DELETE'])
def delete():
# delete file from FS
print("starting deleting file")
filename = request.json['filename']
print(f"filename = {filename}")
# try to obtain file from the filesystem
node = fs.get_file(filename)
if node:
print("file exists")
file = fs.delete_file(node)
print(f"file = {file}")
return jsonify({"file": file})
else:
print("file doesn't exist")
return Response("FAILED: file doesn't exist", 404)
@app.route('/delete/dir-notsure', methods=['DELETE'])
def delete_dir_notsure():
print("starting deleting dir")
dirname = request.json['dirname']
print(f"dirname: {dirname}")
# try to obtain directory from the filesystem
dir_node = fs.get_dir(dirname)
if dir_node:
children = [x for x in dir_node.children]
# check if directory contains something
if len(children) == 0:
dir_node.parent = None
print("directory empty, was removed successfully")
return jsonify({"empty": True})
else:
print("directory not empty")
return jsonify({"empty": False})
else:
print("dir doesn't exist")
return Response("FAILED: dir doesn't exist", 404)
@app.route('/delete/dir-sure', methods=['DELETE'])
def delete_dir_sure():
print("starting deleting dir")
dirname = request.json['dirname']
print(f"dirname: {dirname}")
# obtain the directory from the filesystem
dir_node = fs.get_dir(dirname)
if dir_node:
# get all files in the specified directory
files = fs.get_all_files_rec(dir_node)
# remove directory and all its children from the filesystem
dir_node.parent = None
return jsonify({"files": files})
else:
print("dir doesn't exist")
return Response("FAILED: dir doesn't exist", 404)
@app.route('/copy', methods=['POST'])
def copy():
print("started copying file in namenode")
filename = request.json['filename']
dirname = request.json['dirname']
# node with the file
original_node = fs.get_file(filename)
if original_node:
print(f"file {filename} found")
# node with the new dir
if dirname[-1] == '/':
new_node_par = fs.get_dir(dirname)
if new_node_par:
# resolving name collision
new_name = os.path.basename(filename) + '_copy'
count = 1
file = fs.get_file(new_name)
while file:
new_name = new_name + str(count)
count += 1
file = fs.get_file(new_name)
# creating copy of the file
file = fs.create_file(new_name, new_node_par, original_node.file['size'])
print(f"file was copied under the filename {filename}")
return jsonify({'original': original_node.file, 'copy': file})
else:
dir_name = os.path.dirname(dirname)
file_name = os.path.basename(dirname)
file = fs.get_file(dirname)
if file or fs.get_dir(dirname):
print("specified file already exists")
return Response("FAILED: specified file already exists", 404)
else:
parent_dir = fs.get_dir(dir_name)
if parent_dir:
file = fs.create_file(file_name, parent_dir, original_node.file['size'])
print(f"file was copied under the filename {filename}")
return jsonify({'original': original_node.file, 'copy': file})
else:
print("specified directory does not exist")
return Response("FAILED: specified directory does not exist", 404)
else:
return Response("FAILED: file doesn't exist", 404)
@app.route('/get', methods=['GET'])
def get():
print("started GETTING the file in NAMENODE")
filename = request.json['filename']
print(f"filename = {filename}")
file = fs.get_file(filename)
if file:
print("file exists")
print(f"file = {file.file}")
return jsonify({"file": file.file})
else:
print("file doesn't exist")
return Response("FAILED: file doesn't exist", 404)
@app.route('/create', methods=['POST'])
def create():
print("started CREATING file")
# obtain filename
filename = request.json['filename']
filesize = 0
if request.json['filesize']:
filesize = request.json['filesize']
# check whether file already exists
if fs.get_file(filename) or fs.get_dir(filename):
print(f"FILE {filename} already exists")
# app.logger.info(f"file already exists {filename}")
return Response("FAILED: file or dir with this name already exists", 409)
# create file, return info about datanodes and id
else:
# app.logger.info(f"filesize: {filesize} free_space:{fs.free_space}")
if filesize > fs.free_space: # check if there's available space
print("FAILED: not enough space")
return Response("not enough space", 413)
else:
file_dir = os.path.dirname(filename)
file_name = os.path.basename(filename)
file_parent = fs.get_dir(file_dir)
if file_parent:
if len(file_name) < 1:
return Response("FAILED: filename cannot be empty", 418)
else:
file = fs.create_file(file_name, file_parent, filesize)
return jsonify({"file": file})
else:
return Response(f"FAILED: dir {file_dir} doesn't exist", 404)
@app.route('/mkdir', methods=['POST'])
def mkdir():
# get directory name
dirname = request.json['dirname']
if fs.get_file(dirname) or fs.get_dir(dirname):
return Response("FAILED: dir or file with such name exists", 409)
else:
# add directory to fs tree
dir_parent = os.path.dirname(dirname)
dir_name = os.path.basename(dirname)
parent_node = fs.get_dir(dir_parent)
if parent_node:
fs.create_directory(dir_name, parent_node)
return Response("ok", 200)
else:
return Response(f"FAILED: specified path {dir_parent} does not exist", 404)
@app.route('/ls')
def ls():
# get directory name
dirname = request.json['dirname']
dirs = []
files = []
# get directory from the dilesystem
dir_node = fs.get_dir(dirname)
if not dir_node:
return Response(f"FAILED: specified directory {dirname} does not exist", 404)
for node in dir_node.children:
# check whether file or directory
if node.is_file:
files.append(node.name)
else:
dirs.append(node.name)
return jsonify({'dirs': dirs, 'files': files})
@app.route('/cd', methods=['POST'])
def cd():
# get directory name
dirname = request.json['dirname']
# get the directory from the filesystem
node = fs.get_dir(dirname)
if node:
# change the current directory to the obtained one
fs.cur_node = node
return jsonify({'dirname': fs.cur_node.name, 'cur_dir': fs.get_current_dirname()})
else:
return Response(f'FAILED: specified directory {dirname} does not exist', 404)
@app.route('/info', methods=['POST'])
def info():
# get file name
filename = request.json['filename']
# obtain the file from the filesystem
node = fs.get_file(filename)
if node:
return jsonify({'info': node.file})
else:
return Response(f'FAILED: file {filename} not found', 404)
@app.route('/move', methods=['POST'])
def move():
# get file name
filename = request.json['filename']
# get path
path = request.json['path']
# obtain file from the filesystem
file_node = fs.get_file(filename)
if file_node:
# resolve filename
dir_name = ''
file_name = ''
if path[-1] == '/':
dir_name = path
file_name = os.path.basename(filename)
else:
dir_name = os.path.dirname(path)
file_name = os.path.basename(path)
# obtain the directory where to move
node = fs.get_dir(dir_name)
if node:
if file_name in [x.name for x in node.children]:
return Response(f'FAILED: file {filename} already exists in this dir', 419)
else:
# move the file in a filesystem
file_node.parent = node
file_node.name = file_name
return Response('', 200)
else:
return Response(f'FAILED: specified path {dir_name} does not exist', 404)
else:
return Response(f'FAILED: file {filename} could not be found', 404)
if __name__ == '__main__':
heartbeat_thread = Thread(target=heartbeat)
heartbeat_thread.start()
app.run(debug=True, host=HOST, port=PORT)
heartbeat_thread.join()
|
{"/namenode.py": ["/FileSystem.py"]}
|
40,702,329
|
TooTiredOne/TatDFS
|
refs/heads/master
|
/testing/datanode3/datanode.py
|
import logging
import os, requests
import shutil
from flask import Flask, Response, jsonify, request, send_file
HOST = '0.0.0.0'
PORT = 8087
CURRENT_DIR = os.path.join(os.getcwd(), "data")
app = Flask(__name__)
logging.basicConfig(filename='datanode.log', level=logging.DEBUG)
@app.route("/ping")
def ping():
return Response("ping from datanode", 200)
@app.route("/format")
def format():
'''
Formats the contents of the datanode
'''
global CURRENT_DIR
print("started FORMATTING in DATANODE")
# create root folder if it does not exist
if not os.path.exists(CURRENT_DIR):
os.mkdir(CURRENT_DIR)
# iterate through all files and dirs and delete
for filename in os.listdir(CURRENT_DIR):
path = os.path.join(CURRENT_DIR, filename)
try:
if os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
elif os.path.isdir(path):
shutil.rmtree(path)
except Exception as e:
# if file/dir was not deleted write to log
print(f"FAILED to DELETE {path} because of\n{e}")
app.logger.info(f'failed to delete {path}, reason: {e}')
# obtain info about free space
_, _, free = shutil.disk_usage(CURRENT_DIR)
return jsonify({"free": free})
@app.route("/get", methods=['GET'])
def get_file():
'''
Get file from datanode
'''
print("started transmitting file for get_file")
file_id = request.json['file_id']
if os.path.isfile(os.path.join(CURRENT_DIR, str(file_id))):
print("file found, sending")
return send_file(os.path.join(CURRENT_DIR, str(file_id)))
else:
print("file is not found")
return Response("file doesn't exist in this node", 404)
@app.route("/copy/existing", methods=['POST'])
def copy_existing_file():
'''
Makes copy of the existing file in datanode
'''
print("started copying existing file")
original_id = str(request.json['original_id'])
copy_id = str(request.json['copy_id'])
print(f"original id: {original_id}")
print(f"copy id: {copy_id}")
path_original = os.path.join(CURRENT_DIR, original_id)
path_copy = os.path.join(CURRENT_DIR, copy_id)
try:
shutil.copyfile(path_original, path_copy)
print("file was copied")
return Response("file was copied", 200)
except Exception as e:
print(f"file wasn't copied because of {e}")
return Response(f"file wasn't copied because of {e}", 419)
@app.route('/get-replica', methods=['POST'])
def get_replica():
'''
Getting replica of the file from the other datanode
'''
print("started acquiring the replica")
file_id = str(request.json['file_id'])
src = str(request.json['datanode'])
print(f"file id: {file_id}")
print(f"src: {src}")
path = os.path.join(CURRENT_DIR, file_id)
try:
response = requests.get(src + '/get', json={'file_id': file_id})
except Exception as e:
print(f"FAILED to get file from {src} due to {e}")
return Response("error in get", 400)
if response.status_code // 100 == 2:
print(f"file was acquired")
open(path, 'wb').write(response.content)
return Response("file was replicated", 200)
else:
print(f"couldn't acquire the file from {src}")
return Response("file was not replicated", 400)
@app.route("/copy/non-existing", methods=['POST'])
def copy_non_existing_file():
'''
Copying files by obtaining it from the other datanode
'''
print("started copying non-existing file")
original_id = str(request.json['original_id'])
copy_id = str(request.json['copy_id'])
src = str(request.json['datanode'])
print(f"original id: {original_id}")
print(f"copy id: {copy_id}")
print(f"src: {src}")
path_copy = os.path.join(CURRENT_DIR, copy_id)
try:
response = requests.get(src + '/get', json={'file_id': original_id})
except Exception as e:
print(f"FAILED to get file from {src} due to\n{e}")
return Response(f"FAILED to get file from {src} due to\n{e}")
if response.status_code // 100 == 2:
print(f"file was acquired")
open(path_copy, 'wb').write(response.content)
return Response("file was copied", 200)
else:
print(f"couldn't acquire the file from {src}")
return Response("file was not copied", 400)
@app.route("/delete", methods=['DELETE'])
def delete_file():
print("started deleting file")
file_id = str(request.json['file_id'])
print(f"id: {file_id}")
if os.path.isfile(os.path.join(CURRENT_DIR, file_id)):
print("file is found")
os.unlink(os.path.join(CURRENT_DIR, file_id))
print("file is deleted")
return Response("file was deleted", 200)
else:
print("file is not found")
return Response("file doesn't exist", 404)
@app.route("/put", methods=['POST'])
def put_file():
'''
Put file to datanode
'''
print("started putting file")
# obtain file from client
file_id = [k for k in request.files.keys()][0]
file = request.files[f'{file_id}']
try:
# create file
print(f"file: {file}")
print(f"file id: {file_id}")
file.save(os.path.join(CURRENT_DIR, str(file_id)))
return Response("ok", 200)
except Exception as e:
# if not created append to log, response 400
app.logger.info(f"FAILED to put file because of {e}")
return Response(f"FAILED to put file because of {e}", 400)
@app.route("/create", methods=["POST"])
def create_file():
'''
Creates an empty file in the current directory
'''
# obtain file id from client
print("started creating file")
file_id = request.json['file_id']
try:
# create file
open(CURRENT_DIR + '/' + str(file_id), 'a').close()
return Response("", 200)
except Exception as e:
# if not created append to log, response 400
app.logger.info(f"failed to create file because of\n{e}")
return Response(f"failed to create file because of {e}", 400)
if __name__ == '__main__':
app.run(debug=True, host=HOST, port=PORT)
|
{"/namenode.py": ["/FileSystem.py"]}
|
40,702,330
|
TooTiredOne/TatDFS
|
refs/heads/master
|
/client.py
|
import requests, os
NAMENODE = "http://0.0.0.0:8080"
CURRENT_DIR = "/"
def mistake():
print("cannot execute command, please verify that you are using it correctly")
def show_help(*arguments):
if len(arguments) == 1:
print("""COMMANDS USAGE\n
NOTE: paths are resolved only with respect to current directory\n
---------------------------------------------------------------\n
init : initialize the distributed filesystem\n
touch <file> : create an empty file\n
get <file> : download file from the dfs\n
put <file> <path> : upload a file from the host to the dfs directory under the same name (if ends with /) or under a new name\n
rm <file> : delete a file from the dfs\n
cp <file> <path> : copy a file to the other directory (if ends with /) or under a new name\n
mkdir <dir> : initialize an empty directory\n
ls [dir] : list the contents of the directory (or current directory if no arguments)\n
cd <dir> : change directory\n
info <file> : display information about the file\n
mv <file> <path> : move the file in the dfs to the other directory (if ends with /) or under a new name\n
rmdir <dir> : delete directory (and its contents)\n
exit : exit the DFS client
""")
else:
mistake()
def init(*arguments):
'''
Initialize empty DFS
'''
global CURRENT_DIR
if len(arguments) == 1:
try:
# ping name node
response = requests.get(NAMENODE + "/ping")
except Exception as e:
print(f"couldn't establish connection to NAMENODE because of\n{e}")
return
# check response
if response.status_code // 100 == 2:
print("connection to NAMENODE was established")
try:
# request namenode to initialize the DFS
response = requests.get(NAMENODE + "/init")
except Exception as e:
print(f"FAILED NAMENODE while initializing filesystem\n{e}")
return
# check response
if response.status_code // 100 == 2:
data = response.json()
print(f"filesystem initialized")
CURRENT_DIR = '/'
print(f"available space: {data['free_space'] // (2**20)} MB")
else:
print(response.content.decode())
else:
print("couldn't ping NAMENODE")
else:
mistake()
def create_file(*arguments):
'''
Create an empty file in DFS
:param filename: name of the file to create
'''
if len(arguments) == 2:
filename = arguments[1]
# request NAMENODE to create file
try:
response = requests.post(NAMENODE + "/create", json={"filename": filename, 'filesize': 0})
except Exception as e:
print(f"FAILED to CREATE FILE because of\n{e}")
return
if response.status_code // 100 == 2:
# receive file info from namenode
file = response.json()["file"]
# request each datanode to create a file
for datanode in file['datanodes']:
try:
# requesting datanode for a file creation
resp = requests.post(datanode + "/create", json={"file_id": file['id']})
except Exception as e:
print(f"FAILED to CREATE file in {datanode} due to\n{e}")
continue
if resp.status_code // 100 != 2:
print(response.content.decode())
else:
print(f"FILE {filename} was created in {datanode}")
else:
print(response.content.decode())
else:
mistake()
def get_file(*arguments):
'''
Downloads file from dfs to client's local host
:param filename: name of the file in dfs
'''
if len(arguments) == 2:
filename = arguments[1]
# request namenode to locate a file
try:
response = requests.get(NAMENODE + "/get", json={"filename": filename})
except Exception as e:
print(f"FAILED to GET file from NAMENODE due to\n{e}")
return
if response.status_code // 100 == 2:
# acquiring the file from the datanodes
file = response.json()['file']
datanodes = file['datanodes']
received = False
for datanode in datanodes:
print(f"requesting the file from DATANODE {datanode}")
# requesting datanode for a file
try:
response = requests.get(datanode + "/get", json={"file_id": file['id']})
except Exception as e:
print(f"FAILED to GET file from {datanode} due to\n{e}")
continue
if response.status_code // 100 == 2:
print(f"file was acquired")
received = True
filename = os.path.basename(filename)
open(filename, 'wb').write(response.content)
break
else:
print(response.content.decode())
if received:
print(f"the file {filename} was received")
else:
print("file wasn't received")
else:
print(response.content.decode())
else:
mistake()
def put_file(*arguments):
'''
Put local file to DFS
:param local_filename: name of the local file
:param dfs_filename: name of the file in dfs
'''
if len(arguments) == 3:
local_filename = arguments[1]
dfs_filename = arguments[2]
# obtaining file size in bytes
try:
filesize = os.stat(local_filename).st_size
except Exception as e:
print(f"FAILED to calculate the size due to\n{e}")
return
# resolve filename
if dfs_filename[-1] == '/':
dfs_filename = dfs_filename + os.path.basename(local_filename)
# request namenode to put file
try:
response = requests.post(NAMENODE + "/create", json={"filename": dfs_filename, "filesize": filesize, "put": True})
except Exception as e:
print(f"FAILED to put file in NAMENODE due to\n{e}")
return
if response.status_code // 100 == 2:
# receive file info from namenode
file = response.json()["file"]
# request each datanode to create a file
for datanode in file['datanodes']:
# requesting
try:
resp = requests.post(datanode + "/put",
files={f"{file['id']}": open(local_filename, 'rb')})
except Exception as e:
print(f"FAILED to put file in {datanode} due to\n{e}")
continue
if resp.status_code // 100 != 2:
print(resp.content.decode())
else:
print(f"FILE {local_filename} was put as {dfs_filename} in {datanode}")
else:
print(response.content.decode())
else:
mistake()
def delete_file(*arguments):
'''
Deletes file from dfs
:param filename: name of the file
'''
if len(arguments) == 2:
filename = arguments[1]
# request namenode to delete file
try:
response = requests.delete(NAMENODE + "/delete", json={"filename": filename})
except Exception as e:
print(f"FAILED to REMOVE file from NAMENODE due to\n{e}")
return
if response.status_code // 100 == 2:
print("file was found in namenode")
# acquiring info about file
file = response.json()['file']
# removing file from datanodes
for datanode in file['datanodes']:
print(f"sending delete request to datanode {datanode}")
try:
# request datanode to remove the file
response = requests.delete(datanode + "/delete", json={"file_id": file['id']})
except Exception as e:
print(f"FAILED to REMOVE file from {datanode} due to\n{e}")
continue
if response.status_code // 100 == 2:
print(f"file was deleted from datanode {datanode}")
else:
print(f"FAILED file wasn't found in datanode {datanode}")
else:
print(response.content.decode())
else:
mistake()
def copy_file(*arguments):
'''
Copies the file from the current directory to somewhere else
Name resolution: new filename is filename_copy<num of copy>
:param filename: file in the current directory to copy
:param dirname: path where to put the file
'''
if len(arguments) == 3:
filename = arguments[1]
dirname = arguments[2]
# request namenode to copy file
try:
response = requests.post(NAMENODE + '/copy', json={'filename': filename, 'dirname': dirname})
except Exception as e:
print(f"FAILED to COPY in NAMENODE due to\n{e}")
return
# check response
if response.status_code // 100 == 2:
print("namenode was updated")
original = response.json()['original']
copy = response.json()['copy']
print(f"original file: {original}")
print(f"copy file: {copy}")
for datanode_cp in copy['datanodes']:
# creating a copy of file to the given datanode
print(f"started copying in {datanode_cp}")
if datanode_cp in original['datanodes']:
print("it already contains the file, started copying")
try:
# request datanode to copy file inside it
response = requests.post(datanode_cp + "/copy/existing",
json={"original_id": original['id'], "copy_id": copy['id']})
except Exception as e:
print(f"FAILED to COPY file in {datanode_cp} due to \n{e}")
continue
if response.status_code // 100 == 2:
print(f"file was successfully copied to {datanode_cp}")
else:
print(f"file couldn't be copied to {datanode_cp}")
else:
print("it doesn't contain the file, started copying")
for datanode_orig in original['datanodes']:
try:
# request to get a copy from the other datanode
response = requests.post(datanode_cp + "/copy/non-existing",
json={"original_id": original['id'], "copy_id": copy['id'],
"datanode": datanode_orig})
except Exception as e:
print(f"FAILED to COPY file in {datanode_cp} with {datanode_orig} due to \n{e}")
continue
if response.status_code // 100 == 2:
print(f"file was copied from {datanode_orig}")
break
else:
print(response.content.decode())
print("finished copying")
else:
print(response.content.decode())
else:
mistake()
def delete_directory(*arguments):
'''
Removes the directory
'''
print("started deleting directory")
if len(arguments) == 2:
dirname = arguments[1]
# request to delete if contains no files/directories inside
try:
response = requests.delete(NAMENODE + "/delete/dir-notsure", json={'dirname': dirname})
except Exception as e:
print(f"FAILED to rmdir in NAMENODE due to\n{e}")
return
if response.status_code // 100 == 2:
empty = response.json()['empty']
if empty:
print("empty dir was deleted")
else:
print("dir is not empty")
while True:
# check whether the client wants to delete the directory
delete = input("are you sure that you want do delete all contents? [y/n]")
if delete == 'y' or delete == 'Y' or delete == 'yes' or delete == 'Yes':
try:
# delete directory, get location of its files
response = requests.delete(NAMENODE + "/delete/dir-sure", json={'dirname': dirname})
except Exception as e:
print(f"FAILED to rmdir in NAMENODE due to\n{e}")
return
# delete all files from datanodes
if response.status_code // 100 == 2:
files = response.json()['files']
for file in files:
datanodes = file['datanodes']
id = file['id']
for datanode in datanodes:
try:
response = requests.delete(datanode + '/delete', json={'file_id': id})
except Exception as e:
print(f"FAILED to REMOVE file {file} from {datanode} due to\n{e}")
continue
if response.status_code // 100 == 2:
print(f"{file} was deleted from {datanode}")
else:
print(response.content.decode())
else:
print(response.content.decode())
break
elif delete == 'n' or delete == 'N' or delete == 'no' or delete == 'No':
print("not deleting")
break
else:
print(response.content.decode())
else:
mistake()
def make_directory(*arguments):
'''
Create an empty directory
:param dirname: name for directory to create
'''
if len(arguments) == 2:
dirname = arguments[1]
# request namenode to create directory
try:
response = requests.post(NAMENODE + '/mkdir', json={'dirname': dirname})
except Exception as e:
print(f"FAILED to mkdir in NAMENODE due to\n{e}")
return
# check response
if response.status_code // 100 == 2:
print(f"directory {dirname} successfully created")
else:
print(response.content.decode())
else:
mistake()
def read_directory(*arguments):
'''
Display the contents of the current directory
'''
dirname = ''
if len(arguments) <= 2:
if len(arguments) == 2:
dirname = arguments[1]
# request namenode for the file list
try:
response = requests.get(NAMENODE + '/ls', json={'dirname': dirname})
except Exception as e:
print(f"FAILED to READ dir from NAMENODE due to\n{e}")
return
# check response
if response.status_code // 100 == 2:
# print contents
dirs = response.json()['dirs']
files = response.json()['files']
print('---------------DIRECTORIES---------------')
for dir in dirs:
print(dir)
print('---------------FILES---------------')
for file in files:
print(file)
else:
print(response.content.decode())
else:
mistake()
def change_directory(*arguments):
'''
Change current working directory
:param dirname: the directory that we want to make current working
'''
global CURRENT_DIR
if len(arguments) == 2:
dirname = arguments[1]
try:
response = requests.post(NAMENODE + '/cd', json={'dirname': dirname})
except Exception as e:
print(f"FAILED to ls in NAMENODE due to\n{e}")
# check response
if response.status_code // 100 == 2:
# obtain the new working directory
new_dirname = response.json()['dirname']
cur_dir = response.json()['cur_dir']
CURRENT_DIR = cur_dir
print(f"current directory is {new_dirname}")
elif response.status_code == 418:
print("you cannot change directory to a file")
else:
print(f"failed to change directory to {dirname}")
else:
mistake()
def file_info(*arguments):
'''
Displays file size, creation date and time, datanodes on which the file resides
:param filename: name of file to display info about
'''
if len(arguments) == 2:
filename = arguments[1]
try:
response = requests.post(NAMENODE + '/info', json={'filename': filename})
except Exception as e:
print(f"FAILED to get info from NAMENODE due to\n{e}")
return
# check response
if response.status_code // 100 == 2:
file = response.json()['info']
print(f"FILE {filename}\nSIZE {file['size'] / 2**10} KB\nCREATED {file['created_date']}\nDATANODES {file['datanodes']}")
else:
print(response.content.decode())
else:
mistake()
def move_file(*arguments):
'''
Moves file to a new location
:param filename: file name in the current dir
:param path: destination path
'''
if len(arguments) == 3:
filename = arguments[1]
path = arguments[2]
# resolve filename
if path[-1] == '/':
path = path + os.path.basename(filename)
try:
response = requests.post(NAMENODE + '/move', json={'filename': filename, 'path': path})
except Exception as e:
print(f"FAILED to MOVE file in NAMENODE due to\n{e}")
return
# check response
if response.status_code // 100 == 2:
print(f"file {filename} was successfully moved to {path}")
else:
print(response.content.decode())
else:
mistake()
# command to functions mapping
commands = {
"help": show_help,
"init": init,
"touch": create_file,
"get": get_file,
"put": put_file,
"rm": delete_file,
"mkdir": make_directory,
"ls": read_directory,
"cd": change_directory,
"info": file_info,
"mv": move_file,
"cp": copy_file,
"rmdir": delete_directory
}
if __name__ == "__main__":
print("TatDFS client successfully started\nHere is a small help on how to use it")
show_help([1])
try:
response = requests.get(NAMENODE + '/curdir')
if response.status_code // 100 == 2:
CURRENT_DIR = response.json()['current_dir']
else:
print("connection to namenode cannot be established")
except Exception as e:
print("connection to namenode cannot be established")
while True:
args = input("TatDFS𓆏 " + CURRENT_DIR + " $ ").split()
if len(args) == 0:
continue
command = args[0]
if command == "exit":
break
try:
commands[args[0]](*args)
except Exception as e:
print("cannot execute command, please verify that you are using it correctly")
|
{"/namenode.py": ["/FileSystem.py"]}
|
40,702,331
|
TooTiredOne/TatDFS
|
refs/heads/master
|
/testing.py
|
from anytree import Node, RenderTree, find, Resolver
import os
file1 = {"id": 0, "datanodes": [], "size": 32, "metadata": "grrrrrrrrr"}
file2 = {"id": 1, "datanodes": [], "size": 12, "metadata": "dhdjhsgdhjas"}
file3 = {"id": 2, "datanodes": [], "size": 12, "metadata": "dhdjhsgdhjas"}
root = Node("root")
pics = Node('pics', parent=root)
docs = Node('docs', parent=root)
sum14 = Node('summer 2014', parent=pics)
sum14_1 = Node('pic1', parent=sum14, file=file1)
sum14_2 = Node('pic2', parent=sum14, file=file2)
report = Node('report', parent=docs, file=file3)
print(os.path.basename('/dsf/sdf/zhopa'))
# path = 'summer 2014/pic1'
# r = Resolver('name')
# print(r.get(pics, path))
#
# #
#
# path = '/root/pics/summer 2014'
# r = Resolver('name')
# resp = r.get(root, path)
# new_node = Node('new file', parent=resp, file={"id": 3})
#
# new_node = Node('new file2', parent=resp, file={"id": 4})
#
#
# path = '/root/pics/summer 2014/pic2'
# resp = r.get(root, path)
# file = resp.file
# resp.parent = None
#
# resp.parent = docs
#
# print(RenderTree(root))
#node = find(root, lambda x: r.get(root, x) == path)
#print(node)
#print(list(node.children))
# class A:
# def __init__(self):
# self.a = 0
#
# def incr_a(self):
# self.a += 1
#
#
# a = A()
#
# def test():
# a.incr_a()
#
# print(a.a)
# test()
# print(a.a)
# test()
# print(a.a)
|
{"/namenode.py": ["/FileSystem.py"]}
|
40,702,332
|
TooTiredOne/TatDFS
|
refs/heads/master
|
/testing/namenode/FileSystem.py
|
from anytree import Node, RenderTree, Resolver
import random, requests
from datetime import datetime
import os
ROOT_DIR = "root"
HOST = '0.0.0.0'
PORT = 8080
HEARTBEAT_RATE = 1
class FileSystem:
def __init__(self):
self.root = Node(ROOT_DIR, is_file=False)
self.free_space = 1000000000000000000000
self.cur_dir = ROOT_DIR
# current directory
self.cur_node = self.root
self.live_datanodes = [] # store alive datanodes
self.dead_datanodes = [] # store dead datanodes
self.needs_replica = {} # store files that need replicas in dic (node with file: # of needed replicas)
# id of the next file created
self.id = 0
# replication factor
self.replication = 2
# info about files stored in datanodes
# datanode: array of file ids
self.datanodes_files = {}
def get_current_dirname(self):
dirname = '/'
count = 0
for node in self.cur_node.path:
if count == 0:
count += 1
continue
else:
dirname += node.name + '/'
count += 1
return dirname
def update_needs_replica(self, node, remove):
'''
recalculated needs_replica for the given node
:param node: node
:param remove: if true, the node is removed from needs_replica
:return:
'''
if remove:
if node in self.needs_replica.keys():
self.needs_replica.pop(node)
return
cur_replica = len(node.file['datanodes']) # obtaining current replica
# updating needs_replica
if cur_replica < self.replication:
self.needs_replica[node] = self.replication - cur_replica
elif cur_replica == self.replication:
if node in self.needs_replica.keys():
self.needs_replica.pop(node)
def choose_datanodes(self, n=None, exclude=None):
'''
:param n: number of datanodes to return, equals to self.replication if not stated
:param exclude: listed datanodes won't present in the returned list
:return: a list of datanodes of size min(n, len(live_datanodes))
'''
# choose random datanodes to store the file
amount = self.replication
if n:
amount = n
if exclude:
subset = [node for node in self.live_datanodes if node not in exclude]
return random.sample(subset, min(amount, len(subset)))
else:
return random.sample(self.live_datanodes, min(amount, len(self.live_datanodes)))
def create_file(self, filename, parent_node, filesize=0):
# choose datanodes for storing and replicating
datanodes = self.choose_datanodes()
# create file with info
file = {"id": self.id, "datanodes": datanodes, "size": filesize, "created_date": datetime.now()}
# add info about file to info about files in datanodes
for datanode in datanodes:
if datanode in self.datanodes_files.keys():
self.datanodes_files[datanode].append(self.id)
else:
self.datanodes_files[datanode] = [self.id]
# increment id
self.id += 1
# decrement free space
self.free_space -= filesize
# create file in FS tree
node = Node(filename, parent=parent_node, file=file, is_file=True)
self.update_needs_replica(node, remove=False)
return file
def delete_file(self, node):
file = node.file
self.free_space += file['size']
id = file['id']
datanodes = file['datanodes']
for datanode in datanodes:
try:
self.datanodes_files[datanode].remove(id)
except Exception as e:
print(f"file with id {id} not found in {datanode}")
node.parent = None
self.update_needs_replica(node, remove=True)
return file
def create_directory(self, dirname, parent_dir):
node = Node(dirname, parent=parent_dir, is_file=False)
def get_all_files_rec(self, node):
result = []
for child in node.children:
if child.is_file:
self.update_needs_replica(child, remove=True)
result.append(child.file)
else:
result += self.get_all_files_rec(child)
return result
def get_file(self, filename):
'''
Get the node with the given file
:param filename: path to file relative to the current node
:return: node with the given file or None
'''
if filename[0] == '/':
filename = '/root' + filename
r = Resolver("name")
try:
node = r.get(self.cur_node, filename)
if node:
if node.is_file:
return node
else:
return None
else:
return None
except Exception as e:
return None
def get_dir(self, dirname):
'''
Get the node with the given directory
:param dirname: path to direcroty relative to the current node
:return: node with the given directory or None
'''
if len(dirname) >= 1:
if dirname[0] == '/':
dirname = '/root' + dirname
r = Resolver("name")
try:
node = r.get(self.cur_node, dirname)
if node:
if node.is_file:
return None
else:
return node
else:
return None
except Exception as e:
return None
def get_filenode_by_id(self, node, id):
'''
Traverse the tree and return the node storing the file with corresponding id
:param id: int
:param node: node from where start traversal
:return: node
'''
if node.is_file:
if node.file['id'] == id:
return node
else:
return None
else:
for child in node.children:
result = self.get_filenode_by_id(child, id)
if result:
return result
break
return None
def protocol_lazarus(self, datanode):
'''
Resurrection of the node
:param node:
'''
response = requests.get(datanode + '/format')
if response.status_code // 100 != 2:
print(f"couldn't resurrect datanode: {datanode}")
else:
fs.live_datanodes.append(datanode)
fs.dead_datanodes.remove(datanode)
fs.datanodes_files[datanode] = []
def replicate_on_dead(self, dead_datanode):
'''
Replicating files from dead datanode to alive
:param index: index of the dead datanode in self.live_datanodes
'''
print(f"started replication on dead {dead_datanode}")
# ids of file stored in the dead node
print(f"datanodes_files: {self.datanodes_files}")
file_ids = self.datanodes_files[dead_datanode]
for id in file_ids:
print(f"\tprocessing file with id: {id}")
cur_node = self.get_filenode_by_id(self.root, id) # node storing the file
file = cur_node.file # file itself
print(f"\tfile: {file}")
file['datanodes'].remove(dead_datanode) # removing the dead node from datanodes list of the file
new_datanodes = self.choose_datanodes(n=1, exclude=file['datanodes']) # acquiring new datanode
print(f"\tnew_datanodes: {new_datanodes}")
if len(new_datanodes) > 0:
print("\tavailable datanode was found")
new_datanode = new_datanodes[0]
for datanode in file['datanodes']:
print(f"\t\tstarted replicating from {datanode}")
try:
response = requests.post(new_datanode + '/get-replica', json={'file_id': id, 'datanode': datanode})
except Exception as e:
print(f"Exception while replicating\n{e}")
continue
if response.status_code // 100 == 2:
if new_datanode in self.datanodes_files.keys():
self.datanodes_files[new_datanode].append(id)
else:
self.datanodes_files[new_datanode] = [id]
print(f"\t\tfile was replicated")
break
else:
print(f"\t\tfile was NOT replicated")
file['datanodes'] += new_datanodes # updating the list of datanodes of the file
cur_node.file = file
print(f"\tupdated file datanodes: {file}")
self.update_needs_replica(cur_node, remove=False) # updating needs_replica
print(f"\tupdated needs_replica: {self.needs_replica}")
self.datanodes_files[dead_datanode] = []
fs = FileSystem()
|
{"/namenode.py": ["/FileSystem.py"]}
|
40,768,764
|
iSebDev/filewriter-python
|
refs/heads/main
|
/src/extra/placeholders.py
|
import time as times
class placehold:
def variable(name=None, var=None, time=None):
if not name:
try:
except KeyError
else:
return name + var
return times.sleep(time)
if var == times.sleep:
print("Error with function Times! Times not is a variable in placeholders")
break
for name in variable:
if name[0] > name[20]:
print("Error! Placeholder name error 'args > 20'.")
break
elif(name[0] > name[20]):
return placehold.variable(name=None,var=None,time=None)
|
{"/run.py": ["/config.py"], "/config.py": ["/src/variables.py"]}
|
40,768,765
|
iSebDev/filewriter-python
|
refs/heads/main
|
/config.py
|
from src.variables import vars as v
## v.variable_name
## Config variables in .src/variables.py
class config:
FILE="paraadads.txt" ## FILE NAME + EXTENSION || example.txt || or other extension
OS_ALIAS="my os aliases"
class message:
TEXT = f"""
Hi1
HI + 2
Hi 3 _
Example 1 2 3 {v.variable1}
{v.variable2}
{v.variable3}
{v.variable4}
{v.variable5}
{v.variable6}
"""
class options:
history = False
os_aliases = True
|
{"/run.py": ["/config.py"], "/config.py": ["/src/variables.py"]}
|
40,768,766
|
iSebDev/filewriter-python
|
refs/heads/main
|
/src/write.py
|
import time
import datetime
from time import sleep as wait
def __WRITE__(file=None, text=None):
if not file:
print("Please, set a file in config.py")
elif(file == None):
print("Please, set a file in config.py")
else:
with open(file, 'w') as f:
f.write(text)
|
{"/run.py": ["/config.py"], "/config.py": ["/src/variables.py"]}
|
40,768,767
|
iSebDev/filewriter-python
|
refs/heads/main
|
/src/variables.py
|
import datetime
import random
class vars:
variable1 = 1+1 # Simple sum in variable
variable2 = "Hi" # Simple str var
variable3 = "Hi {}".format(15-5) # Variables in str of var
variable4 = datetime.datetime.utcnow() # Get time
variable5 = random.randint(1,100) # Get random number variable
variable6 = random.choice([variable1,variable2,variable3]) # Get random variable
|
{"/run.py": ["/config.py"], "/config.py": ["/src/variables.py"]}
|
40,768,768
|
iSebDev/filewriter-python
|
refs/heads/main
|
/run.py
|
from config import config as conf
from config import message
from config import options
from time import sleep as wait
import datetime
from src import write
import os
import json
def run():
write.__WRITE__(file=conf.FILE, text=message.TEXT)
wait(5)
print(f"File: {str(os.path.isfile(conf.FILE))}")
if options.os_aliases == True:
print("The file '{}' was written as {} by {} !".format(conf.FILE, datetime.datetime.utcnow(), conf.OS_ALIAS))
else:
print("The file '{}' was written as {} by {} !".format(conf.FILE, datetime.datetime.utcnow(), os.name))
wait(10)
run()
|
{"/run.py": ["/config.py"], "/config.py": ["/src/variables.py"]}
|
40,837,686
|
NaxF11/12CharacterBattleOverlay
|
refs/heads/master
|
/12CB.py
|
import pygame, sys, time, remix_char
from pygame.locals import *
def opcion_1():
pygame.font.init()
myfont = pygame.font.SysFont("Comic Sans MS", 10)
myfont_stocks = pygame.font.SysFont("Comic Sans MS", 27)
cont_texto = 48
cont_texto2 = 48
texto2 = "Designed by Nax & Bob"
texto3 = "48"
texto_2 = myfont.render(texto2,False,(255,255,255))
texto_3 = myfont_stocks.render(texto3,False,(255,255,255))
texto_4 = myfont_stocks.render(texto3,False,(255,255,255))
# Texto
textoCK = False
texto2CK = False
# Creación de la ventana
pygame.init()
ventana = pygame.display.set_mode((800,645))
pygame.display.set_caption("12 Character Battle Chart")
pygame.display.set_icon(pygame.image.load("images/smash_ico.png"))
# Creacion de las imagenes -----------------------------------------------
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# Fila 1
# Luigi
stock_luigi_1 = pygame.image.load("images/stock_luigi.jpg")
stock_luigi_1 = pygame.transform.scale(stock_luigi_1, (15,15))
stock_luigi_1_CK = True
stock_luigi_2_CK = True
stock_luigi_3_CK = True
stock_luigi_4_CK = True
contador_luigi = 4
luigi = pygame.image.load("images/luigi.jpg")
luigi = pygame.transform.scale(luigi, (100, 100))
luigid = pygame.image.load("images/luigid.jpg")
luigid = pygame.transform.scale(luigid, (100,100))
luigiCK = True
# Mario
stock_mario_1 = pygame.image.load("images/stock_luigi.jpg")
stock_mario_1 = pygame.transform.scale(stock_mario_1, (15,15))
stock_mario_1_CK = True
stock_mario_2_CK = True
stock_mario_3_CK = True
stock_mario_4_CK = True
contador_mario = 4
mario = pygame.image.load("images/mario.jpg")
mario = pygame.transform.scale(mario, (100, 100))
mariod = pygame.image.load("images/mariod.jpg")
mariod = pygame.transform.scale(mariod, (100,100))
marioCK = True
# DK
stock_dk_1 = pygame.image.load("images/banana.jpg")
stock_dk_1 = pygame.transform.scale(stock_dk_1, (22,22))
stock_dk_1_CK = True
stock_dk_2_CK = True
stock_dk_3_CK = True
stock_dk_4_CK = True
contador_dk = 4
dk = pygame.image.load("images/dk.jpg")
dk = pygame.transform.scale(dk, (100,100))
dkd = pygame.image.load("images/dkd.jpg")
dkd = pygame.transform.scale(dkd, (100,100))
dkCK = True
# Link
stock_link_1 = pygame.image.load("images/heartrojo.png")
stock_link_1 = pygame.transform.scale(stock_link_1, (30,30))
stock_link_55 = pygame.image.load("images/heartnegro.png")
stock_link_55 = pygame.transform.scale(stock_link_55, (30,30))
life_past = pygame.image.load("images/lifepast.png")
life_past = pygame.transform.scale(life_past, (60,60))
stock_link_1_CK = True
stock_link_2_CK = True
stock_link_3_CK = True
stock_link_4_CK = True
life_pastCK = True
contador_link = 4
link = pygame.image.load("images/link.jpg")
link = pygame.transform.scale(link, (100,100))
linkd = pygame.image.load("images/linkd.jpg")
linkd = pygame.transform.scale(linkd, (100,100))
linkCK = True
# Samus
energy = pygame.image.load("images/energy0.png")
energy = pygame.transform.scale(energy, (40,10))
stock_samus_1 = pygame.image.load("images/pink.png")
stock_samus_1 = pygame.transform.scale(stock_samus_1, (15,15))
stock_samus_5 = pygame.image.load("images/brown.png")
stock_samus_5 = pygame.transform.scale(stock_samus_5, (15,15))
stock_samus_1_CK = True
stock_samus_2_CK = True
stock_samus_3_CK = True
stock_samus_4_CK = True
energyCK = True
contador_samus = 4
samus = pygame.image.load("images/samus.jpg")
samus = pygame.transform.scale(samus, (100,100))
samusd = pygame.image.load("images/samusd.jpg")
samusd = pygame.transform.scale(samusd, (100,100))
samusCK = True
# C. Falcon
stock_falcon_0 = pygame.image.load("images/fz_energy1.png")
stock_falcon_0 = pygame.transform.scale(stock_falcon_0, (90,25))
stock_falcon_1 = pygame.image.load("images/fz_energy2.png")
stock_falcon_1 = pygame.transform.scale(stock_falcon_1, (85,20))
bar1 = pygame.image.load("images/bar1.png")
bar1 = pygame.transform.scale(bar1, (56,2))
bar2 = pygame.image.load("images/bar2.png")
bar2 = pygame.transform.scale(bar2, (2,16))
bar22CK = True
bar22CK_2 = True
bar1CK = True
bar2CK = True
stock_falcon_0_CK = True
stock_falcon_1_CK = True
stock_falcon_2_CK = True
stock_falcon_3_CK = True
stock_falcon_4_CK = True
contador_falcon = 4
falcon = pygame.image.load("images/falcon2.jpg")
falcon = pygame.transform.scale(falcon, (100,100))
falcond = pygame.image.load("images/falcond.jpg")
falcond = pygame.transform.scale(falcond, (100,100))
falconCK = True
# Ness
stock_ness_1 = pygame.image.load("images/hp.png")
stock_ness_1 = pygame.transform.scale(stock_ness_1, (19,17))
stock_ness_2 = pygame.image.load("images/cero.png")
stock_ness_2 = pygame.transform.scale(stock_ness_2, (17,17))
stock_ness_3 = pygame.image.load("images/cero.png")
stock_ness_3 = pygame.transform.scale(stock_ness_3, (17,17))
stock_ness_4 = pygame.image.load("images/cero.png")
stock_ness_4 = pygame.transform.scale(stock_ness_4, (17,17))
stock_ness_5 = pygame.image.load("images/uno.png")
stock_ness_5 = pygame.transform.scale(stock_ness_5, (17,17))
stock_ness_6 = pygame.image.load("images/dos.png")
stock_ness_6 = pygame.transform.scale(stock_ness_6, (17,17))
stock_ness_7 = pygame.image.load("images/tres.png")
stock_ness_7 = pygame.transform.scale(stock_ness_7, (17,17))
stock_ness_8 = pygame.image.load("images/cuatro.png")
stock_ness_8 = pygame.transform.scale(stock_ness_8, (17,17))
stock_ness_1_CK = True
stock_ness_2_CK = True
stock_ness_3_CK = True
stock_ness_4_CK = True
stock_ness_5_CK = False
stock_ness_6_CK = False
stock_ness_7_CK = False
stock_ness_8_CK = True
contador_ness = 4
ness = pygame.image.load("images/ness.jpg")
ness = pygame.transform.scale(ness, (100,100))
nessd = pygame.image.load("images/nessd.jpg")
nessd = pygame.transform.scale(nessd, (100,100))
nessCK = True
# Yoshi
stock_yoshi_1 = pygame.image.load("images/egg.jpg")
stock_yoshi_1 = pygame.transform.scale(stock_yoshi_1, (18,18))
stock_yoshi_1_CK = True
stock_yoshi_2_CK = True
stock_yoshi_3_CK = True
stock_yoshi_4_CK = True
contador_yoshi = 4
yoshi = pygame.image.load("images/yoshi.jpg")
yoshi = pygame.transform.scale(yoshi, (100,100))
yoshid = pygame.image.load("images/yoshid.jpg")
yoshid = pygame.transform.scale(yoshid, (100,100))
yoshiCK = True
# Kirby
stock_kirby_1 = pygame.image.load("images/tomato.png")
stock_kirby_1 = pygame.transform.scale(stock_kirby_1, (30,30))
stock_kirby_1_CK = True
stock_kirby_2_CK = True
stock_kirby_3_CK = True
stock_kirby_4_CK = True
contador_kirby = 4
kirby = pygame.image.load("images/kirby.jpg")
kirby = pygame.transform.scale(kirby, (100,100))
kirbyd = pygame.image.load("images/kirbyd.jpg")
kirbyd = pygame.transform.scale(kirbyd, (100,100))
kirbyCK = True
# Fox
stock_fox_1 = pygame.image.load("images/ship.jpg")
stock_fox_1 = pygame.transform.scale(stock_fox_1, (18,18))
stock_fox_1_CK = True
stock_fox_2_CK = True
stock_fox_3_CK = True
stock_fox_4_CK = True
contador_fox = 4
fox = pygame.image.load("images/fox.jpg")
fox = pygame.transform.scale(fox, (100,100))
foxd = pygame.image.load("images/foxd.jpg")
foxd = pygame.transform.scale(foxd, (100,100))
foxCK = True
# Pikachu
stock_pikachu_1 = pygame.image.load("images/pokeball.jpg")
stock_pikachu_1 = pygame.transform.scale(stock_pikachu_1, (19,19))
stock_pikachu_1_CK = True
stock_pikachu_2_CK = True
stock_pikachu_3_CK = True
stock_pikachu_4_CK = True
contador_pikachu = 5
pikachu = pygame.image.load("images/pikachu.jpg")
pikachu = pygame.transform.scale(pikachu, (100,100))
pikachud = pygame.image.load("images/pikachud.jpg")
pikachud = pygame.transform.scale(pikachud, (100,100))
pikachuCK = True
# Jigglypuff
stock_jigglypuff_1 = pygame.image.load("images/pokeball.jpg")
stock_jigglypuff_1 = pygame.transform.scale(stock_jigglypuff_1, (19,19))
stock_jigglypuff_1_CK = True
stock_jigglypuff_2_CK = True
stock_jigglypuff_3_CK = True
stock_jigglypuff_4_CK = True
contador_jigglypuff = 4
jigglypuff = pygame.image.load("images/jigglypuff.jpg")
jigglypuff = pygame.transform.scale(jigglypuff, (100,100))
jigglypuffd = pygame.image.load("images/jigglypuffd.jpg")
jigglypuffd = pygame.transform.scale(jigglypuffd, (100,100))
jigglypuffCK = True
#---------------------------------------------------------------------
#---------------------------------------------------------------------
#---------------------------------------------------------------------
# Fila 2
# Luigi
stock_luigi_1_CK_2 = True
stock_luigi_2_CK_2 = True
stock_luigi_3_CK_2 = True
stock_luigi_4_CK_2 = True
contador_luigi_2 = 4
luigiCK1 = True
# Mario
stock_mario_1_CK_2 = True
stock_mario_2_CK_2 = True
stock_mario_3_CK_2 = True
stock_mario_4_CK_2 = True
contador_mario_2 = 4
marioCK = True
marioCK1 = True
# DK
stock_dk_1_CK_2 = True
stock_dk_2_CK_2 = True
stock_dk_3_CK_2 = True
stock_dk_4_CK_2 = True
contador_dk_2 = 4
dkCK1 = True
# Link
stock_link_1_CK_2 = True
stock_link_2_CK_2 = True
stock_link_3_CK_2 = True
stock_link_4_CK_2 = True
life_pastCK1 = True
contador_link_2 = 4
linkCK1 = True
# Samus
stock_samus_1_CK_2 = True
stock_samus_2_CK_2 = True
stock_samus_3_CK_2 = True
stock_samus_4_CK_2 = True
contador_samus_2 = 4
samusCK1 = True
energy2CK = True
# C. Falcon
bar22CK_2 = True
bar22CK_2_2 = True
bar1CK_2 = True
bar2CK_2 = True
stock_falcon_0_CK_2 = True
stock_falcon_1_CK_2 = True
stock_falcon_2_CK_2 = True
stock_falcon_3_CK_2 = True
stock_falcon_4_CK_2 = True
contador_falcon_2 = 4
falconCK1 = True
# Ness
stock_ness_1_CK_2 = True
stock_ness_2_CK_2 = True
stock_ness_3_CK_2 = True
stock_ness_4_CK_2 = True
stock_ness_5_CK_2 = False
stock_ness_6_CK_2 = False
stock_ness_7_CK_2 = False
stock_ness_8_CK_2 = True
contador_ness_2 = 4
nessCK1 = True
# Yoshi
stock_yoshi_1_CK_2 = True
stock_yoshi_2_CK_2 = True
stock_yoshi_3_CK_2 = True
stock_yoshi_4_CK_2 = True
contador_yoshi_2 = 4
yoshiCK1 = True
# Kirby
stock_kirby_1_CK_2 = True
stock_kirby_2_CK_2 = True
stock_kirby_3_CK_2 = True
stock_kirby_4_CK_2 = True
contador_kirby_2 = 4
kirbyCK1 = True
# Fox
stock_fox_1_CK_2 = True
stock_fox_2_CK_2 = True
stock_fox_3_CK_2 = True
stock_fox_4_CK_2 = True
contador_fox_2 = 4
foxCK1 = True
# Pikachu
stock_pikachu_1_CK_2 = True
stock_pikachu_2_CK_2 = True
stock_pikachu_3_CK_2 = True
stock_pikachu_4_CK_2 = True
contador_pikachu_2 = 4
pikachuCK1 = True
# Jigglypuff
stock_jigglypuff_1_CK_2 = True
stock_jigglypuff_2_CK_2 = True
stock_jigglypuff_3_CK_2 = True
stock_jigglypuff_4_CK_2 = True
contador_jigglypuff_2 = 4
jigglypuffCK1 = True
# Color del fondo
negro = (0,0,0)
# Mouse
cursor = pygame.image.load("images/fan.png")
cursor = pygame.transform.scale(cursor, (40,40))
pygame.mouse.set_visible(False)
# Boton Reset
reset = pygame.image.load("images/reset.png")
reset = pygame.transform.scale(reset, (90,60))
resetCK = True
# Choose a Mode
modo = pygame.image.load("images/mode.png")
#modo = pygame.transform.scale(modo, (300,200))
modoCK = True
# 1) Escoger opcion
opc = True
opc_1 = False
opc_2 = False
# 2) Escoger opcion
carta_1 = pygame.image.load("images/carta_1.png")
carta_1 = pygame.transform.scale(carta_1, (160, 220))
carta_1CK = True
s_vanilla = pygame.image.load("images/svanilla.png")
s_vanilla = pygame.transform.scale(s_vanilla, (190, 100))
s_remix = pygame.image.load("images/sremix.png")
s_remix = pygame.transform.scale(s_remix, (150, 120))
s_vanilla1 = pygame.image.load("images/svanilla.png")
s_vanilla1 = pygame.transform.scale(s_vanilla1, (150, 70))
s_remix1 = pygame.image.load("images/sremix.png")
s_remix1 = pygame.transform.scale(s_remix1, (120, 90))
plus = pygame.image.load("images/plus.png")
plus = pygame.transform.scale(plus,(110,70))
s_vanillaCK = True
s_remixCK = True
s_vanillaCK1 = True
s_remixCK1 = True
plusCK = True
# Boton start
start_b = pygame.image.load("images/startb.png")
start_b = pygame.transform.scale(start_b, (80,40))
start_bCK = True
# Smash Remix Creation
#----------------------------------------------------------------
#------------Accion de mostrar y no la imagen---------------
#----------------------------------------------------------------
while True:
# Menu
if modoCK == True:
ventana.blit(modo,(0,0))
if s_vanillaCK == True:
ventana.blit(s_vanilla, (70,300))
if s_remixCK == True:
ventana.blit(s_remix, (320,300))
if s_vanillaCK1 == True:
ventana.blit(s_vanilla1, (540,280))
if s_remixCK1 == True:
ventana.blit(s_remix1, (640,340))
if plusCK == True:
ventana.blit(plus, (590,320))
# Mostrar mouse
cor = pygame.mouse.get_pos()
ventana.blit(cursor, cor)
if start_bCK == True:
ventana.blit(start_b, (130, 500))
ventana.blit(start_b, (355, 500))
#ventana.blit(start_b, (600, 500)) PENDIENTE ----------
# Mostrar mouse
cor = pygame.mouse.get_pos()
ventana.blit(cursor, cor)
else:
ventana.blit(start_b, (-400, -400))
# Opcion 1
if opc_1 == True:
ventana.fill(negro)
if resetCK == True:
ventana.blit(reset,(360,570))
#---------------------------------------------------------------
#---------------------------------------------------------------
#---------------------------------------------------------------
# Fila 1
# Luigi
if luigiCK == True:
ventana.blit(luigi,(0,0))
else:
ventana.blit(luigid,(0,0))
if stock_luigi_1_CK == True:
ventana.blit(stock_luigi_1, (10,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_2_CK == True:
ventana.blit(stock_luigi_1, (30,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_3_CK == True:
ventana.blit(stock_luigi_1, (50,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_4_CK == True:
ventana.blit(stock_luigi_1, (70,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
# Mario
if marioCK == True:
ventana.blit(mario,(0,100))
else:
ventana.blit(mariod,(0,100))
if stock_mario_1_CK == True:
ventana.blit(stock_mario_1, (10,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_2_CK == True:
ventana.blit(stock_mario_1, (30,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_3_CK == True:
ventana.blit(stock_mario_1, (50,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_4_CK == True:
ventana.blit(stock_mario_1, (70,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
# DK
if dkCK == True:
ventana.blit(dk,(0,200))
else:
ventana.blit(dkd,(0,200))
if stock_dk_1_CK == True:
ventana.blit(stock_dk_1, (8,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_2_CK == True:
ventana.blit(stock_dk_1, (28,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_3_CK == True:
ventana.blit(stock_dk_1, (48,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_4_CK == True:
ventana.blit(stock_dk_1, (68,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
# Link
if linkCK == True:
ventana.blit(link,(0,300))
else:
ventana.blit(linkd,(0,300))
if stock_link_1_CK == True:
ventana.blit(stock_link_1, (4,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (4,375))
if stock_link_2_CK == True:
ventana.blit(stock_link_1, (24,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (24,375))
if stock_link_3_CK == True:
ventana.blit(stock_link_1, (44,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (44,375))
if stock_link_4_CK == True:
ventana.blit(stock_link_1, (64,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (64,375))
if life_pastCK == True:
ventana.blit(life_past, (20, 350))
else:
ventana.blit(life_past, (20, 350))
# Samus
if samusCK == True:
ventana.blit(samus,(0,400))
else:
ventana.blit(samusd,(0,400))
if stock_samus_1_CK == True:
ventana.blit(stock_samus_1, (14,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (14,480))
if stock_samus_2_CK == True:
ventana.blit(stock_samus_1, (30,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (30,480))
if stock_samus_3_CK == True:
ventana.blit(stock_samus_1, (46,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (46,480))
if stock_samus_4_CK == True:
ventana.blit(stock_samus_1, (62,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (62,480))
if energyCK == True:
ventana.blit(energy, (14,490))
else:
ventana.blit(energy, (14,490))
# C. Falcon
if falconCK == True:
ventana.blit(falcon,(0,500))
else:
ventana.blit(falcond,(0,500))
if stock_falcon_0_CK == True:
ventana.blit(stock_falcon_0, (5,575))
else:
ventana.blit(stock_falcon_0, (-40,-40))
if stock_falcon_1_CK == True:
ventana.blit(stock_falcon_1, (6,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_2_CK == True:
ventana.blit(stock_falcon_1, (20,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_3_CK == True:
ventana.blit(stock_falcon_1, (34,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_4_CK == True:
ventana.blit(stock_falcon_1, (48,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if bar1CK == True:
ventana.blit(bar1, (35,581))
else:
ventana.blit(bar1, (35,581))
if bar2CK == True:
ventana.blit(bar1, (35,597))
else:
ventana.blit(bar1, (35,597))
if bar22CK == True:
ventana.blit(bar2, (35,583))
else:
ventana.blit(bar2, (35,583))
if bar22CK_2 == True:
ventana.blit(bar2, (89,582))
# Ness
if nessCK == True:
ventana.blit(ness,(100,0))
else:
ventana.blit(nessd,(100,0))
if stock_ness_1_CK == True:
ventana.blit(stock_ness_1, (110,80))
else:
ventana.blit(stock_ness_1, (110,80))
if stock_ness_2_CK == True:
ventana.blit(stock_ness_2, (133,80))
else:
ventana.blit(stock_ness_2, (133,80))
if stock_ness_3_CK == True:
ventana.blit(stock_ness_3, (150,80))
else:
ventana.blit(stock_ness_3, (150,80))
if stock_ness_4_CK == True:
ventana.blit(stock_ness_4, (167,80))
else:
ventana.blit(stock_ness_4, (167,80))
if stock_ness_5_CK == True:
ventana.blit(stock_ness_5, (167,80))
else:
ventana.blit(stock_ness_5, (-40,-40))
if stock_ness_6_CK == True:
ventana.blit(stock_ness_6, (167,80))
else:
ventana.blit(stock_ness_6, (-40,-40))
if stock_ness_7_CK == True:
ventana.blit(stock_ness_7, (167,80))
else:
ventana.blit(stock_ness_7, (-40,-40))
if stock_ness_8_CK == True:
ventana.blit(stock_ness_8, (167,80))
else:
ventana.blit(stock_ness_8, (-40,-40))
# Yoshi
if yoshiCK == True:
ventana.blit(yoshi,(100,100))
else:
ventana.blit(yoshid,(100,100))
if stock_yoshi_1_CK == True:
ventana.blit(stock_yoshi_1, (110,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_2_CK == True:
ventana.blit(stock_yoshi_1, (130,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_3_CK == True:
ventana.blit(stock_yoshi_1, (150,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_4_CK == True:
ventana.blit(stock_yoshi_1, (170,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
# Kirby
if kirbyCK == True:
ventana.blit(kirby,(100,200))
else:
ventana.blit(kirbyd,(100,200))
if stock_kirby_1_CK == True:
ventana.blit(stock_kirby_1, (105,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_2_CK == True:
ventana.blit(stock_kirby_1, (125,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_3_CK == True:
ventana.blit(stock_kirby_1, (145,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_4_CK == True:
ventana.blit(stock_kirby_1, (165,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
# Fox
if foxCK == True:
ventana.blit(fox,(100,300))
else:
ventana.blit(foxd,(100,300))
if stock_fox_1_CK == True:
ventana.blit(stock_fox_1, (110,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_2_CK == True:
ventana.blit(stock_fox_1, (130,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_3_CK == True:
ventana.blit(stock_fox_1, (150,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_4_CK == True:
ventana.blit(stock_fox_1, (170,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
# Pikachu
if pikachuCK == True:
ventana.blit(pikachu,(100,400))
else:
ventana.blit(pikachud,(100,400))
if stock_pikachu_1_CK == True:
ventana.blit(stock_pikachu_1, (110,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_2_CK == True:
ventana.blit(stock_pikachu_1, (130,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_3_CK == True:
ventana.blit(stock_pikachu_1, (150,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_4_CK == True:
ventana.blit(stock_pikachu_1, (170,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
# Jigglypuff
if jigglypuffCK == True:
ventana.blit(jigglypuff,(100,500))
else:
ventana.blit(jigglypuffd,(100,500))
if stock_jigglypuff_1_CK == True:
ventana.blit(stock_jigglypuff_1, (110,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_2_CK == True:
ventana.blit(stock_jigglypuff_1, (130,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_3_CK == True:
ventana.blit(stock_jigglypuff_1, (150,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_4_CK == True:
ventana.blit(stock_jigglypuff_1, (170,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
# Fila 2
# Luigi
if luigiCK1 == True:
ventana.blit(luigi,(600,0))
else:
ventana.blit(luigid,(600,0))
if stock_luigi_1_CK_2 == True:
ventana.blit(stock_luigi_1, (610,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_2_CK_2 == True:
ventana.blit(stock_luigi_1, (630,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_3_CK_2 == True:
ventana.blit(stock_luigi_1, (650,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
if stock_luigi_4_CK_2 == True:
ventana.blit(stock_luigi_1, (670,80))
else:
ventana.blit(stock_luigi_1, (-40,-40))
# Mario
if marioCK1 == True:
ventana.blit(mario,(600,100))
else:
ventana.blit(mariod,(600,100))
if stock_mario_1_CK_2 == True:
ventana.blit(stock_mario_1, (610,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_2_CK_2 == True:
ventana.blit(stock_mario_1, (630,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_3_CK_2 == True:
ventana.blit(stock_mario_1, (650,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
if stock_mario_4_CK_2 == True:
ventana.blit(stock_mario_1, (670,180))
else:
ventana.blit(stock_mario_1, (-40,-40))
# DK
if dkCK1 == True:
ventana.blit(dk,(600,200))
else:
ventana.blit(dkd,(600,200))
if stock_dk_1_CK_2 == True:
ventana.blit(stock_dk_1, (608,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_2_CK_2 == True:
ventana.blit(stock_dk_1, (628,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_3_CK_2 == True:
ventana.blit(stock_dk_1, (648,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
if stock_dk_4_CK_2 == True:
ventana.blit(stock_dk_1, (668,275))
else:
ventana.blit(stock_dk_1, (-40,-40))
# Link
if linkCK1 == True:
ventana.blit(link,(600,300))
else:
ventana.blit(linkd,(600,300))
if stock_link_1_CK_2 == True:
ventana.blit(stock_link_1, (604,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (604,375))
if stock_link_2_CK_2 == True:
ventana.blit(stock_link_1, (624,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (624,375))
if stock_link_3_CK_2 == True:
ventana.blit(stock_link_1, (644,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (644,375))
if stock_link_4_CK_2 == True:
ventana.blit(stock_link_1, (664,374))
else:
ventana.blit(stock_link_1, (-40,-40))
ventana.blit(stock_link_55, (664,375))
if life_pastCK1 == True:
ventana.blit(life_past, (620, 350))
else:
ventana.blit(life_past, (620, 350))
# Samus
if samusCK1 == True:
ventana.blit(samus,(600,400))
else:
ventana.blit(samusd,(600,400))
if stock_samus_1_CK_2 == True:
ventana.blit(stock_samus_1, (614,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (614,480))
if stock_samus_2_CK_2 == True:
ventana.blit(stock_samus_1, (630,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (630,480))
if stock_samus_3_CK_2 == True:
ventana.blit(stock_samus_1, (646,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (646,480))
if stock_samus_4_CK_2 == True:
ventana.blit(stock_samus_1, (662,480))
else:
ventana.blit(stock_samus_1, (-40,-40))
ventana.blit(stock_samus_5, (662,480))
if energy2CK == True:
ventana.blit(energy, (614,490))
else:
ventana.blit(energy, (614,490))
# Falcon
if falconCK1 == True:
ventana.blit(falcon,(600,500))
else:
ventana.blit(falcond,(600,500))
if stock_falcon_0_CK_2 == True:
ventana.blit(stock_falcon_0, (605,575))
else:
ventana.blit(stock_falcon_0, (-40,-40))
if stock_falcon_1_CK_2 == True:
ventana.blit(stock_falcon_1, (606,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_2_CK_2 == True:
ventana.blit(stock_falcon_1, (620,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_3_CK_2 == True:
ventana.blit(stock_falcon_1, (634,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if stock_falcon_4_CK_2 == True:
ventana.blit(stock_falcon_1, (648,580))
else:
ventana.blit(stock_falcon_1, (-40,-40))
if bar1CK_2 == True:
ventana.blit(bar1, (635,581))
else:
ventana.blit(bar1, (635,581))
if bar2CK_2 == True:
ventana.blit(bar1, (635,597))
else:
ventana.blit(bar1, (635,597))
if bar22CK_2 == True:
ventana.blit(bar2, (635,583))
else:
ventana.blit(bar2, (635,583))
if bar22CK_2_2 == True:
ventana.blit(bar2, (689,582))
# Ness
if nessCK1 == True:
ventana.blit(ness,(700,0))
else:
ventana.blit(nessd,(700,0))
if stock_ness_1_CK_2 == True:
ventana.blit(stock_ness_1, (710,80))
else:
ventana.blit(stock_ness_1, (710,80))
if stock_ness_2_CK_2 == True:
ventana.blit(stock_ness_2, (733,80))
else:
ventana.blit(stock_ness_2, (733,80))
if stock_ness_3_CK_2 == True:
ventana.blit(stock_ness_3, (750,80))
else:
ventana.blit(stock_ness_3, (750,80))
if stock_ness_4_CK_2 == True:
ventana.blit(stock_ness_4, (767,80))
else:
ventana.blit(stock_ness_4, (767,80))
if stock_ness_5_CK_2 == True:
ventana.blit(stock_ness_5, (767,80))
else:
ventana.blit(stock_ness_5, (-40,-40))
if stock_ness_6_CK_2 == True:
ventana.blit(stock_ness_6, (767,80))
else:
ventana.blit(stock_ness_6, (-40,-40))
if stock_ness_7_CK_2 == True:
ventana.blit(stock_ness_7, (767,80))
else:
ventana.blit(stock_ness_7, (-40,-40))
if stock_ness_8_CK_2 == True:
ventana.blit(stock_ness_8, (767,80))
else:
ventana.blit(stock_ness_8, (-40,-40))
# Yoshi
if yoshiCK1 == True:
ventana.blit(yoshi,(700,100))
else:
ventana.blit(yoshid,(700,100))
if stock_yoshi_1_CK_2 == True:
ventana.blit(stock_yoshi_1, (710,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_2_CK_2 == True:
ventana.blit(stock_yoshi_1, (730,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_3_CK_2 == True:
ventana.blit(stock_yoshi_1, (750,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
if stock_yoshi_4_CK_2 == True:
ventana.blit(stock_yoshi_1, (770,180))
else:
ventana.blit(stock_yoshi_1, (-40,-40))
# Kirby
if kirbyCK1 == True:
ventana.blit(kirby,(700,200))
else:
ventana.blit(kirbyd,(700,200))
if stock_kirby_1_CK_2 == True:
ventana.blit(stock_kirby_1, (705,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_2_CK_2 == True:
ventana.blit(stock_kirby_1, (725,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_3_CK_2 == True:
ventana.blit(stock_kirby_1, (745,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
if stock_kirby_4_CK_2 == True:
ventana.blit(stock_kirby_1, (765,270))
else:
ventana.blit(stock_kirby_1, (-40,-40))
# Fox
if foxCK1 == True:
ventana.blit(fox,(700,300))
else:
ventana.blit(foxd,(700,300))
if stock_fox_1_CK_2 == True:
ventana.blit(stock_fox_1, (710,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_2_CK_2 == True:
ventana.blit(stock_fox_1, (730,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_3_CK_2 == True:
ventana.blit(stock_fox_1, (750,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
if stock_fox_4_CK_2 == True:
ventana.blit(stock_fox_1, (770,378))
else:
ventana.blit(stock_fox_1, (-40,-40))
# Pikachu
if pikachuCK1 == True:
ventana.blit(pikachu,(700,400))
else:
ventana.blit(pikachud,(700,400))
if stock_pikachu_1_CK_2 == True:
ventana.blit(stock_pikachu_1, (710,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_2_CK_2 == True:
ventana.blit(stock_pikachu_1, (730,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_3_CK_2 == True:
ventana.blit(stock_pikachu_1, (750,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
if stock_pikachu_4_CK_2 == True:
ventana.blit(stock_pikachu_1, (770,480))
else:
ventana.blit(stock_pikachu_1, (-40,-40))
# Jigglypuff
if jigglypuffCK1 == True:
ventana.blit(jigglypuff,(700,500))
else:
ventana.blit(jigglypuffd,(700,500))
if stock_jigglypuff_1_CK_2 == True:
ventana.blit(stock_jigglypuff_1, (710,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_2_CK_2 == True:
ventana.blit(stock_jigglypuff_1, (730,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_3_CK_2 == True:
ventana.blit(stock_jigglypuff_1, (750,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if stock_jigglypuff_4_CK_2 == True:
ventana.blit(stock_jigglypuff_1, (770,580))
else:
ventana.blit(stock_jigglypuff_1, (-40,-40))
if textoCK == True:
texto3 = str(cont_texto)
texto_3 = myfont_stocks.render(texto3,False,(255,255,255))
ventana.blit(texto_3,(83,597))
else:
ventana.blit(texto_3,(83,597))
if texto2CK == True:
texto3 = str(cont_texto2)
texto_4 = myfont_stocks.render(texto3,False,(255,255,255))
ventana.blit(texto_4,(683,597))
else:
ventana.blit(texto_4,(683,597))
# Mostrar version del programa y los creadores
ventana.blit(texto_2,(690,631))
# Mostrar mouse
cor = pygame.mouse.get_pos()
ventana.blit(cursor, cor)
# Opcion 2 REMIX CHARACTERS---------------------------------------------
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
if opc_2 == True:
ventana.fill(negro)
# FILA 1------------------------------------------------------------
if remix_char.dr_marioCK == True:
ventana.blit(remix_char.dr_mario, (0,0))
if remix_char.y_linkCK == True:
ventana.blit(remix_char.y_link, (0,100))
if remix_char.dark_samusCK == True:
ventana.blit(remix_char.dark_samus, (0,200))
if remix_char.warioCK == True:
ventana.blit(remix_char.wario, (0,300))
if remix_char.lucasCK == True:
ventana.blit(remix_char.lucas, (0,400))
if remix_char.ganondorfCK == True:
ventana.blit(remix_char.ganondorf, (0,500))
if remix_char.falcooCK == True:
ventana.blit(remix_char.falcoo, (100,0))
# FILA 2------------------------------------------------------------
if remix_char.dr_marioCK2 == True:
ventana.blit(remix_char.dr_mario, (600,0))
if remix_char.y_linkCK2 == True:
ventana.blit(remix_char.y_link, (600,100))
if remix_char.dark_samusCK2 == True:
ventana.blit(remix_char.dark_samus, (600,200))
if remix_char.warioCK2 == True:
ventana.blit(remix_char.wario, (600,300))
if remix_char.lucasCK2 == True:
ventana.blit(remix_char.lucas, (600,400))
if remix_char.ganondorfCK2 == True:
ventana.blit(remix_char.ganondorf, (600,500))
if remix_char.falcooCK2 == True:
ventana.blit(remix_char.falcoo, (700,0))
# Mostrar Mouse
cor = pygame.mouse.get_pos()
ventana.blit(cursor, cor)
#-----------------------------------------------------------
#-----------------------------------------------------------
#-----------------------------------------------------------
# Eventos del programa (loop)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if opc == True:
if event.type == MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x > 100 and x < 182:
if y > 460 and y < 500:
start_bCK = False
#pause_time = int(pygame.time.get_ticks()/1000)
#print(pause_time)
#display(2,pause_time)
modoCK = False
opc = False
opc_1 = True
if x > 325 and x < 405:
if y > 460 and y < 500:
modoCK = False
opc_2 = True
if opc_1 == True:
#display(5)
if event.type == MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
if my > 535 and my < 570:
if mx > 300 and mx < 420:
cont_texto = 48
cont_texto2 = 48
stock_luigi_1_CK = True
stock_luigi_2_CK = True
stock_luigi_3_CK = True
stock_luigi_4_CK = True
luigiCK = True
contador_luigi = 4
stock_mario_1_CK = True
stock_mario_2_CK = True
stock_mario_3_CK = True
stock_mario_4_CK = True
marioCK = True
contador_mario = 4
stock_dk_1_CK = True
stock_dk_2_CK = True
stock_dk_3_CK = True
stock_dk_4_CK = True
dkCK = True
contador_dk = 4
stock_link_1_CK = True
stock_link_2_CK = True
stock_link_3_CK = True
stock_link_4_CK = True
linkCK = True
contador_link = 4
stock_samus_1_CK = True
stock_samus_2_CK = True
stock_samus_3_CK = True
stock_samus_4_CK = True
samusCK = True
contador_samus = 4
stock_falcon_1_CK = True
stock_falcon_2_CK = True
stock_falcon_3_CK = True
stock_falcon_4_CK = True
falconCK = True
contador_falcon = 4
stock_ness_4_CK = False
stock_ness_8_CK = True
nessCK = True
contador_ness = 4
stock_yoshi_1_CK = True
stock_yoshi_2_CK = True
stock_yoshi_3_CK = True
stock_yoshi_4_CK = True
yoshiCK = True
contador_yoshi = 4
stock_kirby_1_CK = True
stock_kirby_2_CK = True
stock_kirby_3_CK = True
stock_kirby_4_CK = True
kirbyCK = True
contador_kirby = 4
stock_fox_1_CK = True
stock_fox_2_CK = True
stock_fox_3_CK = True
stock_fox_4_CK = True
foxCK = True
contador_fox = 4
stock_pikachu_1_CK = True
stock_pikachu_2_CK = True
stock_pikachu_3_CK = True
stock_pikachu_4_CK = True
pikachuCK = True
contador_pikachu = 4
stock_jigglypuff_1_CK = True
stock_jigglypuff_2_CK = True
stock_jigglypuff_3_CK = True
stock_jigglypuff_4_CK = True
jigglypuffCK = True
contador_jigglypuff = 4
# Fila 2
stock_luigi_1_CK_2 = True
stock_luigi_2_CK_2 = True
stock_luigi_3_CK_2 = True
stock_luigi_4_CK_2 = True
luigiCK1 = True
contador_luigi_2 = 4
stock_mario_1_CK_2 = True
stock_mario_2_CK_2 = True
stock_mario_3_CK_2 = True
stock_mario_4_CK_2 = True
marioCK1 = True
contador_mario_2 = 4
stock_dk_1_CK_2 = True
stock_dk_2_CK_2 = True
stock_dk_3_CK_2 = True
stock_dk_4_CK_2 = True
dkCK1 = True
contador_dk_2 = 4
stock_link_1_CK_2 = True
stock_link_2_CK_2 = True
stock_link_3_CK_2 = True
stock_link_4_CK_2 = True
linkCK1 = True
contador_link_2 = 4
stock_samus_1_CK_2 = True
stock_samus_2_CK_2 = True
stock_samus_3_CK_2 = True
stock_samus_4_CK_2 = True
samusCK1 = True
contador_samus_2 = 4
stock_falcon_1_CK_2 = True
stock_falcon_2_CK_2 = True
stock_falcon_3_CK_2 = True
stock_falcon_4_CK_2 = True
falconCK1 = True
contador_falcon_2 = 4
stock_ness_4_CK_2 = False
stock_ness_8_CK_2 = True
nessCK1 = True
contador_ness_2 = 4
stock_yoshi_1_CK_2 = True
stock_yoshi_2_CK_2 = True
stock_yoshi_3_CK_2 = True
stock_yoshi_4_CK_2 = True
yoshiCK1 = True
contador_yoshi_2 = 4
stock_kirby_1_CK_2 = True
stock_kirby_2_CK_2 = True
stock_kirby_3_CK_2 = True
stock_kirby_4_CK_2 = True
kirbyCK1 = True
contador_kirby_2 = 4
stock_fox_1_CK_2 = True
stock_fox_2_CK_2 = True
stock_fox_3_CK_2 = True
stock_fox_4_CK_2 = True
foxCK1 = True
contador_fox_2 = 4
stock_pikachu_1_CK_2 = True
stock_pikachu_2_CK_2 = True
stock_pikachu_3_CK_2 = True
stock_pikachu_4_CK_2 = True
pikachuCK1 = True
contador_pikachu_2 = 4
stock_jigglypuff_1_CK_2 = True
stock_jigglypuff_2_CK_2 = True
stock_jigglypuff_3_CK_2 = True
stock_jigglypuff_4_CK_2 = True
jigglypuffCK1 = True
contador_jigglypuff_2 = 4
#-------------------------------------------
# Fila 1
# Luigi
if mx < 100 and my < 100:
contador_luigi = contador_luigi - 1
if contador_luigi == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_luigi_4_CK = False
if contador_luigi == 2:
cont_texto = cont_texto - 1
stock_luigi_3_CK = False
textoCK = True
if contador_luigi == 1:
cont_texto = cont_texto - 1
stock_luigi_2_CK = False
textoCK = True
if contador_luigi == 0:
cont_texto = cont_texto - 1
stock_luigi_1_CK = False
textoCK = True
luigiCK = False
if contador_luigi == -1:
cont_texto = cont_texto + 4
stock_luigi_1_CK = True
stock_luigi_2_CK = True
stock_luigi_3_CK = True
stock_luigi_4_CK = True
luigiCK = True
contador_luigi = 4
# Mario
if mx < 100 and my > 100 and my < 200:
contador_mario = contador_mario - 1
if contador_mario == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_mario_4_CK = False
if contador_mario == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_mario_3_CK = False
if contador_mario == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_mario_2_CK = False
if contador_mario == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_mario_1_CK = False
marioCK = False
if contador_mario == -1:
cont_texto = cont_texto + 4
stock_mario_1_CK = True
stock_mario_2_CK = True
stock_mario_3_CK = True
stock_mario_4_CK = True
marioCK = True
contador_mario = 4
# DK
if mx < 100 and my > 200 and my < 300:
contador_dk = contador_dk - 1
if contador_dk == 3:
stock_dk_4_CK = False
cont_texto = cont_texto - 1
textoCK = True
if contador_dk == 2:
stock_dk_3_CK = False
cont_texto = cont_texto - 1
textoCK = True
if contador_dk == 1:
stock_dk_2_CK = False
cont_texto = cont_texto - 1
textoCK = True
if contador_dk == 0:
stock_dk_1_CK = False
dkCK = False
cont_texto = cont_texto - 1
textoCK = True
if contador_dk == -1:
cont_texto = cont_texto + 4
stock_dk_1_CK = True
stock_dk_2_CK = True
stock_dk_3_CK = True
stock_dk_4_CK = True
dkCK = True
contador_dk = 4
# Link
if mx < 100 and my > 300 and my < 400:
contador_link = contador_link - 1
if contador_link == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_link_4_CK = False
if contador_link == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_link_3_CK = False
if contador_link == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_link_2_CK = False
if contador_link == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_link_1_CK = False
linkCK = False
if contador_link == -1:
cont_texto = cont_texto + 4
stock_link_1_CK = True
stock_link_2_CK = True
stock_link_3_CK = True
stock_link_4_CK = True
linkCK = True
contador_link = 4
# Samus
if mx < 100 and my > 400 and my < 500:
contador_samus = contador_samus - 1
if contador_samus == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_samus_4_CK = False
if contador_samus == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_samus_3_CK = False
if contador_samus == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_samus_2_CK = False
if contador_samus == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_samus_1_CK = False
samusCK = False
if contador_samus == -1:
cont_texto = cont_texto + 4
stock_samus_1_CK = True
stock_samus_2_CK = True
stock_samus_3_CK = True
stock_samus_4_CK = True
samusCK = True
contador_samus = 4
# C. Falcon
if mx < 100 and my > 500 and my < 600:
contador_falcon = contador_falcon - 1
if contador_falcon == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_falcon_4_CK = False
if contador_falcon == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_falcon_3_CK = False
if contador_falcon == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_falcon_2_CK = False
if contador_falcon == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_falcon_1_CK = False
falconCK = False
if contador_falcon == -1:
cont_texto = cont_texto + 4
stock_falcon_1_CK = True
stock_falcon_2_CK = True
stock_falcon_3_CK = True
stock_falcon_4_CK = True
falconCK = True
contador_falcon = 4
# Ness
if mx > 100 and mx < 200 and my > 0 and my < 100:
contador_ness = contador_ness - 1
if contador_ness == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_ness_8_CK = False
stock_ness_7_CK = True
if contador_ness == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_ness_7_CK = False
stock_ness_6_CK = True
if contador_ness == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_ness_6_CK = False
stock_ness_5_CK = True
if contador_ness == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_ness_5_CK = False
stock_ness_4_CK = True
nessCK = False
if contador_ness == -1:
stock_ness_4_CK = False
stock_ness_8_CK = True
nessCK = True
cont_texto = cont_texto + 4
contador_ness = 4
# Yoshi
if mx > 100 and mx < 200 and my > 100 and my < 200:
contador_yoshi = contador_yoshi - 1
if contador_yoshi == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_yoshi_4_CK = False
if contador_yoshi == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_yoshi_3_CK = False
if contador_yoshi == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_yoshi_2_CK = False
if contador_yoshi == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_yoshi_1_CK = False
yoshiCK = False
if contador_yoshi == -1:
cont_texto = cont_texto + 4
stock_yoshi_1_CK = True
stock_yoshi_2_CK = True
stock_yoshi_3_CK = True
stock_yoshi_4_CK = True
yoshiCK = True
contador_yoshi = 4
# Kirby
if mx > 100 and mx < 200 and my > 200 and my < 300:
contador_kirby = contador_kirby - 1
if contador_kirby == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_kirby_4_CK = False
if contador_kirby == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_kirby_3_CK = False
if contador_kirby == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_kirby_2_CK = False
if contador_kirby == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_kirby_1_CK = False
kirbyCK = False
if contador_kirby == -1:
cont_texto = cont_texto + 4
stock_kirby_1_CK = True
stock_kirby_2_CK = True
stock_kirby_3_CK = True
stock_kirby_4_CK = True
kirbyCK = True
contador_kirby = 4
# Fox
if mx > 100 and mx < 200 and my > 300 and my < 400:
contador_fox = contador_fox - 1
if contador_fox == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_fox_4_CK = False
if contador_fox == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_fox_3_CK = False
if contador_fox == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_fox_2_CK = False
if contador_fox == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_fox_1_CK = False
foxCK = False
if contador_fox == -1:
cont_texto = cont_texto + 4
stock_fox_1_CK = True
stock_fox_2_CK = True
stock_fox_3_CK = True
stock_fox_4_CK = True
foxCK = True
contador_fox = 4
# Pikachu
if mx > 100 and mx < 200 and my > 400 and my < 500:
contador_pikachu = contador_pikachu - 1
if contador_pikachu == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_pikachu_4_CK = False
if contador_pikachu == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_pikachu_3_CK = False
if contador_pikachu == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_pikachu_2_CK = False
if contador_pikachu == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_pikachu_1_CK = False
pikachuCK = False
if contador_pikachu == -1:
cont_texto = cont_texto + 4
stock_pikachu_1_CK = True
stock_pikachu_2_CK = True
stock_pikachu_3_CK = True
stock_pikachu_4_CK = True
pikachuCK = True
contador_pikachu = 4
# Jigglypuff
if mx > 100 and mx < 200 and my > 500 and my < 600:
contador_jigglypuff = contador_jigglypuff - 1
if contador_jigglypuff == 3:
cont_texto = cont_texto - 1
textoCK = True
stock_jigglypuff_4_CK = False
if contador_jigglypuff == 2:
cont_texto = cont_texto - 1
textoCK = True
stock_jigglypuff_3_CK = False
if contador_jigglypuff == 1:
cont_texto = cont_texto - 1
textoCK = True
stock_jigglypuff_2_CK = False
if contador_jigglypuff == 0:
cont_texto = cont_texto - 1
textoCK = True
stock_jigglypuff_1_CK = False
jigglypuffCK = False
if contador_jigglypuff == -1:
cont_texto = cont_texto + 4
stock_jigglypuff_1_CK = True
stock_jigglypuff_2_CK = True
stock_jigglypuff_3_CK = True
stock_jigglypuff_4_CK = True
jigglypuffCK = True
contador_jigglypuff = 4
#--------------------------------------------------------------
#--------------------------------------------------------------
#--------------------------------------------------------------
# Fila 2
# Luigi
if mx > 600 and mx < 700 and my > 0 and my < 100:
contador_luigi_2 = contador_luigi_2 - 1
if contador_luigi_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_luigi_4_CK_2 = False
if contador_luigi_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_luigi_3_CK_2 = False
if contador_luigi_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_luigi_2_CK_2 = False
if contador_luigi_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_luigi_1_CK_2 = False
luigiCK1 = False
if contador_luigi_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_luigi_1_CK_2 = True
stock_luigi_2_CK_2 = True
stock_luigi_3_CK_2 = True
stock_luigi_4_CK_2 = True
luigiCK1 = True
contador_luigi_2 = 4
# Mario
if mx > 600 and mx < 700 and my > 100 and my < 200:
contador_mario_2 = contador_mario_2 - 1
if contador_mario_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_mario_4_CK_2 = False
if contador_mario_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_mario_3_CK_2 = False
if contador_mario_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_mario_2_CK_2 = False
if contador_mario_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_mario_1_CK_2 = False
marioCK1 = False
if contador_mario_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_mario_1_CK_2 = True
stock_mario_2_CK_2 = True
stock_mario_3_CK_2 = True
stock_mario_4_CK_2 = True
marioCK1 = True
contador_mario_2 = 4
# DK
if mx > 600 and mx < 700 and my > 200 and my < 300:
contador_dk_2 = contador_dk_2 - 1
if contador_dk_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_dk_4_CK_2 = False
if contador_dk_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_dk_3_CK_2 = False
if contador_dk_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_dk_2_CK_2 = False
if contador_dk_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_dk_1_CK_2 = False
dkCK1 = False
if contador_dk_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_dk_1_CK_2 = True
stock_dk_2_CK_2 = True
stock_dk_3_CK_2 = True
stock_dk_4_CK_2 = True
dkCK1 = True
contador_dk_2 = 4
# Link
if mx > 600 and mx < 700 and my > 300 and my < 400:
contador_link_2 = contador_link_2 - 1
if contador_link_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_link_4_CK_2 = False
if contador_link_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_link_3_CK_2 = False
if contador_link_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_link_2_CK_2 = False
if contador_link_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_link_1_CK_2 = False
linkCK1 = False
if contador_link_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_link_1_CK_2 = True
stock_link_2_CK_2 = True
stock_link_3_CK_2 = True
stock_link_4_CK_2 = True
linkCK1 = True
contador_link_2 = 4
# Samus
if mx > 600 and mx < 700 and my > 400 and my < 500:
contador_samus_2 = contador_samus_2 - 1
if contador_samus_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_samus_4_CK_2 = False
if contador_samus_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_samus_3_CK_2 = False
if contador_samus_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_samus_2_CK_2 = False
if contador_samus_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_samus_1_CK_2 = False
samusCK1 = False
if contador_samus_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_samus_1_CK_2 = True
stock_samus_2_CK_2 = True
stock_samus_3_CK_2 = True
stock_samus_4_CK_2 = True
samusCK1 = True
contador_samus_2 = 4
# C. Falcon
if mx > 600 and mx < 700 and my > 500 and my < 600:
contador_falcon_2 = contador_falcon_2 - 1
if contador_falcon_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_falcon_4_CK_2 = False
if contador_falcon_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_falcon_3_CK_2 = False
if contador_falcon_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_falcon_2_CK_2 = False
if contador_falcon_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_falcon_1_CK_2 = False
falconCK1 = False
if contador_falcon_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_falcon_1_CK_2 = True
stock_falcon_2_CK_2 = True
stock_falcon_3_CK_2 = True
stock_falcon_4_CK_2 = True
falconCK1 = True
contador_falcon_2 = 4
# Ness
if mx > 700 and mx < 800 and my > 0 and my < 100:
contador_ness_2 = contador_ness_2 - 1
if contador_ness_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_ness_8_CK_2 = False
stock_ness_7_CK_2 = True
if contador_ness_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_ness_7_CK_2 = False
stock_ness_6_CK_2 = True
if contador_ness_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_ness_6_CK_2 = False
stock_ness_5_CK_2 = True
if contador_ness_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_ness_5_CK_2 = False
stock_ness_4_CK_2 = True
nessCK1 = False
if contador_ness_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_ness_4_CK_2 = False
stock_ness_8_CK_2 = True
nessCK1 = True
contador_ness_2 = 4
# Yoshi
if mx > 700 and mx < 800 and my > 100 and my < 200:
contador_yoshi_2 = contador_yoshi_2 - 1
if contador_yoshi_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_yoshi_4_CK_2 = False
if contador_yoshi_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_yoshi_3_CK_2 = False
if contador_yoshi_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_yoshi_2_CK_2 = False
if contador_yoshi_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_yoshi_1_CK_2 = False
yoshiCK1 = False
if contador_yoshi_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_yoshi_1_CK_2 = True
stock_yoshi_2_CK_2 = True
stock_yoshi_3_CK_2 = True
stock_yoshi_4_CK_2 = True
yoshiCK1 = True
contador_yoshi_2 = 4
# Kirby
if mx > 700 and mx < 800 and my > 200 and my < 300:
contador_kirby_2 = contador_kirby_2 - 1
if contador_kirby_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_kirby_4_CK_2 = False
if contador_kirby_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_kirby_3_CK_2 = False
if contador_kirby_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_kirby_2_CK_2 = False
if contador_kirby_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_kirby_1_CK_2 = False
kirbyCK1 = False
if contador_kirby_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_kirby_1_CK_2 = True
stock_kirby_2_CK_2 = True
stock_kirby_3_CK_2 = True
stock_kirby_4_CK_2 = True
kirbyCK1 = True
contador_kirby_2 = 4
# Fox
if mx > 700 and mx < 800 and my > 300 and my < 400:
contador_fox_2 = contador_fox_2 - 1
if contador_fox_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_fox_4_CK_2 = False
if contador_fox_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_fox_3_CK_2 = False
if contador_fox_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_fox_2_CK_2 = False
if contador_fox_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_fox_1_CK_2 = False
foxCK1 = False
if contador_fox_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_fox_1_CK_2 = True
stock_fox_2_CK_2 = True
stock_fox_3_CK_2 = True
stock_fox_4_CK_2 = True
foxCK1 = True
contador_fox_2 = 4
# Pikachu
if mx > 700 and mx < 800 and my > 400 and my < 500:
contador_pikachu_2 = contador_pikachu_2 - 1
if contador_pikachu_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_pikachu_4_CK_2 = False
if contador_pikachu_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_pikachu_3_CK_2 = False
if contador_pikachu_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_pikachu_2_CK_2 = False
if contador_pikachu_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_pikachu_1_CK_2 = False
pikachuCK1 = False
if contador_pikachu_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_pikachu_1_CK_2 = True
stock_pikachu_2_CK_2 = True
stock_pikachu_3_CK_2 = True
stock_pikachu_4_CK_2 = True
pikachuCK1 = True
contador_pikachu_2 = 4
# Jigglypuff
if mx > 700 and mx < 800 and my > 500 and my < 600:
contador_jigglypuff_2 = contador_jigglypuff_2 - 1
if contador_jigglypuff_2 == 3:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_jigglypuff_4_CK_2 = False
if contador_jigglypuff_2 == 2:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_jigglypuff_3_CK_2 = False
if contador_jigglypuff_2 == 1:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_jigglypuff_2_CK_2 = False
if contador_jigglypuff_2 == 0:
cont_texto2 = cont_texto2 - 1
texto2CK = True
stock_jigglypuff_1_CK_2 = False
jigglypuffCK1 = False
if contador_jigglypuff_2 == -1:
cont_texto2 = cont_texto2 + 4
stock_jigglypuff_1_CK_2 = True
stock_jigglypuff_2_CK_2 = True
stock_jigglypuff_3_CK_2 = True
stock_jigglypuff_4_CK_2 = True
jigglypuffCK1 = True
contador_jigglypuff_2 = 4
pygame.display.update()
#---------------------MAIN-----------------------------
opcion_1()
|
{"/12CB.py": ["/remix_char.py"]}
|
40,837,687
|
NaxF11/12CharacterBattleOverlay
|
refs/heads/master
|
/remix_char.py
|
import pygame
# DR MARIO
dr_mario = pygame.image.load("images/remix/dr_mario.png")
dr_mario = pygame.transform.scale(dr_mario, (100,100))
dr_mariod = pygame.image.load("images/remix/dr_mariod.png")
dr_mariod = pygame.transform.scale(dr_mariod, (100,100))
dr_marioCK = True
dr_marioCK2 = True
# YOUNG LINK
y_link = pygame.image.load("images/remix/y_link.png")
y_link = pygame.transform.scale(y_link, (100,100))
y_linkd = pygame.image.load("images/remix/y_linkd.png")
y_linkd = pygame.transform.scale(y_linkd, (100,100))
y_linkCK = True
y_linkCK2 = True
# DARK SAMUS
dark_samus = pygame.image.load("images/remix/dark_samus.png")
dark_samus = pygame.transform.scale(dark_samus, (100,100))
dark_samusd = pygame.image.load("images/remix/dark_samusd.png")
dark_samusd = pygame.transform.scale(dark_samusd, (100,100))
dark_samusCK = True
dark_samusCK2 = True
# WARIO
wario = pygame.image.load("images/remix/wario.png")
wario = pygame.transform.scale(wario, (100,100))
wariod = pygame.image.load("images/remix/wariod.png")
wariod = pygame.transform.scale(wariod, (100,100))
warioCK = True
warioCK2 = True
# LUCAS
lucas = pygame.image.load("images/remix/lucas.png")
lucas = pygame.transform.scale(lucas, (100,100))
lucasd = pygame.image.load("images/remix/lucasd.png")
lucasd = pygame.transform.scale(lucasd, (100,100))
lucasCK = True
lucasCK2 = True
# GANONDORF
ganondorf = pygame.image.load("images/remix/ganondorf.png")
ganondorf = pygame.transform.scale(ganondorf, (100,100))
ganondorfd = pygame.image.load("images/remix/ganondorfd.png")
ganondorfd = pygame.transform.scale(ganondorfd, (100,100))
ganondorfCK = True
ganondorfCK2 = True
# FALCO
falcoo = pygame.image.load("images/remix/falcoo.png")
falcoo = pygame.transform.scale(falcoo, (100,100))
falcood = pygame.image.load("images/remix/falcood.png")
falcood = pygame.transform.scale(falcood, (100,100))
falcooCK = True
falcooCK2 = True
|
{"/12CB.py": ["/remix_char.py"]}
|
40,853,401
|
bstriner/pytorch-igniter-demo
|
refs/heads/master
|
/setup.py
|
from setuptools import find_packages, setup
import os
with open(os.path.abspath(os.path.join(__file__, '../README.rst')), encoding='utf-8') as f:
long_description = f.read()
setup(name='pytorch-igniter-demo',
version='0.0.3',
author='Ben Striner',
author_email="bstriner@gmail.com",
url='https://github.com/bstriner/pytorch-igniter-demo',
description="Demo for pytorch-igniter",
install_requires=[
'pytorch-igniter==0.0.42',
'aws-sagemaker-remote==0.0.48'
],
package_data={'': [
'**/*.txt'
]},
include_package_data=True,
entry_points={
'console_scripts': [
'pytorch-igniter-demo=pytorch_igniter_demo.main:main'
]
},
packages=find_packages(),
long_description=long_description,
long_description_content_type='text/x-rst')
|
{"/pytorch_igniter_demo/config.py": ["/pytorch_igniter_demo/dataprep.py"], "/pytorch_igniter_demo/main.py": ["/pytorch_igniter_demo/config.py", "/pytorch_igniter_demo/dataprep.py"]}
|
40,853,402
|
bstriner/pytorch-igniter-demo
|
refs/heads/master
|
/pytorch_igniter_demo/dataprep.py
|
from aws_sagemaker_remote.processing.main import ProcessingCommand
import os
import argparse
import os
import pprint
from torch import nn
from torch.utils import data
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
from aws_sagemaker_remote.processing import sagemaker_processing_main
import aws_sagemaker_remote
from aws_sagemaker_remote.processing.main import ProcessingCommand
from aws_sagemaker_remote.commands import run_command
def get_dataset(path, train=True):
os.makedirs(
path, exist_ok=True
)
loader = MNIST(
root=path, download=True,
transform=transforms.ToTensor(),
train=train
)
return loader
def get_loader(path, batch_size, train=True, shuffle=True):
ds = get_dataset(path, train=train)
dl = data.DataLoader(ds, shuffle=shuffle, batch_size=batch_size)
return dl
def dataprep(args):
output = args.output
get_dataset(output)
print("Downloaded MNIST dataset")
class DataprepCommand(ProcessingCommand):
def __init__(self, env=None):
super(DataprepCommand, self).__init__(
# Script to run command on SageMaker
script=__file__,
# Help will display when running `pytorch-igniter-demo dataprep --help`
help='Prepare dataset',
# Define entrypoint for dataprep command
main=dataprep,
outputs={
# Define output names and default paths
'output': 'output/data'
},
dependencies={
# Add a module to SageMaker
# module name: module path
'aws_sagemaker_remote': aws_sagemaker_remote
},
# Add commands to configure container
configuration_command='pip3 install --upgrade sagemaker sagemaker-experiments',
# Job name will show up in SageMaker processing tab
base_job_name='pytorch-igniter-demo-dataprep',
env=env
)
if __name__ == '__main__':
command = DataprepCommand()
run_command(
command=command,
description='pytorch-igniter demo dataprep'
)
|
{"/pytorch_igniter_demo/config.py": ["/pytorch_igniter_demo/dataprep.py"], "/pytorch_igniter_demo/main.py": ["/pytorch_igniter_demo/config.py", "/pytorch_igniter_demo/dataprep.py"]}
|
40,853,403
|
bstriner/pytorch-igniter-demo
|
refs/heads/master
|
/pytorch_igniter_demo/config.py
|
from pytorch_igniter.config import IgniterConfig
from torchvision.models.resnet import resnet18
from torch.optim import Adam
from torch.nn import CrossEntropyLoss
from .dataprep import get_loader
from torch import nn
import torch.nn.functional as F
import torch
import pytorch_igniter_demo
import os
from pytorch_igniter.spec import InferenceSpec, RunSpec
from pytorch_igniter.inference.greyscale_image_input_fn import input_fn
import pytorch_igniter
import aws_sagemaker_remote
def model_args(parser):
"""
Arguments used to build the model
"""
parser.add_argument('--classes', type=int, default=10)
def train_args(parser):
"""
Arguments specific to the trainer
"""
parser.add_argument('--learning-rate', type=float, default=1e-3)
parser.add_argument('--weight-decay', type=float, default=1e-5)
parser.add_argument('--train-batch-size', type=int, default=32)
def eval_args(parser):
"""
Arguments specific to the evaluator
"""
parser.add_argument('--eval-batch-size', type=int, default=32)
class Net(nn.Module):
"""
Model class
"""
def __init__(self, args):
print("args.device: {}".format(args.device))
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
class Trainer(nn.Module):
"""
Create loader, step, and metrics for training
Engine:
- Iterates through loader
- Passes batches to the step function
- Calculate metrics using outputs of step function
"""
def __init__(self, args, model):
super(Trainer, self).__init__()
self.optimizer = Adam(
params=model.parameters(),
lr=args.learning_rate
)
self.criteria = CrossEntropyLoss()
self.model = model
metrics = {
'loss': 'loss',
'accuracy': 'accuracy'
}
loader = get_loader(
path=args.input,
batch_size=args.train_batch_size,
train=True
)
self.spec = RunSpec(
loader=loader,
metrics=metrics,
step=self.step
)
def step(self, engine, batch):
self.model.train()
self.model.zero_grad()
x, y = batch
yp = self.model(x)
loss = self.criteria(input=yp, target=y)
loss.backward()
self.optimizer.step()
pred = torch.argmax(yp, dim=-1)
accuracy = torch.eq(y, pred).float().mean()
return {
'loss': loss,
'accuracy': accuracy
}
class Evaluator(object):
"""
Create loader, step, and metrics for evaluation
"""
def __init__(self, args, model):
self.model = model
self.criteria = CrossEntropyLoss()
metrics = {
'loss': 'loss',
'accuracy': 'accuracy'
}
loader = get_loader(
path=args.input,
batch_size=args.eval_batch_size,
train=False
)
self.spec = RunSpec(
loader=loader,
metrics=metrics,
step=self.step
)
def step(self, engine, batch):
#print("Step Batch: {}".format(batch))
self.model.eval()
x, y = batch
yp = self.model(x)
loss = self.criteria(input=yp, target=y)
pred = torch.argmax(yp, dim=-1)
accuracy = torch.eq(y, pred).float().mean()
return {
'loss': loss,
'accuracy': accuracy
}
class Inferencer(object):
"""
Object deployed to SageMaker endpoint for inference
"""
def __init__(self, args):
self.args = args
self.model = Net(args)
self.model.eval()
def inference(self, data):
data = data.unsqueeze(0)
output = self.model(data)
output = output.squeeze(0)
pred = torch.argmax(output)
return {
"class": pred.item(),
"logits": output
}
def make_config():
"""
Build a configuration
- Model, training, and evaluation arguments and inputs
- Trainer, evaluator, and inferencer
- Additional defaults like number of epochs, save frequency, etc. (see docs)
"""
return IgniterConfig(
model_args=model_args,
train_args=train_args,
eval_args=eval_args,
train_inputs={
'input': 'output/data'
},
eval_inputs={
'input': 'output/data'
},
make_model=Net,
make_trainer=Trainer,
make_evaluator=Evaluator,
inference_spec=InferenceSpec(
dependencies=[
pytorch_igniter_demo
],
requirements=os.path.abspath(
os.path.join(__file__, '../inference_requirements.txt')
),
inferencer=Inferencer,
input_fn=input_fn
),
max_epochs=5
)
|
{"/pytorch_igniter_demo/config.py": ["/pytorch_igniter_demo/dataprep.py"], "/pytorch_igniter_demo/main.py": ["/pytorch_igniter_demo/config.py", "/pytorch_igniter_demo/dataprep.py"]}
|
40,853,404
|
bstriner/pytorch-igniter-demo
|
refs/heads/master
|
/pytorch_igniter_demo/main.py
|
from pytorch_igniter.experiment_cli import experiment_cli
from pytorch_igniter_demo.config import make_config
from pytorch_igniter_demo.dataprep import DataprepCommand
import pytorch_igniter_demo
def main(dry_run=False):
"""
Generate experiment CLI.
Running locally, this function is run by a wrapper created by setuptools
"""
return experiment_cli(
config=make_config(),
script=__file__,
description='pytorch-igniter demo script',
extra_commands={
'dataprep': DataprepCommand()
},
model_dir='output/model',
checkpoint_dir='output/checkpoint',
output_dir='output/output',
dry_run=dry_run,
dependencies ={
'pytorch_igniter_demo': pytorch_igniter_demo
}
)
def parser_for_docs():
"""
Create a parser for generating documentation
"""
return main(dry_run=True)
if __name__ == '__main__':
# Running remotely, this is where execution starts
main()
|
{"/pytorch_igniter_demo/config.py": ["/pytorch_igniter_demo/dataprep.py"], "/pytorch_igniter_demo/main.py": ["/pytorch_igniter_demo/config.py", "/pytorch_igniter_demo/dataprep.py"]}
|
40,916,247
|
Homagn/MOVILAN
|
refs/heads/main
|
/planner/params.py
|
camera_horizon_angle = 30
room_type = "Bedroom"
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,916,248
|
Homagn/MOVILAN
|
refs/heads/main
|
/planner/low_level_planner/grid_planning.py
|
import numpy as np
from skimage.measure import regionprops, label
import sys
import os
os.environ['MAIN'] = '/ai2thor'
sys.path.append(os.path.join(os.environ['MAIN']))
from mapper import test_gcn
from planner.low_level_planner import move_camera
def occupancy_grid(target_object, localize_params, hallucinate = [0,0]): #displays the true map of the environment around the agent for a focussed object + floor
print("(grid_planning.py -> occupancy_grid)")
labeled_grid = test_gcn.estimate_map(target_object,localize_params = localize_params)
#without map the agent spirals the camera upward to capture an image so reset the camera position
if isinstance(localize_params['room'],int)==False:
move_camera.set_default_tilt(localize_params['room'])
if hallucinate[0]!=0 or hallucinate[1]!=0:
print("Target is visible, but too far away for depth sensor, halucinating the position")
visualize = True
p = int(labeled_grid.shape[0]/2)
q = int(labeled_grid.shape[1]/2)
labeled_grid[p+int(hallucinate[0]*p), q+int(hallucinate[1]*q)] = 4 # object_codes[target_object] = 4
###################### get the target bounding coordinates of the object to set graph search target ###################
search_grid = np.where(labeled_grid==2,labeled_grid,0) #only places where target object is mapped is nonzero
props = regionprops(label(np.asarray(search_grid,dtype = np.int)))
print("Number of regionprops found for ",target_object, " is = ",len(props))
bbox = props[0].bbox #need to refine when multiple objects are present (for example drawers)
if len(props)>1:
dists = []
print("Number of regionprops>1, picking closest region ")
for p in props:
bbox = p.bbox
corners = bbox-np.array([int(labeled_grid.shape[0]/2),int(labeled_grid.shape[1]/2)]*2) #top left and bottom right corners of the target obj
av_dist = (corners[0]+corners[2])**2 + (corners[1]+corners[3])**2
#av_dist = (corners[0]+corners[1]+corners[2]+corners[3])/4.0 #not a fool proof way, because sizes of similar objects can still be different
dists.append(av_dist)
min_d = np.argmin(dists)
bbox = props[min_d].bbox
#bbox = bbox - np.array([0,0,1,1])
corners = bbox-np.array([int(labeled_grid.shape[0]/2),int(labeled_grid.shape[1]/2)]*2) #top left and bottom right corners of the target obj
up,left,down,right = corners[0],corners[1],corners[2],corners[3] #-1 because region props gives open interval for the bottom corner
n_facing_pos = [int((up+down)/2), left-1] #translating to i,j index of the the labeled_grid matrix
w_facing_pos = [down, int((left+right)/2)]
s_facing_pos = [int((up+down)/2), right]
e_facing_pos = [up-1, int((left+right)/2)] #new modifications-> added -1 to left and up in lines 339,342
#print("bounding box ",bbox-np.array([int(labeled_grid.shape[0]/2),int(labeled_grid.shape[1]/2)]*2))
#print("four corners (agent rel) of ",target_object, " ",corners)
print("Facing grid positions north, west, south, east ",n_facing_pos, w_facing_pos, s_facing_pos, e_facing_pos)
print(" ")
return labeled_grid, [n_facing_pos,w_facing_pos,s_facing_pos,e_facing_pos]
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,916,249
|
Homagn/MOVILAN
|
refs/heads/main
|
/robot/params.py
|
camera = {'width':300,'height':300}
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,916,250
|
Homagn/MOVILAN
|
refs/heads/main
|
/mapper/datagen.py
|
import numpy as np
import math
import sys
import glob
import os
import json
import random
import copy
import argparse
#sys.path.append(os.path.join(os.environ['ALFRED_ROOT']))
#sys.path.append(os.path.join(os.environ['ALFRED_ROOT'], 'gen'))
#from env.thor_env import ThorEnv
os.environ['MAIN'] = '../'
sys.path.append(os.path.join(os.environ['MAIN']))
from robot.sensing import sensing
import panorama as pan
import projection as proj
import gtmaps as gtm
import mapper.params as params
parser = argparse.ArgumentParser()
#my arguments
parser.add_argument('--room', type=int, default=301)
parser.add_argument('--task', type=int, default=1)
parser.add_argument('--inputs', dest='inputs', action='store_true')
parser.add_argument('--targets', dest='targets', action='store_true') #if --nomap is passed agent has to approximate bev proj using graph conv
parser.add_argument('--correct', dest='correct', action='store_true')
parser.add_argument('--allinputs', dest='allinputs', action='store_true')
parser.add_argument('--alltargets', dest='alltargets', action='store_true')
parser.add_argument('--aliasinput', dest='aliasinput', action='store_true')
parser.add_argument('--checkpan', dest='checkpan', action='store_true')
parser.add_argument('--checkinput', dest='checkinput', action='store_true')
parser.add_argument('--checktarget', dest='checktarget', action='store_true')
parser.add_argument('--specific_input', dest='specific_input', action='store_true')
args = parser.parse_args()
def get_file(rn = 302, task_index = 1, trial_num = 0):
#folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*'+repr(rn))) #for home computer
#folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*-'+repr(rn))) #for home computer
#folders = sorted(glob.glob('/alfred/data/json_2.1.0/train/*-'+repr(rn))) #for home computer
folders = sorted(glob.glob(params.trajectory_data_location+repr(rn))) #for home computer
print("Number of demonstrated tasks for this room ",len(folders))
trials = glob.glob(folders[task_index]+'/*') #there would be len(folders) number of different tasks
print("Number of different trials (language instr) for the same task ",len(trials))
traj = glob.glob(trials[trial_num]+'/*.json')
print("got trajectory file ",traj)
return traj
def set_env(json_file, env = []):
if env==[]:
#if no env passed, initialize an empty environment first
#IMAGE_WIDTH = 300 #rendering- can change this in robot/params.py
#IMAGE_HEIGHT = 300
#env = ThorEnv(player_screen_width=IMAGE_WIDTH,player_screen_height=IMAGE_HEIGHT) #blank ai2thor environment
env = sensing()
with open(json_file[0]) as f:
traj_data = json.load(f)
#print("loaded traj file")
# scene setup
scene_num = traj_data['scene']['scene_num']
object_poses = traj_data['scene']['object_poses']
object_toggles = traj_data['scene']['object_toggles']
dirty_and_empty = traj_data['scene']['dirty_and_empty']
# reset
scene_name = 'FloorPlan%d' % scene_num
env.reset(scene_name)
env.restore_scene(object_poses, object_toggles, dirty_and_empty)
print("setting orientation of the agent to facing north ")
traj_data['scene']['rotation'] = 0
event = env.step(dict(traj_data['scene']['init_action']))
return env,event,traj_data
if __name__ == '__main__':
def init_once(room = 301, task = 0):
#load information from training trajectory files and set the environment accordingly
traj_file = get_file(rn = room, task_index = task, trial_num = 0)
env,event,traj_data = set_env(traj_file)
#orient the agent to always facing north
custom_rot = {"action": "TeleportFull","horizon": 30,"rotateOnTeleport": True,"rotation": 0,
"x": event.metadata['agent']['position']['x'],
"y": event.metadata['agent']['position']['y'],
"z": event.metadata['agent']['position']['z']}
event = env.step(dict(custom_rot))
return env,event
if args.inputs:
#obtain input vision panorama images and approx projection map from that
#load the ground truth BEV map obtained using other functions
#from this map, we get to know the actual minimum coordinate positions in the room
o_grids = np.load('data/targets/'+repr(args.room)+'.npy',allow_pickle = 'TRUE').item()
env,event = init_once(room = args.room, task = args.task)
x,y,z = event.metadata['agent']['position']['x'], event.metadata['agent']['position']['y'], event.metadata['agent']['position']['z']
print("In task ",args.task," the agent starting position is ",x,y,z)
grid_coord = [int((z-o_grids['min_pos']['mz'])/0.25), int((x-o_grids['min_pos']['mx'])/0.25)]
print("This is equivalent to grid coordinate ",grid_coord)
debug = False # True-load premade panorama image/ False- Dont
#gridsize = 33
gridsize = params.grid_size
panorama = pan.rotation_image(env, objects_to_visit = [], debug = debug) #gets a panorama image of everything thats visible
bev = proj.bevmap(panorama,grid_size = gridsize, debug = debug)
#save the obtained bev projection
np.save('data/inputs/bev_'+repr(args.room)+'_'+repr(grid_coord)+'.npy',bev)
#sample check the created projection map for a random object in the room
proj.displaymap(bev,'Desk')
nav_map = proj.input_navigation_map(bev, 'Desk', grid_size = gridsize, unk_id = 0,flr_id = 1, tar_id = 2, obs_id = 3)
print("Now displaying input navigation map")
proj.prettyprint(nav_map,argmax = True)
#print(nav_map) #should be grid_size x grid_size x 4 matrix contain floats between 0 and 1
if args.aliasinput:
#change any key in any room for semantic maps in the inputs bev projections
#say for eg- FP301:Cube is renamed as Shelf1| (a more meaningful name)
print("For room ",args.room)
try:
with open('data/alias/'+repr(args.room)+'.json') as f:
aliases = json.load(f)
print("loaded previous aliases ")
print(aliases)
except:
aliases = {}
while True:
obj = input("Enter the actual object id you want to alias")
obj_alis = input("Enter the alias name ")
aliases[obj_alis] = obj
i = input("Continue ?(y/n) ")
if i=="n":
break
with open('data/alias/'+repr(args.room)+'.json', 'w') as fp:
json.dump(aliases, fp, indent = 4)
if args.targets:
# creating ground truth BEV maps
#room = 0
#task = 164
env,event = init_once(room = args.room, task = args.task)
#o_grids stores BEV map for all objects as indexed in the event metadata
#fname = '../ai2thor/mapping/gcdata/'+repr(room)+'.npy'
fname = 'data/targets/'+repr(args.room)+'.npy'
o_grids = gtm.gtmap(env,event) # Obtains ground truth occupancy grids using Ai2Thor functions / try-> Dresser|-01.33|+00.00|-00.75 for room 301
np.save(fname,o_grids)
if args.correct:
#manual labeling for objects that are unable to be disabled and are like fixed parts in the room
gtm.manual_label(args.room) #0 is the room number (0 is the first kitchen, 301 is the first bedroom)
if args.alltargets:
#IMAGE_WIDTH = 300 #rendering
#IMAGE_HEIGHT = 300
#env = ThorEnv(player_screen_width=IMAGE_WIDTH,player_screen_height=IMAGE_HEIGHT) #blank ai2thor environment
env = sensing()
room_range = [308,330]
print("Creating all the training targets for graph convolution mapping training ")
for r in range(room_range[0], room_range[1]):
try:
traj_file = get_file(rn = r, task_index = 0, trial_num = 0) #take default first task of each room
except:
print("File is not present ")
continue
env,event,traj_data = set_env(traj_file, env = env)
#orient the agent to always facing north
custom_rot = {"action": "TeleportFull","horizon": 30,"rotateOnTeleport": True,"rotation": 0,
"x": event.metadata['agent']['position']['x'],
"y": event.metadata['agent']['position']['y'],
"z": event.metadata['agent']['position']['z']}
event = env.step(dict(custom_rot))
fname = 'data/targets/'+repr(r)+'.npy'
o_grids = gtm.gtmap(env,event) # Obtains ground truth occupancy grids using Ai2Thor functions / try-> Dresser|-01.33|+00.00|-00.75 for room 301
np.save(fname,o_grids)
if args.allinputs:
#IMAGE_WIDTH = 300 #rendering
#IMAGE_HEIGHT = 300
#env = ThorEnv(player_screen_width=IMAGE_WIDTH,player_screen_height=IMAGE_HEIGHT) #blank ai2thor environment
env = sensing()
room_range = [327,331]
print("Creating all the training inputs for graph convolution mapping training ")
for r in range(room_range[0], room_range[1]):
try:
traj_file = get_file(rn = r, task_index = 0, trial_num = 0) #take default first task of each room
print("Loaded room ",r)
except:
print("File is not present ")
continue
env,event,traj_data = set_env(traj_file, env = env)
#load the ground truth BEV map obtained using other functions
#from this map, we get to know the actual minimum coordinate positions in the room
o_grids = np.load('data/targets/'+repr(r)+'.npy',allow_pickle = 'TRUE').item()
#env,event = init_once(room = args.room, task = args.task)
nav_pos = np.argwhere(o_grids['nav_space']==1).tolist()
for p in nav_pos:
#command to position the agent in one of the navigable positions facing north
custom_rot = {"action": "TeleportFull","horizon": 30,"rotateOnTeleport": True,"rotation": 0,
"x": p[0]*0.25+ o_grids['min_pos']['mx'],
"y": event.metadata['agent']['position']['y'],
"z": p[1]*0.25+ o_grids['min_pos']['mz']}
event = env.step(dict(custom_rot))
debug = False # True-load premade panorama image/ False- Dont
#gridsize = 33
gridsize = params.grid_size
panorama = pan.rotation_image(env, objects_to_visit = [], debug = debug) #gets a panorama image of everything thats visible
bev = proj.bevmap(panorama,grid_size = gridsize, debug = debug)
#save the obtained bev projection
np.save('data/inputs/bev_'+repr(r)+'_'+repr([p[1],p[0]])+'.npy',bev)
print("saved panorama projection image for the room ",r," for the position ",[p[1],p[0]])
#==========================================================================================
#DEBUGGING PURPOSES
if args.checkpan: #check panorama images at a location
env,event = init_once(room = args.room, task = args.task)
debug = True # True-load premade panorama image/ False- Dont
gridsize = 33
panorama = pan.rotation_image(env, objects_to_visit = [], debug = debug) #gets a panorama image of everything thats visible
if args.checkinput: #check whether the projection mapping was done properly
room = 301
pos = [0,2]
room_obj = 'Bed'
camera_proj = np.load('data/inputs/bev_'+repr(room)+'_'+repr(pos)+'.npy',allow_pickle = 'TRUE').item()
nav_map = proj.input_navigation_map(camera_proj, room_obj, grid_size = params.grid_size,
unk_id = params.semantic_classes['unk'],
flr_id = params.semantic_classes['flr'],
tar_id = params.semantic_classes['tar'],
obs_id = params.semantic_classes['obs'])
#nav_map is an array of params.grid_size x params.grid_size x 4 (4 classes unk,flr,tar and obs)| contains values between 0 and 1
#for example grid i,j may contain the value [0.1,0.2,0.3,0.5] - sum of values is 1.0, last index is the argmax meaning highest prob that the grid contains obstacle
#because obstacle id=3 in params.py
can_see_target = proj.prettyprint(nav_map,argmax = True) #it cant print without argmax because each element of nav_map is 4 dimensional
print("Agent camera can see target ? ",can_see_target)
if args.checktarget: #check whether the projection mapping was done properly
room = 301
pos = [2,0]
room_obj = 'Bed'
o_grids = np.load('data/targets/'+repr(room)+'.npy',allow_pickle = 'TRUE').item()
#nav_map is an array of params.grid_size x params.grid_size -each grid [i,j] contains an integer between 0 to 4 denoting the type of object occupying that place
#whether its a target/navgable space/unk/obstacle
nav_map_t = gtm.target_navigation_map( o_grids, room_obj,
{'x':pos[0]*0.25+ o_grids['min_pos']['mx'], 'y':0.0, 'z': pos[1]*0.25+ o_grids['min_pos']['mz']},
grid_size = params.grid_size,
unk_id = params.semantic_classes['unk'],
flr_id = params.semantic_classes['flr'],
tar_id = params.semantic_classes['tar'],
obs_id = params.semantic_classes['obs'])
print("Showing ground truth map")
#gtm.prettyprint(nav_map_t)
proj.starviz(nav_map_t)
if args.specific_input: #for debugging purposes
#IMAGE_WIDTH = 300 #rendering
#IMAGE_HEIGHT = 300
#env = ThorEnv(player_screen_width=IMAGE_WIDTH,player_screen_height=IMAGE_HEIGHT) #blank ai2thor environment
env = sensing()
room = 301
pos = [9,4]
print("Creating all the training inputs for graph convolution mapping training ")
r = room
try:
traj_file = get_file(rn = r, task_index = 0, trial_num = 0) #take default first task of each room
print("Loaded room ",r)
except:
print("File is not present ")
env,event,traj_data = set_env(traj_file, env = env)
#load the ground truth BEV map obtained using other functions
#from this map, we get to know the actual minimum coordinate positions in the room
o_grids = np.load('data/targets/'+repr(r)+'.npy',allow_pickle = 'TRUE').item()
#env,event = init_once(room = args.room, task = args.task)
nav_pos = np.argwhere(o_grids['nav_space']==1).tolist()
p = pos
#command to position the agent in one of the navigable positions facing north
custom_rot = {"action": "TeleportFull","horizon": 30,"rotateOnTeleport": True,"rotation": 0,
"x": p[0]*0.25+ o_grids['min_pos']['mx'],
"y": event.metadata['agent']['position']['y'],
"z": p[1]*0.25+ o_grids['min_pos']['mz']}
event = env.step(dict(custom_rot))
debug = False # True-load premade panorama image/ False- Dont
#gridsize = 33
gridsize = params.grid_size
panorama = pan.rotation_image(env, objects_to_visit = [], debug = debug) #gets a panorama image of everything thats visible
bev = proj.bevmap(panorama,grid_size = gridsize, debug = debug)
#save the obtained bev projection
np.save('data/inputs/bev_'+repr(r)+'_'+repr([p[1],p[0]])+'.npy',bev)
print("saved panorama projection image for the room ",r," for the position ",[p[1],p[0]])
'''
#obtain input vision panorama images and approx projection map from that
env,event = init()
debug = False # True-load premade panorama image/ False- Dont
gridsize = 33
panorama = pan.rotation_image(env, objects_to_visit = [], debug = debug) #gets a panorama image of everything thats visible
bev = proj.bevmap(panorama,grid_size = gridsize, debug = debug)
#save the obtained bev projection
np.save('../ai2thor/mapping/data/inputs/bev.npy',bev)
proj.displaymap(bev,'Desk')
nav_map = proj.input_navigation_map(bev, 'Desk', grid_size = gridsize, unk_id = 0,flr_id = 1, tar_id = 2, obs_id = 3)
print("Now displaying input navigation map")
proj.prettyprint(nav_map,argmax = True)
#print(nav_map) #should be grid_size x grid_size x 4 matrix contain floats between 0 and 1
'''
'''
# creating ground truth BEV maps
room = 0
task = 164
env,event = init(room = room, task = task)
#o_grids stores BEV map for all objects as indexed in the event metadata
fname = '/home/hom/Desktop/ai2thor/mapping/gcdata/'+repr(room)+'.npy'
o_grids = gtm.gtmap(env,event) # Obtains ground truth occupancy grids using Ai2Thor functions / try-> Dresser|-01.33|+00.00|-00.75 for room 301
np.save(fname,o_grids)
'''
'''
#loading ground truth BEV maps
room = 0
task = 164
fname = '/home/hom/Desktop/ai2thor/mapping/gcdata/'+repr(room)+'.npy'
o_grids = np.load(fname,allow_pickle = 'TRUE').item()
print("The navigable space ")
gtm.prettyprint(o_grids['nav_space']) #navigable space in the map considering all obstructions
print("The fixed obstructions map")
gtm.prettyprint(o_grids['fixed_obstructions']) #grid with 0s and 1s showing navigable spaces with all objects in the room removed
'''
'''
#utilizing gt maps
print("The navigable space ")
print(o_grids['nav_space']) #navigable space in the map considering all obstructions
# with vision radius of 16, chose a grid size of 33
position = {'x':-0.75, 'y':0.9009992, 'z':-1.25}
#nav_map_t = gtm.target_navigation_map(o_grids, 'Bed', [0,0], grid_size = 33, unk_id = 0,flr_id = 1, tar_id = 2, obs_id = 3)
nav_map_t = gtm.target_navigation_map(o_grids, 'Bed', position, grid_size = 33, unk_id = 0,flr_id = 1, tar_id = 2, obs_id = 3)
print("The target navigation map ")
gtm.prettyprint(nav_map_t)
print("The fixed obstructions map")
gtm.prettyprint(o_grids['fixed_obstructions']) #grid with 0s and 1s showing navigable spaces with all objects in the room removed
'''
'''
#random testing
#gtm.target_vectors() #-> {'Bed|-00.64|+00.00|+00.87': array([ 0., 3., 5., 9., 0., 13., -5., 8.])}
fname = '/home/hom/Desktop/ai2thor/mapping/gcdata/'+repr(301)+'.npy'
o_grids = np.load(fname,allow_pickle = 'TRUE').item()
#gtm.prettyprint(o_grids['Bed|-00.64|+00.00|+00.87'])
gtm.target_vectors1(o_grids,'Bed')
'''
#manual labeling for objects that are unable to be disabled and are like fixed parts in the room
#gtm.manual_label(301) #0 is the room number (0 is the first kitchen, 301 is the first bedroom)
'''
run examples
(debug the panorama image acquisition process)
python datagen.py --room 301 --task 0 --checkpan
(debug the projection map created from the panorama image )
python3 datagen.py --room 301 --task 0 --checkinput
(get ground truth BEV data)
python3 datagen.py --room 301 --task 0 --checktarget
(correct wrong ground truth BEV data)
python datagen.py --room 301 --correct
(get camera based approximate projection BEV data) (must run after ground truth BEV is extracted and corrected)
python datagen.py --room 301 --task 0 --inputs
python datagen.py --room 1 --aliasinput
(complete data preparation of inputs and outputs/ correction need to be done for each seperately later)
python datagen.py --alltargets
python datagen.py --allinputs
'''
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,916,251
|
Homagn/MOVILAN
|
refs/heads/main
|
/planner/low_level_planner/refinement.py
|
import numpy as np
from skimage.measure import regionprops, label
import copy
import sys
import os
os.environ['MAIN'] = '/ai2thor'
sys.path.append(os.path.join(os.environ['MAIN']))
from mapper import test_gcn
import planner.low_level_planner.object_localization as object_localization
def nudge(areas, key, env, act1,act2, rollback = False):
#NOTE!
#In this case we are not adding steps to the entire trajectory in the algorithm
#This is because this is an observable target object area maximization step
#Agent takes a step in the direction which will maximize observed area of target object
#This can be implemented much more efficiently with object tracking models that wont require the agent to brute force as in this code below
change = 0
#count_step is addtional functionality by me which can disable number of steps counter towards the entire trajectory
env.step(dict({"action": act1, 'forceAction': True}), count_step = False)
change+=1
mask_image = env.get_segmented_image()
depth_image = env.get_depth_image()
_,_,_,areas_new,_ = object_localization.location_in_fov(env,mask_image,depth_image)
if key not in areas_new.keys():
areas_new[key] = 0
if areas_new[key]<=areas[key]:
env.step(dict({"action": act2, 'forceAction': True}), count_step = False)
env.step(dict({"action": act2, 'forceAction': True}), count_step = False)
change-=2
mask_image = env.get_segmented_image()
depth_image = env.get_depth_image()
_,_,_,areas_new,_ = object_localization.location_in_fov(env,mask_image,depth_image)
if key not in areas_new.keys():
areas_new[key] = 0
if areas_new[key]<=areas[key]:
env.step(dict({"action": act1, 'forceAction': True}), count_step = False)
change+=1
else:
print("nudged ",act2)
else:
print("nudged ",act1)
if rollback: #cancel nudge refinement
if change==-1:
env.step(dict({"action": act1, 'forceAction': True}), count_step = False)
if change==1:
env.step(dict({"action": act2, 'forceAction': True}), count_step = False)
return env
def unit_refinement(env, obj, numtry = 0):
print("refinement.py -> unit_refinement")
print("Trying this for the ",numtry," time")
#on top of final navigation using graph search , brute force search over the unit grid of the last grid in the path
#add a final translation and final rotation that increases the area of the detected target object in segmentation image
max_area = 0
mask_image = env.get_segmented_image()
depth_image = env.get_depth_image()
_,_,_,areas,_ = object_localization.location_in_fov(env,mask_image,depth_image) #HERE/ face_touch = object_localization.location_in_fov
key = ""
for k in areas.keys():
if obj+'|' in k:
print("Able to see the object ",k)
key = k
print(k," has area ",areas[k])
elif '|' in obj: #this means a resolve function has been called earlier to remove confusion about the object name and now we have the precise name
if obj in k:
print("Able to see the object ",k)
key = k
print(k," has area ",areas[k])
if key=="":
print("Object went out of sight trying to realign")
env.step(dict({"action": "RotateLeft", 'forceAction': True}))
#event = env.step(dict({"action": "RotateLeft"}))
#t.sleep(2)
#event = env.step(dict({"action": "RotateRight"}))
if numtry<3:
return unit_refinement(env, obj, numtry = numtry+1)
else:
return env
env = nudge(areas, key, env, "MoveLeft","MoveRight")
env = nudge(areas, key, env, "MoveAhead","MoveBack")
env = nudge(areas, key, env, "RotateLeft","RotateRight")
return env
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,916,252
|
Homagn/MOVILAN
|
refs/heads/main
|
/planner/low_level_planner/manipulation_signatures.py
|
import os
import sys
os.environ['MAIN'] = '/ai2thor'
sys.path.append(os.path.join(os.environ['MAIN']))
import planner.params as params
import numpy as np
import cv2
import copy
import math
import random
import time as t
#all submodules in this folder
import planner.low_level_planner.drawer_manipulation as drawer_manipulation
import planner.low_level_planner.carry as carry
import planner.low_level_planner.handle_appliance as handle_appliance
import planner.low_level_planner.move_camera as move_camera
import planner.low_level_planner.pick_objects as pick_objects
import planner.low_level_planner.place_objects as place_objects
import planner.low_level_planner.gaze as gaze
drawer_manipulation_remove = drawer_manipulation.drawer_manipulation_remove
drawer_manipulation_place = drawer_manipulation.drawer_manipulation_place
carry = carry.carry
toggle = handle_appliance.toggle
set_default_tilt = move_camera.set_default_tilt
refined_pick = pick_objects.refined_pick
check_pick = pick_objects.check_pick
resolve_place = place_objects.resolve_place
gaze = gaze.gaze
|
{"/main_interactive.py": ["/robot/sensing.py"], "/planner/low_level_planner/heat_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/drawer_manipulation.py"], "/planner/low_level_planner/drawer_manipulation.py": ["/planner/low_level_planner/object_type.py", "/planner/low_level_planner/reverse_actions.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/handle_appliance.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py"], "/planner/low_level_planner/refinement.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/planner/high_level_planner.py": ["/robot/sensing.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/carry.py": ["/planner/low_level_planner/refinement.py", "/planner/low_level_planner/object_localization.py"], "/planner/low_level_planner/navigation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/grid_planning.py", "/planner/low_level_planner/visibility_check.py", "/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/astar_search.py", "/planner/low_level_planner/refinement.py", "/planner/low_level_planner/exploration.py", "/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/visibility_check.py": ["/planner/params.py"], "/main_batchrun.py": ["/robot/sensing.py"], "/mapper/datagen.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/object_localization.py": ["/planner/low_level_planner/resolve.py"], "/planner/low_level_planner/exploration.py": ["/planner/low_level_planner/visibility_check.py"], "/planner/low_level_planner/manipulation_signatures.py": ["/planner/params.py", "/planner/low_level_planner/drawer_manipulation.py", "/planner/low_level_planner/carry.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/place_objects.py", "/planner/low_level_planner/slice_objects.py", "/planner/low_level_planner/gaze.py", "/planner/low_level_planner/heat_objects.py", "/planner/low_level_planner/clean_objects.py"], "/planner/low_level_planner/slice_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py"], "/mapper/test_gcn.py": ["/robot/sensing.py", "/mapper/params.py"], "/planner/low_level_planner/clean_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/handle_appliance.py", "/planner/low_level_planner/place_objects.py"], "/robot/sensing.py": ["/robot/params.py"], "/planner/low_level_planner/place_objects.py": ["/planner/low_level_planner/object_localization.py", "/planner/low_level_planner/object_type.py", "/planner/low_level_planner/move_camera.py", "/planner/low_level_planner/resolve.py", "/planner/low_level_planner/refinement.py"], "/disambiguation/ask_google.py": ["/disambiguation/image_vector.py", "/disambiguation/im_download.py"]}
|
40,929,432
|
ThomasJensz/2810ICT-Assignment
|
refs/heads/main
|
/display.py
|
import openpyxl
import wx
import datetime
import wx.lib.scrolledpanel as scrolled
import matplotlib.pyplot as plt
wb = openpyxl.load_workbook("Crash Statistics Victoria.xlsx", read_only=True)
sheet = wb["Crash Statistics Victoria"]
def FindWithinDates(a, b):
DateStart = StringToDate(a)
DateEnd = StringToDate(b)
rList = []
List = []
for row in sheet.rows:
if type(row[4].value) == str:
for cell in row:
rList.append(cell.value)
List.append(rList)
rList = []
continue
if DateStart < row[4].value < DateEnd:
for cell in row:
rList.append(cell.value)
List.append(rList)
rList = []
app = wx.App()
Example(None, title = 'Accident Within Given Date', results = List[0:25])
app.MainLoop()
wb.close()
def KeywordWithinDates(a, b, c):
DateStart = StringToDate(a)
DateEnd = StringToDate(b)
rList = []
List = []
for row in sheet.rows:
if type(row[4].value) == str:
for cell in row:
rList.append(cell.value)
List.append(rList)
rList = []
continue
if DateStart < row[4].value < DateEnd and c in row[9].value:
for cell in row:
rList.append(cell.value)
List.append(rList)
rList = []
app = wx.App()
Example(None, title = 'Accident Within Given Date', results = List[0:25])
app.MainLoop()
wb.close()
def AlcoholAnalysis(a):
alcoholList = [0,0,0,0,0,0,0,0,0,0,0,0]
darkList = [0,0,0,0,0,0,0,0,0,0,0,0]
alcoholInjList = [0,0,0,0,0,0,0,0,0,0,0,0]
darkInjList = [0,0,0,0,0,0,0,0,0,0,0,0]
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
for row in sheet.rows:
if type(row[4].value) == str:
continue
if row[4].value.year == int(a):
index = row[4].value.month - 1
if row[45].value == "Yes":
if row[27].value > 0 or row[28].value > 0:
alcoholInjList[index] += 1
print("Alc Inj Added:" + months[index])
else:
alcoholList[index] += 1
print("Alc Added:" + months[index])
elif "Dark" in row[11].value:
if row[27].value > 0 or row[28].value > 0:
darkInjList[index] += 1
print("Dark Inj Added:" + months[index])
else:
darkList[index] += 1
print("Dark Added:" + months[index])
plt.plot(months, alcoholList, label = "Alcohol (Non-Injury)")
plt.plot(months, darkList, label = "Dark (Non-Injury)")
plt.plot(months, alcoholInjList, label = "Alcohol (Injury/Fatality)")
plt.plot(months, darkInjList, label = "Dark (Injury/Fatality)")
plt.legend(loc = "upper left")
plt.ylabel("Number of Accidents")
plt.xlabel("Month")
plt.title("Influence of Alcohol on Accident Severity")
plt.show()
wb.close()
def HourlyWithinDates(a,b):
DateStart = StringToDate(a)
DateEnd = StringToDate(b)
hoursData = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
hoursLabel = ["12am", "1am", "2am", "3am", "4am", "5am", "6am", "7am", "8am", "9am", "10am", "11am", "12pm", "1pm", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm", "9pm", "10pm", "11pm"]
for row in sheet.rows:
if type(row[4].value) == str:
continue
if DateStart < row[4].value < DateEnd:
split = row[5].value.split('.')
index = int(split[0])
print(index)
hoursData[index] += 1
plt.plot(hoursLabel, hoursData)
plt.ylabel("Number of Accidents")
plt.xlabel("Time of Day (Hourly)")
plt.title("Hourly Accident Frequency")
plt.show()
wb.close()
def PassengersAnalysis(a):
ctrList = [0,0,0,0,0,0,0]
injList = [0,0,0,0,0,0,0]
labels = [0,1,2,3,4,5,"6+"]
for row in sheet.rows:
if type(row[4].value) == str:
continue
if row[4].value.year == int(a):
index = row[49].value
if index > 6:
index = 6
if row[27].value > 0 or row[28].value > 0:
injList[index] += 1
print("Inj Added: " + str(labels[index]))
else:
ctrList[index] += 1
print("Ctr Added: " + str(labels[index]))
plt.plot(labels, ctrList, label = "Non-Injury")
plt.plot(labels, injList, label = "Serious Injury/Fatality")
plt.legend(loc = "upper left")
plt.ylabel("Number of Accidents")
plt.xlabel("Number of Passengers")
plt.title("Influence of Passengers on Accident Severity")
plt.show()
wb.close()
def StringToDate(data):
split = data.split("-")
try:
year = int(split[0])
month = int(split[1])
day = int(split[2])
date = datetime.datetime(year,month,day)
print("Date Converted")
return date
except:
print("First row skipped")
return datetime.datetime(2000,1,1)
class MyPanel(scrolled.ScrolledPanel):
def __init__(self, parent):
scrolled.ScrolledPanel.__init__(self, parent, -1)
self.SetAutoLayout(1)
self.SetupScrolling()
class Example(wx.Frame):
def __init__(self, parent, title, results):
super(Example, self).__init__(parent, title = title,size = (300,200))
self.InitUI(results)
self.Centre()
self.Show()
def InitUI(self, results):
self.SetSize(wx.Size(1280,720))
p = MyPanel(self)
gr = wx.FlexGridSizer(len(results), len(results[0]), 10, 5)
for i in results:
for j in i:
text = j
gr.Add(wx.StaticText(p, label = str(text)))
print("Row Added")
p.SetSizer(gr)
|
{"/main.py": ["/display.py"]}
|
40,929,433
|
ThomasJensz/2810ICT-Assignment
|
refs/heads/main
|
/main.py
|
import wx
from display import *
class myGUI(wx.Frame):
def __init__ (self,parent,id,title):
wx.Frame.__init__(self,parent,id,title)
self.parent = parent
self.initialise()
def initialise(self):
self.SetSize(wx.Size(900,500))
pnl = wx.Panel(self)
#UI for Function 1
lbl1A = wx.StaticText(pnl,label="Find accident information within given dates.", pos=(25,25))
lbl1B = wx.StaticText(pnl,label="Dates must be formatted as YYYY-MM-DD.", pos=(25,50))
lbl1C = wx.StaticText(pnl,label="Start Date:", pos=(25,80))
lbl1D = wx.StaticText(pnl,label="End Date:", pos=(200,80))
self.input1A = wx.TextCtrl(pnl, value = "", pos = (80, 75))
self.input1B = wx.TextCtrl(pnl, value = "", pos = (255, 75))
btn = wx.Button(pnl, pos = (225,110), label = "Display Accidents")
#Logic for Function 1
btn.Bind(wx.EVT_BUTTON, self.DateSearch)
##UI for Function 2
lbl2A = wx.StaticText(pnl,label="Find hourly number of accidents for given date.", pos=(25,180))
lbl2B = wx.StaticText(pnl,label="Date must be formatted as YYYY-MM-DD.", pos=(25,205))
lbl2C = wx.StaticText(pnl,label="Start Date:", pos=(25,235))
lbl2C = wx.StaticText(pnl,label="End Date:", pos=(200,235))
self.input2A = wx.TextCtrl(pnl, value = "", pos = (80, 230))
self.input2B = wx.TextCtrl(pnl, value = "", pos = (255, 230))
btn2 = wx.Button(pnl, pos = (225,265), label = "Accidents per Hour")
#Logic for Function 2
btn2.Bind(wx.EVT_BUTTON, self.HourSearch)
##UI for Function 3
lbl3A = wx.StaticText(pnl,label="Find accident information with DCA-Code, within given dates.", pos=(525,25))
lbl3B = wx.StaticText(pnl,label="Dates must be formatted as YYYY-MM-DD.", pos=(525,50))
lbl3C = wx.StaticText(pnl,label="Start Date", pos=(525,80))
lbl3D = wx.StaticText(pnl,label="End Date", pos=(700,80))
lbl3E = wx.StaticText(pnl,label="Keyword entered must be capitalised.", pos=(525,100))
lbl3F = wx.StaticText(pnl,label="Keyword:", pos=(525,130))
self.input3A = wx.TextCtrl(pnl, value = "", pos = (580, 75))
self.input3B = wx.TextCtrl(pnl, value = "", pos = (755, 75))
self.input3C = wx.TextCtrl(pnl, value = "", pos = (580, 125))
btn3 = wx.Button(pnl, pos = (755,160), label = "Search Keyword")
#Logic for Function 3
btn3.Bind(wx.EVT_BUTTON, self.KeywordSearch)
##UI for Function 4
lbl4A = wx.StaticText(pnl,label="Discover how alcohol influences accident severity for given year.", pos=(525,200))
lbl4B = wx.StaticText(pnl,label="Year must be formatted as YYYY.", pos=(525,225))
lbl4C = wx.StaticText(pnl,label="Year:", pos=(540,255))
self.input4 = wx.TextCtrl(pnl, value = "", pos = (580, 250))
btn4 = wx.Button(pnl, pos = (755,275), label = "Impact of Alcohol")
#Logic for Function 4
btn4.Bind(wx.EVT_BUTTON, self.AlcoholSearch)
##UI for Function 5
lbl5A = wx.StaticText(pnl,label="Discover how passengers influence accident severity for given year.", pos=(525,325))
lbl5B = wx.StaticText(pnl,label="Year must be formatted as YYYY.", pos=(525,350))
lbl5C = wx.StaticText(pnl,label="Year:", pos=(540,380))
self.input5 = wx.TextCtrl(pnl, value = "", pos = (580, 375))
btn5 = wx.Button(pnl, pos = (740,400), label = "Impact of Passengers")
#Logic for Function 5
btn5.Bind(wx.EVT_BUTTON, self.PassengerSearch)
self.Show()
def DateSearch(self, event):
wx.MessageBox("Notice: Please allow up to a couple minutes to complete, depending on CPU performance. Click okay to continue.")
FindWithinDates(self.input1A.GetValue(), self.input1B.GetValue())
def HourSearch(self, event):
wx.MessageBox("Notice: Please allow up to a couple minutes to complete, depending on CPU performance. Click okay to continue.")
HourlyWithinDates(self.input2A.GetValue(), self.input2B.GetValue())
def KeywordSearch(self, event):
wx.MessageBox("Notice: Please allow up to a couple minutes to complete, depending on CPU performance. Click okay to continue.")
KeywordWithinDates(self.input3A.GetValue(), self.input3B.GetValue(), self.input3C.GetValue())
def AlcoholSearch(self, event):
wx.MessageBox("Notice: Please allow up to a couple minutes to complete, depending on CPU performance. Click okay to continue.")
AlcoholAnalysis(self.input4.GetValue())
def PassengerSearch(self, event):
wx.MessageBox("Notice: Please allow up to a couple minutes to complete, depending on CPU performance. Click okay to continue.")
PassengersAnalysis(self.input5.GetValue())
if __name__ == "__main__":
app = wx.App()
mainFrame = myGUI(None, -1, "Victorian Traffic Accident Data Analysis")
app.MainLoop()
|
{"/main.py": ["/display.py"]}
|
40,944,719
|
maanavshah/cache-policy-lru-mru
|
refs/heads/master
|
/mru_example.py
|
from lib.mru import MRU
mru = MRU()
mru.insert(1)
mru.get()
mru.insert(2)
mru.get()
mru.insert(3)
mru.get()
mru.insert(4)
mru.get()
mru.insert(5)
mru.get()
mru.insert(6)
mru.get()
mru.insert(4)
mru.get()
mru.insert(1)
mru.get()
mru.insert(6)
mru.get()
mru.insert(8)
mru.get()
mru.insert(5)
mru.get()
mru.insert(1)
mru.get()
mru.insert(5)
mru.get()
"""
OUTPUT ::
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 6]
[1, 2, 3, 4, 6]
[2, 3, 1, 4, 6]
[2, 3, 6, 1, 4]
[2, 8, 6, 1, 4]
[5, 8, 6, 1, 4]
[5, 8, 6, 4, 1]
[8, 6, 4, 5, 1]
"""
|
{"/lib/lru.py": ["/lib/cache_policy.py"], "/lru_example.py": ["/lib/lru.py"]}
|
40,945,025
|
Wyesumu/restapi_app
|
refs/heads/main
|
/app/rest_app/models.py
|
from django.db import models
class Deal(models.Model):
customer = models.CharField(max_length=200)
item = models.CharField(max_length=200)
total = models.IntegerField(default=0)
quantity = models.IntegerField(default=0)
date = models.DateTimeField()
|
{"/app/rest_app/serializers.py": ["/app/rest_app/models.py"], "/app/rest_app/views.py": ["/app/rest_app/models.py", "/app/rest_app/utils.py", "/app/rest_app/serializers.py"], "/app/rest_app/utils.py": ["/app/rest_app/models.py", "/app/rest_app/serializers.py"]}
|
40,945,026
|
Wyesumu/restapi_app
|
refs/heads/main
|
/app/rest_app/serializers.py
|
from rest_framework.serializers import ModelSerializer
from .models import Deal
class DealsSerializer(ModelSerializer):
class Meta:
model = Deal
fields = ["customer", "item", "total", "quantity", "date"]
|
{"/app/rest_app/serializers.py": ["/app/rest_app/models.py"], "/app/rest_app/views.py": ["/app/rest_app/models.py", "/app/rest_app/utils.py", "/app/rest_app/serializers.py"], "/app/rest_app/utils.py": ["/app/rest_app/models.py", "/app/rest_app/serializers.py"]}
|
40,945,027
|
Wyesumu/restapi_app
|
refs/heads/main
|
/app/rest_app/views.py
|
#from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser
import csv
import io
from .serializers import DealsSerializer
from .models import Deal
from django.db.models import Sum
from django.views.decorators.cache import cache_control
class UploadData(APIView):
parser_classes = (MultiPartParser,)
def post(self, request, format=None):
decoded_file = request.data['data'].read().decode('utf-8')
io_string = io.StringIO(decoded_file)
dict_csv = list(csv.DictReader(io_string))
serializer = DealsSerializer(data=dict_csv, many=True)
if serializer.is_valid():
Deal.objects.all().delete()
serializer.save()
return Response('Файл был обработан без ошибок', status=status.HTTP_200_OK)
else:
return Response('Error, Desc:' + str(serializer.errors) + '- в процессе обработки файла произошла ошибка', status=status.HTTP_400_BAD_REQUEST)
class GetData(APIView):
@cache_control(must_revalidate=True, max_age=3600)
def get(self, request, format=None):
#find top 5 customers by spent money
deals = Deal.objects.values('customer').annotate(spent_money=Sum('total')).order_by('-spent_money')[:5]
#create list of dictionaries of customers with name, spent money
#and list of all gems bought by customer
customers = []
for deal in deals:
customer = {'customer':deal['customer'], 'spent_money': deal['spent_money'], 'gems':[]}
#get all gems that customer bought
customers_from_db = Deal.objects.filter(customer=customer['customer']).values('item').distinct()
for row in customers_from_db:
customer['gems'].append(row['item'])
customers.append(customer)
result = []
for customer in customers:
for gem in customer['gems']:
gem_has_duplicate = False
#iterate through every customer gems
#and compare it with every other customer gem_list
for c in customers:
#ignore if it's a same customer
if customer['customer'] != c['customer']:
#if other customer has gem in his list
if gem in c['gems']:
#then mark it
gem_has_duplicate = True
#and exit loop for this gem
break
#if wasn't able to find second gem in any other
#customer gem list then delete this gem
if not gem_has_duplicate:
customer['gems'].remove(gem)
result.append(customer)
return Response(result, status=status.HTTP_200_OK)
|
{"/app/rest_app/serializers.py": ["/app/rest_app/models.py"], "/app/rest_app/views.py": ["/app/rest_app/models.py", "/app/rest_app/utils.py", "/app/rest_app/serializers.py"], "/app/rest_app/utils.py": ["/app/rest_app/models.py", "/app/rest_app/serializers.py"]}
|
41,174,779
|
danysousa/krpsim
|
HEAD
|
/config.py
|
import sys
import re
class Config(object):
def __init__(self, filename):
self.filename = filename
try:
fd = open(filename, 'r')
except IOError:
print("Can't open " + filename)
sys.exit(0)
self.parse(fd)
def parse(self, fd):
for line in fd :
if (line[0] == '#'):
continue
self.findAction(line)
def findAction(self, line):
patterns = [
"^([a-zA-Z0-9_]{1,}):([0-9]{1,})$",
"^([a-zA-Z0-9_]{1,}):((\([a-zA-Z0-9_]{1,}:[0-9]\));?){1,}:((\([a-zA-Z0-9_]{1,}:[0-9]\));?){1,}:([a-zA-Z0-9_]{1,})$",
"optimize:\(((time|[a-zA-Z0-9_]{1,});?){1,}\)"
]
name = ["stock", "process", "optimize"]
for i in xrange(0, len(patterns)):
m = re.match(patterns[i], line)
if (m):
print("[" + name[i] + "]: " + line)
print(m.groups())
|
{"/main.py": ["/Stock.py", "/Manager.py", "/Kprocess.py", "/config.py"], "/config.py": ["/Stock.py", "/Kprocess.py"]}
|
41,174,780
|
danysousa/krpsim
|
HEAD
|
/main.py
|
#!/usr/bin/python2.7
from config import Config
import sys
if ( len(sys.argv) == 2 ):
c = Config(sys.argv[1])
else:
print("Usage : ./main.py [config_file]")
|
{"/main.py": ["/Stock.py", "/Manager.py", "/Kprocess.py", "/config.py"], "/config.py": ["/Stock.py", "/Kprocess.py"]}
|
41,197,708
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/services/__init__.py
|
__all__ = ['fabric', 'ordinary_types', 'SerBase', 'serFunc']
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,709
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/services/fabric.py
|
from serializations import JsonClass, TomlClass as t, YamlClass as y, PickleClass as p
def fabrica(s):
if s == 'json':
return JsonClass.JsonClassMy()
elif s == 'pickle':
return p.PickleClassMy()
elif s == 'toml':
return t.TomlClassMy()
elif s == 'yaml':
return y.YamlClassMy()
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,710
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/additionals/13.py
|
# https://www.youtube.com/watch?v=Xgaj0Vxz_to&ab_channel=%D0%A4%D0%BE%D0%BA%D1%81%D1%84%D0%BE%D1%80%D0%B4
# https://foxford.ru/wiki/informatika/bystraya-sortirovka-hoara-python
# quick
import random as ra
def Quck_sort(data):
if len(data) <= 1:
return data
else:
pivot = ra.choice(data)
l = []
r = []
m = []
for elem in data:
if elem < pivot:
l.append(elem)
elif elem > pivot:
r.append(elem)
else:
m.append(elem)
return Quck_sort(l) + m + Quck_sort(r)
# merge https://foxford.ru/wiki/informatika/sortirovka-sliyaniem?provider=google_oauth2
def merge(a, b):
res = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
res.append(a[i])
i += 1
else:
res.append(b[j])
j += 1
res += a[i:] + b[j:]
return res
def merge_sort(data):
if len(data) <= 1:
return data
else:
l = data[:len(data) // 2]
r = data[len(data) // 2:]
return merge(merge_sort(l), merge_sort(r))
# regex
def regex_sort(a):
length = len(str(max(a)))
rang = 10
for i in range(length):
b = [[] for k in range(rang)]
for elem in a:
sign = elem//10**i%10
b[sign].append(elem)
a = []
for k in range(rang):
a +=b[k]
print(a)
A = [12, 5, 664, 63, 5, 73, 93, 127, 432, 64, 34]
regex_sort(A)
a = [2, 3, -4, 3, -7, -8, 9]
# print(merge_sort(a))
# https://foxford.ru/wiki/informatika/porazryadnaya-sortirovka
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,711
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/additionals/8.py
|
def dec(func):
def wrapper(a):
print("look what i have ",a)
print("before")
func(a)
print("after")
return wrapper
@dec
def stand_alone_function(a):
print("Я простая одинокая функция, ты ведь не посмеешь меня изменять? ", a)
storage = {}
def cashed(func):
def wrapper(a1):
global storage
if a1 not in storage:
ans = func(a1)
storage[a1] = ans
return ("The ans was calculated by the func . The res is {}".format(ans))
else:
return ("The ans was taken from cashe . The res is {}".format(storage[a1]))
return wrapper
@cashed
def cubes(n:int)->list:
res = []
for i in range(n):
res.append(i**3)
return res
print(cubes(5))
print(cubes(5))
print("dfvd")
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,712
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/serializations/TomlClass.py
|
from serializations.Exceptions import InvalidTypeSourceException
a = """{
"AllData": {"ArchiveAndDearchieveConfiguration": {
"Archieve": true,
"DeArchieve": true
},
"FinderInfo": {
"Coding": "utf8",
"SourceDirectory": "/Users/victoriasviridchik/Desktop/lab2/SourceDir",
"TargetDirectory": "/Users/victoriasviridchik/Desktop/lab2/TargetDir/",
"LogPath": "/Users/victoriasviridchik/Desktop/zoo/templog.txt",
"NeedToLog": true
},
"CompressingOptions": {
"Compressing": false
},
"EncryptingAndDecriptingOptions": {
"RandomKey": true,
"Encrypt": false,
"DEncrypt": false
},
"DataOptions": {
"Server": "localhost\\SQLEXPRESS",
"Database": "master",
"Trusted_Connection": true
}
}
}"""
from services import SerBase
import inspect
import re
from pydoc import locate
from types import CodeType, FunctionType
FUNCTION_ATTRIBUTES = [
"__code__",
"__name__",
"__defaults__",
"__closure__"
]
CODE_OBJECT_ARGS = [
'co_argcount',
'co_posonlyargcount',
'co_kwonlyargcount',
'co_nlocals',
'co_stacksize',
'co_flags',
'co_code',
'co_consts',
'co_names',
'co_varnames',
'co_filename',
'co_name',
'co_firstlineno',
'co_lnotab',
'co_freevars',
'co_cellvars'
]
class TomlClassMy(SerBase.SerBaseClass):
def dumps(self, obj) -> str:
obj = Serializer.serialize(obj)
return f"tuple = {serialize_toml(obj)}"
def dump(self, obj, fp):
with open(fp, 'w') as fp_prep:
return fp_prep.write(self.dumps(obj))
def loads(self, obj: str):
obj = obj.split('=', 1)
if len(obj) < 2:
raise InvalidTypeSourceException()
else:
obj = obj[1]
obj = deserialize_toml(obj.replace("\\n", "\n").strip())
return Serializer.deserialize(obj)
def load(self, fp):
with open(fp, 'r') as fp_prep:
prep_obj = self.loads(fp_prep.read())
return prep_obj
class Serializer:
@staticmethod
def serialize(obj):
ans = {}
object_type = type(obj)
if object_type == list:
ans["type"] = "list"
ans["value"] = tuple([Serializer.serialize(i) for i in obj])
elif object_type == dict:
ans["type"] = "dict"
ans["value"] = {}
for i in obj:
key = Serializer.serialize(i)
value = Serializer.serialize(obj[i])
ans["value"][key] = value
ans["value"] = tuple((k, ans["value"][k]) for k in ans["value"])
elif object_type == tuple:
ans["type"] = "tuple"
ans["value"] = tuple([Serializer.serialize(i) for i in obj])
elif object_type == bytes:
ans["type"] = "bytes"
ans["value"] = tuple([Serializer.serialize(i) for i in obj])
elif obj is None:
ans["type"] = "NoneType"
ans["value"] = None
elif inspect.isroutine(obj):
ans["type"] = "function"
ans["value"] = {}
members = inspect.getmembers(obj)
members = [i for i in members if i[0] in FUNCTION_ATTRIBUTES]
for i in members:
key = Serializer.serialize(i[0])
if i[0] != "__closure__":
value = Serializer.serialize(i[1])
else:
value = Serializer.serialize(None)
ans["value"][key] = value
if i[0] == "__code__":
key = Serializer.serialize("__globals__")
ans["value"][key] = {}
names = i[1].__getattribute__("co_names")
glob = obj.__getattribute__("__globals__")
globdict = {}
for name in names:
if name in glob and inspect.ismodule(glob[name]):
raise InvalidTypeSourceException
elif name == obj.__name__:
globdict[name] = obj.__name__
elif name in glob and not inspect.ismodule(name) and name not in __builtins__:
globdict[name] = glob[name]
ans["value"][key] = Serializer.serialize(globdict)
ans["value"] = tuple((k, ans["value"][k]) for k in ans["value"])
elif isinstance(obj, (int, float, complex, bool, str)):
typestr = re.search(r"\'(\w+)\'", str(object_type)).group(1)
ans["type"] = typestr
ans["value"] = obj
else:
ans["type"] = "instance"
ans["value"] = {}
members = inspect.getmembers(obj)
members = [i for i in members if not callable(i[1])]
for i in members:
key = Serializer.serialize(i[0])
val = Serializer.serialize(i[1])
ans["value"][key] = val
ans["value"] = tuple((k, ans["value"][k]) for k in ans["value"])
ans = tuple((k, ans[k]) for k in ans)
return ans
@staticmethod
def deserialize(d):
d = dict((a, b) for a, b in d)
object_type = d["type"]
ans = None
if object_type == "list":
ans = [Serializer.deserialize(i) for i in d["value"]]
elif object_type == "dict":
ans = {}
if "value" not in d:
raise InvalidTypeSourceException()
for i in d["value"]:
val = Serializer.deserialize(i[1])
ans[Serializer.deserialize(i[0])] = val
elif object_type == "tuple":
ans = tuple([Serializer.deserialize(i) for i in d["value"]])
elif object_type == "function":
func = [0] * 4
code = [0] * 16
glob = {"__builtins__": __builtins__}
for i in d["value"]:
key = Serializer.deserialize(i[0])
if key == "__globals__":
globdict = Serializer.deserialize(i[1])
for globkey in globdict:
glob[globkey] = globdict[globkey]
elif key == "__code__":
val = i[1][1][1]
for arg in val:
codeArgKey = Serializer.deserialize(arg[0])
if codeArgKey != "__doc__":
codeArgVal = Serializer.deserialize(arg[1])
index = CODE_OBJECT_ARGS.index(codeArgKey)
code[index] = codeArgVal
code = CodeType(*code)
else:
index = FUNCTION_ATTRIBUTES.index(key)
func[index] = (Serializer.deserialize(i[1]))
func[0] = code
func.insert(1, glob)
ans = FunctionType(*func)
if ans.__name__ in ans.__getattribute__("__globals__"):
ans.__getattribute__("__globals__")[ans.__name__] = ans
elif object_type == "NoneType":
ans = None
elif object_type == "bytes":
ans = bytes([Serializer.deserialize(i) for i in d["value"]])
else:
if object_type == "bool":
ans = d["value"] == "True"
else:
ans = locate(object_type)(d["value"])
return ans
def serialize_toml(obj) -> str:
if type(obj) == tuple:
ans = ""
for i in obj:
ans += f"{serialize_toml(i)}, "
return f"[ {ans[0:len(ans) - 1]}]"
else:
return f"\"{str(obj)}\"".replace("\n", "\\n")
def deserialize_toml(obj: str):
if obj == '[]':
return tuple()
elif obj[0] == '[':
obj = obj[1:len(obj) - 1]
parsed = []
depth = 0
quote = False
substr = ""
for i in obj:
if i == '[':
depth += 1
elif i == ']':
depth -= 1
elif i == '\"':
quote = not quote
elif i == ',' and not quote and depth == 0:
parsed.append(deserialize_toml(substr))
substr = ""
continue
elif i == ' ' and not quote:
continue
substr += i
return tuple(parsed)
else:
return obj[1:len(obj) - 1]
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,713
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/serializations/PickleClass.py
|
a = """{
"AllData": {"ArchiveAndDearchieveConfiguration": {
"Archieve": true,
"DeArchieve": true
},
"FinderInfo": {
"Coding": "utf8",
"SourceDirectory": "/Users/victoriasviridchik/Desktop/lab2/SourceDir",
"TargetDirectory": "/Users/victoriasviridchik/Desktop/lab2/TargetDir/",
"LogPath": "/Users/victoriasviridchik/Desktop/zoo/templog.txt",
"NeedToLog": true
},
"CompressingOptions": {
"Compressing": false
},
"EncryptingAndDecriptingOptions": {
"RandomKey": true,
"Encrypt": false,
"DEncrypt": false
},
"DataOptions": {
"Server": "localhost\\SQLEXPRESS",
"Database": "master",
"Trusted_Connection": true
}
}
}"""
# import re as r
# pattern = '""(\w*[^""{}])"": {([^}]*)} ?'
# res = r.match(pattern,a)
# for r in res:
# print(rim
import pickle
from services import SerBase
from .Exceptions import InvalidTypeSourceException
from services.ordinary_types import *
class PickleClassMy(SerBase.SerBaseClass):
def dump(self, obj, fp):
"""сериализует Python объект в файл"""
prep_obj = prepare_data(obj)
with open(fp, 'wb') as fp_prep:
try:
return pickle.dump(prep_obj, fp_prep)
except pickle.PicklingError as e:
raise InvalidTypeSourceException(e)
def dumps(self, obj):
"""сериализует Python объект в строку"""
prep_obj = prepare_data(obj)
try:
return pickle.dumps(prep_obj)
except pickle.PicklingError as e:
raise InvalidTypeSourceException(e)
def load(self, fp):
"""десериализует Python объект из файла"""
with open(fp, 'rb') as fp_prep:
try:
prep_obj = de_prepare_data(pickle.load(fp_prep))
except (pickle.UnpicklingError, KeyError) as e:
raise InvalidTypeSourceException(e)
return prep_obj
def loads(self, s):
"""десериализует Python объект из строки"""
try:
prep_obj = de_prepare_data(pickle.loads(s))
except (pickle.UnpicklingError, KeyError) as e:
raise InvalidTypeSourceException(e)
return prep_obj
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,714
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/tests.py
|
import os
import unittest
from serializations import *
from services.ordinary_types import *
from services.fabric import *
import math
def p(c):
return "the res is {}".format(c)
def summ(a=9, b=1):
return p(a + b)
def out_func(x):
return math.cos(x)
data_etalon = {'__closure__': None,
'__code__': {'co_argcount': 2,
'co_cellvars': [],
'co_code': [116, 0, 124, 0, 124, 1, 23, 0, 131, 1, 83, 0],
'co_consts': [None],
'co_filename': '/Users/victoriasviridchik/PycharmProjects/isp_4sem_2/tests.py',
'co_firstlineno': 7,
'co_flags': 67,
'co_freevars': [],
'co_kwonlyargcount': 0,
'co_lnotab': [0, 1],
'co_name': 'summ',
'co_names': ['p'],
'co_nlocals': 2,
'co_posonlyargcount': 0,
'co_stacksize': 3,
'co_varnames': ['a', 'b']},
'__defaults__': (9, 1),
'__globals__': {'p': {'__closure__': None,
'__code__': {'co_argcount': 1,
'co_cellvars': [],
'co_code': [100,
1,
160,
0,
124,
0,
161,
1,
83,
0],
'co_consts': [None, 'the res is {}'],
'co_filename': '/Users/victoriasviridchik/PycharmProjects/isp_4sem_2/tests.py',
'co_firstlineno': 4,
'co_flags': 67,
'co_freevars': [],
'co_kwonlyargcount': 0,
'co_lnotab': [0, 1],
'co_name': 'p',
'co_names': ['format'],
'co_nlocals': 1,
'co_posonlyargcount': 0,
'co_stacksize': 3,
'co_varnames': ['c']},
'__defaults__': None,
'__globals__': {},
'__name__': 'p'}},
'__name__': 'summ'}
class TestSer(unittest.TestCase):
def test_atom(self):
a_int = prepare_data(9)
a_float = prepare_data(3.14)
self.assertEqual(a_int, 9)
self.assertEqual(a_float, 3.14)
def test_simplices(self):
list_data = [1, 2, 3]
a_list = prepare_data(list_data)
dict_data = {'data': [{'vbh': bytes([6, 9, 123]), 'y': ('x', 5), 'o': {8, 'z'}}]}
a_dict = prepare_data(dict_data)
a_exp = {'data': [{'o': [8, 'z'], 'vbh': [6, 9, 123], 'y': ['x', 5]}]}
self.assertEqual(a_list, list_data)
self.assertEqual(a_dict, a_exp)
def test_func(self):
a_func = prepare_data(summ)
self.assertEqual(de_prepare_data(a_func)(2), "the res is 3")
# self.assertEqual(a_dict, a_exp)
def test_dumps_loads(self):
data = {"I am tired HELP": ["very"], 'float': 3.14, 'bool': True, 'unbool': False}
# a_dict = prepare_data(data)
# a_expp_json = {"I am tired HELP": ["very"]}
# a_expp_pickle =bytes("I am tired HELP")
# print(a_expp)
res = fabrica('json').dumps(data)
res_pickle = fabrica('pickle').dumps(data)
res_toml = fabrica('toml').dumps(data)
res_yaml = fabrica('yaml').dumps(data)
# print(a_expp)
# print(res)
# self.assertEqual(res,a_expp_json)
self.assertEqual(fabrica('json').loads(res), data)
self.assertEqual(fabrica('pickle').loads(res_pickle), data)
self.assertEqual(fabrica('toml').loads(res_toml), data)
self.assertEqual(fabrica('yaml').loads(res_yaml), data)
def test_loads_dumps_json(self):
full_json_str = '{"name": "Viktor", "age": 30, "married": true, "divorced": false, "children": ["Anna", ["Alex", "Nikita"], "Bogdan"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}'
res = fabrica('json').loads(full_json_str)
self.assertEqual(fabrica('json').dumps(res), full_json_str)
def test_dump_load(self):
data = {"I am tired HELP": ["very"]}
# a_dict = prepare_data(data)
# with open('data_json', 'w'):
fabrica('json').dump(data, 'data_json')
self.assertEqual(fabrica('json').load('data_json'), data)
# with open('data_toml', 'w'):
fabrica('toml').dump(data, 'data_toml')
self.assertEqual(fabrica('toml').load('data_toml'), data)
# with open('data_yaml', 'w'):
fabrica('yaml').dump(data, 'data_yaml')
self.assertEqual(fabrica('yaml').load('data_yaml'), data)
# with open('pickle_data', 'wb'):
fabrica('pickle').dump(data, 'pickle_data')
self.assertEqual(fabrica('pickle').load('pickle_data'), data)
os.remove('data_json')
os.remove('data_toml')
os.remove('data_yaml')
os.remove('pickle_data')
def test_func_with_out_import(self):
data = out_func
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('json').dump(data, 'data_json')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('toml').dump(data, 'data_toml')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('yaml').dump(data, 'data_yaml')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('pickle').dump(data, 'pickle_data')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('json').dumps(data)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('toml').dumps(data)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('yaml').dumps(data)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('pickle').dumps(data)
def test_func_ser(self):
data = summ
fabrica('json').dump(data, 'data_json')
fabrica('toml').dump(data, 'data_toml')
fabrica('yaml').dump(data, 'data_yaml')
fabrica('pickle').dump(data, 'pickle_data')
res = fabrica('json').dumps(data)
fabrica('json').loads(res)
res = fabrica('toml').dumps(data)
fabrica('toml').loads(res)
fabrica('yaml').dumps(data)
res = fabrica('pickle').dumps(data)
fabrica('pickle').loads(res)
class TestDeSer(unittest.TestCase):
def test_atom(self):
a_int = de_prepare_data(prepare_data(9))
a_float = de_prepare_data(prepare_data(3.14))
self.assertEqual(a_int, 9)
self.assertEqual(a_float, 3.14)
def test_simplices(self):
list_data = [1, 2, 3]
a_list = de_prepare_data(prepare_data(list_data))
dict_data = {'data': [{'vbh': bytes([6, 9, 123]), 'y': ('x', 5), 'o': {8, 'z'}}]}
a_dict = de_prepare_data(prepare_data(dict_data))
a_exp = {'data': [{'o': [8, 'z'], 'vbh': [6, 9, 123], 'y': ['x', 5]}]}
self.assertEqual(a_list, list_data)
self.assertEqual(a_dict, a_exp)
def test_func(self):
a_func = de_prepare_data(prepare_data(summ))
self.assertEqual(a_func(3), "the res is 4")
# self.assertEqual(a_dict, a_exp)
class CustomExceptionTest(unittest.TestCase):
def test_loads(self):
data = {'data': {'asd': [1, 2, 3]}}
res_json = fabrica('json').dumps(data)
res_pickle = fabrica('pickle').dumps(data)
res_toml = fabrica('toml').dumps(data)
res_yaml = fabrica('yaml').dumps(data)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
res_pickle = res_pickle[:len(res_json) // 2]
fabrica('pickle').loads(res_pickle)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
res_json = res_json[:len(res_json) // 2]
fabrica('json').loads(res_json)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
res_toml = res_toml[:len(res_toml) // 2]
fabrica('toml').loads(res_toml)
with self.assertRaises(Exceptions.InvalidTypeSourceException):
res_yaml = '\x09'
fabrica('yaml').loads(res_yaml)
def test_load(self):
data = {"I am tired HELP": ["very"], 'tired_koef': 100500}
# a_dict = prepare_data(data)
fabrica('json').dump(data, 'data_json')
with open('data_json', 'a') as fp:
fp.seek(3)
fp.write('hhr"en"hr')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('json').load('data_json')
fabrica('yaml').dump(data, 'data_yaml')
with open('data_yaml', 'a') as fp:
fp.seek(3)
fp.write('hhr"en"hr')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('yaml').load('data_yaml')
# fabrica('pickle').dump(data, 'data_pickle')
with open('data_pickle', 'wb') as fp:
# fp.seek(10)
fp.write(b'hhr"en"hsaf;;lmr')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
fabrica('pickle').load('data_pickle')
fabrica('toml').dump(data, 'data_toml')
with open('data_toml', 'w') as fp:
# fp.seek(10, os.SEEK_CUR)
fp.write('hhr"en"hsaf;;lmr')
with self.assertRaises(Exceptions.InvalidTypeSourceException):
res = fabrica('toml').load('data_toml')
fabrica('toml').load('data_toml')
os.remove('data_json')
os.remove('data_toml')
os.remove('data_yaml')
os.remove('data_pickle')
if __name__ == '__main__':
unittest.main()
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,715
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/serializations/Exceptions.py
|
class InvalidTypeSourceException(Exception):
pass
# def __init__(self, *args):
# super().__init__(self, *args)
#
# def __str__(self):
# return 'InvalidTypeSourceException'
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,716
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/file.py
|
from services import fabric
# import json as js
CONST = 6
def ya_func(x):
x += CONST
return x
kaka = fabric.fabrica('pickle')
kaka.dump(ya_func, 'fp')
res = kaka.load('fp')
print(res)
print(res(10))
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,717
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/setup.py
|
from setuptools import setup
setup(name='Isp2lr',
version='1.0',
description='Python Distribution Utilities',
author='VictoriaSv',
author_email='viccisviri@gmail.com',
packages=['serializations', 'services'],
# install_requires=['PyYAML', 'toml'],
scripts=['bin/magic.py'],
test_suit='tests')
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,718
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/serializations/__init__.py
|
__all__ = ['JsonClass', 'PickleClass', 'TomlClass', 'YamlClass', 'Exceptions']
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,719
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/serializations/JsonClass.py
|
from serializations.Exceptions import InvalidTypeSourceException
a = """{
"AllData": {"ArchiveAndDearchieveConfiguration": {
"Archieve": true,
"DeArchieve": true
},
"FinderInfo": {
"Coding": "utf8",
"SourceDirectory": "/Users/victoriasviridchik/Desktop/lab2/SourceDir",
"TargetDirectory": "/Users/victoriasviridchik/Desktop/lab2/TargetDir/",
"LogPath": "/Users/victoriasviridchik/Desktop/zoo/templog.txt",
"NeedToLog": true
},
"CompressingOptions": {
"Compressing": false
},
"EncryptingAndDecriptingOptions": {
"RandomKey": true,
"Encrypt": false,
"DEncrypt": false
},
"DataOptions": {
"Server": "localhost\\SQLEXPRESS",
"Database": "master",
"Trusted_Connection": true
}
}
}"""
# import re as r
# pattern = '""(\w*[^""{}])"": {([^}]*)} ?'
# res = r.match(pattern,a)
# for r in res:
# print(rim
from services.ordinary_types import *
from services import SerBase
import re
# import json
class JsonClassMy(SerBase.SerBaseClass):
def dump(self, obj, fp):
"""сериализует Python объект в файл"""
# prep_obj = prepare_data(obj)
with open(fp, 'w') as fp_prep:
return fp_prep.write(self.dumps(obj))
def dumps(self, obj):
"""сериализует Python объект в строку"""
def dumps_prepared(prep_obj):
return str(prep_obj).replace("'", '"').replace('None', 'null').replace(
'True', 'true').replace('False', 'false').replace('(', '[').replace(')', ']')
prep_obj = prepare_data(obj)
return dumps_prepared(prep_obj)
def load(self, fp):
"""десериализует Python объект из файла"""
# fp_prep = open(fp, 'w')
with open(fp, 'r') as fp_prep:
prep_obj = self.loads(fp_prep.read())
# try:
# prep_obj = de_prepare_data(json.load(fp_prep))
# except json.JSONDecodeError as e:
# raise InvalidTypeSourceException(e)
return prep_obj
def loads(self, s):
"""десериализует Python объект из строки"""
# try:
# prep_obj = de_prepare_data(json.loads(s))
# except json.JSONDecodeError as e:
# raise InvalidTypeSourceException(e)
# return prep_obj
def loads_prep(s: str):
def find_list_end(data, i):
if data[i].strip()[-1] == ']':
return 0
j = i
open_count = 0
while open_count or j == i:
open_count += data[j].count('[')
open_count -= data[j].count(']')
j += 1
return j
def find_dict_end(data, i):
if data[i].strip()[-1] == '}':
return 0
j = i
open_count = 0
while open_count or j == i:
open_count += data[j].count('{')
open_count -= data[j].count('}')
# if data[j].strip()[-1] == '}':
# open_count -= 1
# elif data[j].strip()[0] == '{':
# open_count += 1
j += 1
return j
s = s.strip()
if s[0] == '{' and s[-1] == '}':
# dict
res = {}
data = s[1:len(s) - 1].split(',')
if len(data) == 1 and data[0].strip() == '':
return {}
skip_count = 0
for i in range(len(data)):
if skip_count:
skip_count -= 1
continue
# for key_value in s[1:len(s) - 1].split(','):
key, value = data[i].split(':', 1)
if value.strip()[0] == '[':
j = find_list_end(data, i)
if j != 0:
value = ','.join([value] + data[i + 1:j])
skip_count = j - i - 1
if value.strip()[0] == '{':
j = find_dict_end(data, i)
if j != 0:
value = ','.join([value] + data[i + 1:j])
skip_count = j - i - 1
res[loads_prep(key)] = loads_prep(value)
return res
elif s[0] == '"' and s[-1] == '"':
# str
return str(s[1:len(s) - 1])
elif s == 'null':
return None
elif s == 'true':
return True
elif s == 'false':
return False
elif s[0] == '[' and s[-1] == ']':
res = []
data = s[1:len(s) - 1].split(',')
if len(data) == 1 and data[0].strip() == '':
return []
skip_count = 0
for i in range(len(data)):
if skip_count:
skip_count -= 1
continue
value = data[i]
if value.strip()[0] == '[':
j = find_list_end(data, i)
if j != 0:
value = ','.join([value] + data[i + 1:j])
skip_count = j - i - 1
if value.strip()[0] == '{':
j = find_dict_end(data, i)
if j != 0:
value = ','.join([value] + data[i + 1:j])
skip_count = j - i - 1
res.append(loads_prep(value))
return res
elif re.fullmatch(r"[-+]?\d+", s):
return int(s)
elif re.fullmatch(r"[-+]?\d+\.\d*", s):
return float(s)
else:
raise InvalidTypeSourceException(f'Wrong json type near {s}')
prep_obj = de_prepare_data(loads_prep(s))
return prep_obj
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,720
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/additionals/4.py
|
class Vector(object):
"""creates vector"""
def __init__(self,x=0,y=0):
self.x,self.y = x,y
def __str__(self):
return "({},{})".format(self.x,self.y)
def __add__(self, other):
return Vector(self.x+other.x,self.y+other.y)
def __sub__(self, other):
return Vector(self.x-other.x,self.y-other.y)
def __mul__(self, other):
return Vector(self.x*other,self.y*other)
def scalar(self,other):
return Vector(self.x*other.x+self.x*other.x)
def __len__(self):
return ((self.x)**2+(self.y)**2)**(1/2)
def __cmp__(self, other):
""" self < other отрицательное
self == other нуль
self > other положительное"""
return (len(self) - len(other))
# class IndexIterable:
# def __init__(self, obj):
# self.obj = obj
#
# def __getitem__(self, index):
# return self.obj[index]
#
#
# for letter in IndexIterable('str'):
# print(letter)
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
41,197,721
|
sviridchik/ISP2_4SEM
|
refs/heads/master
|
/additionals/9.py
|
def my_range(start:int , stop:int = None,step=1):
|
{"/services/fabric.py": ["/serializations/__init__.py"], "/serializations/TomlClass.py": ["/serializations/Exceptions.py", "/services/__init__.py"], "/serializations/PickleClass.py": ["/services/__init__.py", "/serializations/Exceptions.py", "/services/ordinary_types.py"], "/tests.py": ["/serializations/__init__.py", "/services/ordinary_types.py", "/services/fabric.py"], "/file.py": ["/services/__init__.py"], "/serializations/JsonClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"], "/services/ordinary_types.py": ["/serializations/Exceptions.py"], "/bin/magic.py": ["/services/__init__.py", "/serializations/__init__.py"], "/serializations/YamlClass.py": ["/serializations/Exceptions.py", "/services/ordinary_types.py", "/services/__init__.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.