branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';
@IonicPage()
@Component({
selector: 'page-editar-articulo',
templateUrl: 'editar-articulo.html',
})
export class EditarArticuloPage {
articulo:any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public http: HttpClient,
public viewController: ViewController) {
this.articulo = navParams.get('articulo');
}
modificarArticulo(){
let articulo = {
id: this.articulo._id,
referencia: this.articulo.referencia,
precio: this.articulo.precio
}
this.http.put('http://localhost:3000/articulo/' + articulo.id, articulo)
.subscribe((resp:any)=>{
this.viewController.dismiss();
},(error)=>{
console.log(error);
})
}
cancelar(){
this.viewController.dismiss();
}
}
| 0db95a1e912c514db9b0e16266e96a5f16e26861 | [
"TypeScript"
] | 1 | TypeScript | tayduivn/erp-ionic-1 | 6ca00e1c28e8f4a16190219b7a384a42c3d4fa88 | 6589863a881528a6cbdc4392d1970381ad6f4e2e |
refs/heads/master | <repo_name>nakashima0709/git_myblog<file_sep>/config/routes.rb
Rails.application.routes.draw do
root "tweet#index"
end
| 9941bc84df628cd2af200b242ef66c8f8ea93865 | [
"Ruby"
] | 1 | Ruby | nakashima0709/git_myblog | 1f17f2d222a83241ef632e752d57e32ce283d6cf | ba9fee5bd8da25bd066180062f2fd154267acd93 |
refs/heads/main | <file_sep>"""Stara verzija frameworka PJ (danas vepar), služi samo za implementaciju
interpretera za jezik C0. Ne koristiti u novijim programima!"""
import enum, types, collections, contextlib
# TODO: lex.prepoznaj: unifikacija ključna_riječ i operator
def ključna_riječ(enumeracija, riječ, case=True):
with contextlib.suppress(ValueError, KeyError):
e = enumeracija(riječ) if case else enumeracija[riječ.upper()]
if e.name.casefold() == e.value.casefold(): return e
def operator(enumeracija, znak):
assert len(znak) == 1
with contextlib.suppress(ValueError): return enumeracija(znak)
def identifikator(znak): return znak.isalnum() or znak == '_'
# TODO: bolji API: Greška(poruka, pozicija ili token ili AST...)
# ali ostaviti i lex.greška() i parser.greška() for convenience
class Greška(Exception): """Baza za sve greške vezane uz poziciju u kodu."""
class LeksičkaGreška(Greška): """Greška nastala prilikom leksičke analize."""
class SintaksnaGreška(Greška): """Greška nastala prilikom sintaksne analize."""
class SemantičkaGreška(Greška):"""Greška nastala prilikom semantičke analize."""
class GreškaIzvođenja(Greška): """Greška nastala prilikom izvođenja."""
class Tokenizer:
def __init__(self, string):
self.pročitani, self.buffer, self.stream = [], None, iter(string)
self.početak = self.i, self.j = 1, 0
@property
def pozicija(self): return self.i, self.j
@property
def sadržaj(self): return ''.join(self.pročitani)
def čitaj(self):
"""Čita sljedeći znak iz buffera ili stringa."""
znak = self.buffer or next(self.stream, '')
self.pročitani.append(znak)
self.buffer = None
if znak == '\n':
self.gornji_j = self.j
self.i += 1
self.j = 0
else: self.j += 1
return znak
def vrati(self):
"""Poništava čitanje zadnjeg pročitanog znaka."""
assert not self.buffer
self.buffer = self.pročitani.pop()
if self.j: self.j -= 1
else:
self.j = self.gornji_j
self.i -= 1
del self.gornji_j
def pogledaj(self):
"""'Viri' u sljedeći znak, 'bez' čitanja."""
znak = self.čitaj()
self.vrati()
return znak
def slijedi(self, znak):
"""Čita sljedeći znak ako i samo ako je jednak očekivanom."""
return self.čitaj() == znak or self.vrati()
def zvijezda(self, uvjet):
"""Čita Kleene* (nula ili više) znakova koji zadovoljavaju uvjet."""
while uvjet(self.čitaj()): pass
self.vrati()
def plus(self, uvjet):
"""Čita Kleene+ (jedan ili više) znakova koji zadovoljavaju uvjet."""
prvi = self.čitaj()
if not uvjet(prvi): self.greška('očekivan ' + uvjet.__name__)
self.zvijezda(uvjet)
def pročitaj(self, znak):
"""Čita zadani znak, ili prijavljuje leksičku grešku."""
if znak != self.čitaj(): self.greška('očekivano {!r}'.format(znak))
def greška(self, info=''):
"""Prijavljuje leksičku grešku."""
if self.buffer: self.čitaj()
poruka = 'Redak {}, stupac {}: '.format(*self.pozicija)
poruka += 'neočekivan znak {!r}'.format(self.pročitani.pop())
if info: poruka += ' (' + info + ')'
raise LeksičkaGreška(poruka)
def token(self, tip):
"""Odašilje token."""
t = Token(tip, self.sadržaj)
t.početak = self.početak
self.pročitani.clear()
self.početak = self.pozicija
return t
class E(enum.Enum): # Everywhere
"""Često korišteni tipovi tokena, neovisno o konkretnom jeziku."""
KRAJ = None # End
GREŠKA = '\x00' # Error
PRAZNO = ' ' # Empty
VIŠAK = '' # Extra
class Token(collections.namedtuple('TokenTuple', 'tip sadržaj')):
"""Klasa koja predstavlja tokene."""
def __new__(cls, tip, sadržaj):
if isinstance(tip.value, type): cls = tip.value
return super().__new__(cls, tip, sadržaj)
def __init__(self, *args):
# if self.tip is E.GREŠKA: prijavi grešku na početku tokena, ne na kraju
self.uspoređeni = set()
self.razriješen = False
def __repr__(self):
ime, sadržaj = self.tip.name, self.sadržaj
if sadržaj not in {ime, ''}: ime += repr(self.sadržaj)
return ime
def __pow__(self, tip):
"""Vraća sebe (istina) ako je zadanog tipa, inače None (laž)."""
if not isinstance(tip, set): tip = {tip}
self.uspoređeni |= tip
if self.tip in tip:
self.razriješen = True
return self
def je(self, *tipovi):
self.uspoređeni.update(tipovi)
if self.tip in tipovi:
self.razriješen = True
return self
def neočekivan(self, info=''):
"""Prijavljuje sintaksnu grešku: neočekivan tip tokena."""
poruka = 'Redak {}, stupac {}: neočekivan token {!r}'
if info: poruka += ' (' + info + ')'
očekivano = ' ili '.join(t.name for t in self.uspoređeni if t!=self.tip)
if očekivano: poruka += '\nOčekivano: ' + očekivano
i, j = getattr(self, 'početak', '??')
raise SintaksnaGreška(poruka.format(i, j, self))
def redeklaracija(self, prvi=None):
"""Prijavljuje semantičku grešku redeklaracije."""
i, j = getattr(self, 'početak', '??')
poruka = 'Redak {}, stupac {}: redeklaracija {!r}'.format(i, j, self)
if prvi is not None:
info = 'Prva deklaracija je bila ovdje: redak {}, stupac {}'
poruka += '\n' + info.format(*prvi.početak)
raise SemantičkaGreška(poruka)
def nedeklaracija(self, info='nedeklarirano'):
"""Prijavljuje semantičku grešku nedeklariranog simbola."""
i, j = getattr(self, 'početak', '??')
poruka = 'Redak {}, stupac {}: {} {!r}'.format(i, j, info, self)
raise SemantičkaGreška(poruka)
def iznimka(self, info):
"""Prijavljuje grešku izvođenja."""
poruka = 'Redak {}, stupac {}: {!r}: {}'
i, j = getattr(self, 'početak', '??')
raise GreškaIzvođenja(poruka.format(i, j, self, info))
@classmethod
def kraj(cls):
"""Oznaka kraja niza tokena."""
t = cls(E.KRAJ, '')
t.početak = 'zadnji', 0
t.razriješen = False
return t
class Parser:
def __init__(self, tokeni):
self.buffer, self.stream = None, iter(tokeni)
self.zadnji, self.kraj = None, Token.kraj()
def čitaj(self):
"""Čitanje sljedećeg tokena iz buffera ili inicijalnog niza."""
token = self.buffer
if token is None:
if self.zadnji is not None and not self.zadnji.razriješen:
self.greška()
token = next(self.stream, self.kraj)
self.buffer = None
self.zadnji = token
return token
def vrati(self):
"""Poništavanje čitanja zadnjeg pročitanog tokena."""
assert not self.buffer, 'Buffer je pun'
self.buffer = self.zadnji
pogledaj = Tokenizer.pogledaj
def pročitaj(self, *tipovi):
"""Čita jedan od dozvoljenih simbola, ili javlja sintaksnu grešku."""
token = self.čitaj()
if token ** set(tipovi): return token
self.vrati()
self.greška()
def slijedi(self, *tipovi):
"""Čita sljedeći token samo ako je odgovarajućeg tipa."""
return self.zadnji if self.čitaj().je(*tipovi) else self.vrati()
def __rshift__(self, tip):
"""Čita sljedeći token samo ako je odgovarajućeg tipa."""
return self.zadnji if self.čitaj() ** tip else self.vrati()
def vidi(self, *tipovi): return self.pogledaj().je(*tipovi)
def __ge__(self, tip): return self.pogledaj() ** tip
def greška(self): self.zadnji.neočekivan()
@classmethod
def parsiraj(klasa, tokeni):
parser = klasa(tokeni)
try: rezultat = parser.start()
except NoneInAST: parser.greška() # BUG: ovo nije dovoljno precizno!
else:
parser.pročitaj(E.KRAJ)
return rezultat
elementarni = str, int, bool
class NoneInAST(Exception): pass
def AST_adapt(component):
if isinstance(component, (Token, AST0, elementarni)): return component
elif isinstance(component, (tuple, list)):
if None in component: raise NoneInAST('Neobuhvaćen slučaj!')
return ListaAST(component)
elif isinstance(component, dict):
if None in component or None in component.values():
raise NoneInAST('Neobuhvaćen slučaj!')
return RječnikAST(component.items())
elif component is None: raise NoneInAST('Neobuhvaćen slučaj!')
else: raise TypeError('Nepoznat tip komponente {}'.format(type(component)))
class AST0:
"""Bazna klasa za sva apstraktna sintaksna stabla."""
def __pow__(self, tip):
return isinstance(tip, type) and isinstance(self, tip)
def je(self, *tipovi): return isinstance(self, tipovi)
class Atom(Token, AST0): """Atomarni token kao apstraktno stablo."""
class ListaAST(tuple):
def __repr__(self): return repr(list(self))
class RječnikAST(tuple):
def __repr__(self): return repr(dict(self))
class Nenavedeno(AST0):
"""Atribut koji nije naveden."""
def __bool__(self): return False
nenavedeno = Nenavedeno()
def AST(atributi):
AST2 = collections.namedtuple('AST2', atributi)
# AST2.__new__.__defaults__ = tuple(nenavedeno for field in AST2._fields)
class AST1(AST2, AST0):
def __new__(cls, *args, **kw):
new_args = [AST_adapt(arg) for arg in args]
new_kw = {k: AST_adapt(v) for k, v in kw.items()}
return super().__new__(cls, *new_args, **new_kw)
return AST1
<file_sep>"""Hardverski NAND-realizator i optimizator digitalnih sklopova.
Zadatak s drugog kolokvija ljetnog semestra 2017. https://goo.gl/JGACGH
Kao međuprikaz (koji se optimizira) korištene su Pythonove liste."""
from vepar import *
class T(TipoviTokena):
OOTV, OZATV, UOTV, UZATV, ILI, NE = "()[]+'"
class SLOVO(Token):
def uNand(t): return t.sadržaj
@lexer
def ds(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isalpha(): yield lex.token(T.SLOVO)
else: yield lex.literal(T)
### Beskontekstna gramatika
# sklop -> disjunkt | sklop ILI disjunkt
# disjunkt -> faktor | disjunkt faktor
# faktor -> SLOVO | faktor NE | OOTV sklop OZATV | UOTV sklop UZATV
class P(Parser):
def sklop(p) -> 'Or|disjunkt':
disjunkti = [p.disjunkt()]
while p >= T.ILI: disjunkti.append(p.disjunkt())
return Or.ili_samo(disjunkti)
def disjunkt(p) -> 'And|faktor':
konjunkti = [p.faktor()]
while p > {T.SLOVO, T.OOTV, T.UOTV}: konjunkti.append(p.faktor())
return And.ili_samo(konjunkti)
def faktor(p) -> 'sklop|Not|SLOVO':
if p >= T.OOTV:
trenutni = p.sklop()
p >> T.OZATV
elif p >= T.UOTV:
trenutni = Not(p.sklop())
p >> T.UZATV
else: trenutni = p >> T.SLOVO
while p >= T.NE: trenutni = Not(trenutni)
return trenutni
class Not(AST):
ulaz: 'sklop'
def uNand(self): return [self.ulaz.uNand()]
class And(AST):
ulazi: 'sklop*'
def uNand(self): return [[ulaz.uNand() for ulaz in self.ulazi]]
class Or(AST):
ulazi: 'sklop*'
def uNand(self): return [[ulaz.uNand()] for ulaz in self.ulazi]
def pod_negacijom(sklop):
"""Vraća x ako je sklop == [x], inače None."""
if isinstance(sklop, list) and len(sklop) == 1: return sklop[0]
def optimiziraj(sklop):
if isinstance(sklop, str): return sklop
opt = [optimiziraj(ulaz) for ulaz in sklop]
return pod_negacijom(pod_negacijom(opt)) or opt
print(opis := "x ([yxx'] + y')")
ds(opis)
prikaz(ast := P(opis))
print(nand := ast.uNand()) # [['x', [[[[['y', 'x', ['x']]]]], [['y']]]]]
print(optimiziraj(nand))
<file_sep>r"""Interpreter za programski "jezik" koji reprezentira liste.
Liste se pišu kao [x1,x2,...,xk], svaki xi može biti broj, string ili lista.
Neprazne liste mogu imati "viseći zarez" prije zatvorene uglate zagrade.
Brojevi su samo prirodni (veći od 0).
Stringovi se pišu kao "...", gdje unutar ... ne smije biti znak ".
Stringovi se mogu pisati i kao '...', gdje unutar ... nema znaka '.
Zapravo, "..."-stringovi smiju sadržavati i ", ali uvedene znakom \.
Dakle, \" označava ". \n označava novi red. \\ označava \.
Unutar '...'-stringova \ nema nikakvo posebno značenje."""
from vepar import *
BKSL, N1, N2, NOVIRED = '\\', "'", '"', '\n'
@cache
def raspiši(string):
"""Interpretira obrnute kose crte (backslashes) u stringu."""
iterator, rezultat = iter(string), []
for znak in iterator:
if znak == BKSL:
sljedeći = next(iterator)
if sljedeći == 'n': rezultat.append(NOVIRED)
else: rezultat.append(sljedeći)
else: rezultat.append(znak)
return ''.join(rezultat)
class T(TipoviTokena):
UOTV, UZATV, ZAREZ = '[],'
class BROJ(Token):
"""Pozitivni prirodni broj."""
def vrijednost(t): return int(t.sadržaj)
class STRING1(Token):
"""String u jednostrukim navodnicima (raw string)."""
def vrijednost(t): return t.sadržaj[1:-1]
class STRING2(Token):
"""String u dvostrukim navodnicima (backslash kao escape)."""
def vrijednost(t): return raspiši(t.sadržaj[1:-1])
@lexer
def listlexer(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isdecimal():
lex.prirodni_broj(znak, nula=False)
yield lex.token(T.BROJ)
elif znak == N1:
lex - N1
yield lex.token(T.STRING1)
elif znak == N2:
while (znak := next(lex)) != N2:
if not znak:
raise lex.greška('nezavršeni string do kraja ulaza!')
elif znak == NOVIRED:
raise lex.greška('nezavršeni string do kraja retka!')
elif znak == BKSL: next(lex)
yield lex.token(T.STRING2)
else: yield lex.literal(T)
## Beskontekstna gramatika
# element -> BROJ | STRING1 | STRING2 | UOTV elementi UZATV
# elementi -> element | elementi ZAREZ element | ''
class P(Parser):
def element(self) -> 'Lista|BROJ|STRING1|STRING2':
if self >= T.UOTV:
if self >= T.UZATV: return Lista([])
elementi = [self.element()]
while self >= T.ZAREZ and not self > T.UZATV:
elementi.append(self.element())
self >> T.UZATV
return Lista(elementi)
else: return self >> {T.BROJ, T.STRING1, T.STRING2}
## AST:
# element: Lista: elementi:[element]
# BROJ: Token
# STRING1: Token
# STRING2: Token
class Lista(AST):
elementi: 'element*'
def vrijednost(self): return [el.vrijednost() for el in self.elementi]
print(lista := r'''
[[], 23, "ab\"c]", 'a[]', [2, 3, ], 523, [1,2,2,3], '"', '\', "\e",
"\\", '', "", "\[", ]
''')
listlexer(lista)
prikaz(ast := P(lista), 2)
print(v := ast.vrijednost())
print(*v, sep='\t')
# DZ: omogućite razne druge \-escape sekvence (npr. \u za znakove Unikoda)
# DZ: omogućite izraze umjesto samih konstantnih vrijednosti:
# implementirajte polimorfni + za zbrajanje/konkatenaciju
<file_sep>"""Virtualna mašina za rad s listama; kolokvij 31. siječnja 2011. (Puljić).
9 registara (L1 do L9) koji drže liste cijelih brojeva (počinju od prazne),
2 naredbe (ubacivanje i izbacivanje elementa po indeksu),
3 upita (duljina i praznost liste, dohvaćanje elementa po indeksu)."""
from vepar import *
class T(TipoviTokena):
LISTA, UBACI, IZBACI = 'lista', 'ubaci', 'izbaci'
KOLIKO, PRAZNA, DOHVATI = 'koliko', 'prazna', 'dohvati'
class ID(Token): pass
class BROJ(Token):
def vrijednost(self): return int(self.sadržaj)
class MINUSBROJ(BROJ): """Negativni broj."""
@lexer
def listlexer(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == 'L':
if (nakonL := next(lex)).isdecimal():
n = lex.prirodni_broj(nakonL)
tok = lex.token(T.ID)
if 1 <= n <= 9: yield tok
else: raise tok.krivi_sadržaj('očekivan broj liste između 1 i 9')
else:
lex * str.isalpha
yield lex.literal(T, case=False)
elif znak.isalpha():
lex * str.isalpha
yield lex.literal(T, case=False)
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak == '-':
lex.prirodni_broj('', nula=False)
yield lex.token(T.MINUSBROJ)
else: raise lex.greška()
### Beskontekstna gramatika (jezik je regularan!)
# start -> '' | start naredba
# naredba -> deklaracija | provjera | ubaci | izbaci | dohvati | duljina
# deklaracija -> LISTA ID
# provjera -> PRAZNA ID
# ubaci -> UBACI ID BROJ BROJ | UBACI ID MINUSBROJ BROJ
# izbaci -> IZBACI ID BROJ
# dohvati -> DOHVATI ID BROJ
# duljina -> KOLIKO ID
### Apstraktna sintaksna stabla
# Program: naredbe:[naredba]
# naredba: Deklaracija: lista:ID
# Provjera: lista:ID
# Ubaci: lista:ID vrijednost:BROJ|MINUSBROJ indeks:BROJ
# Izbaci: lista:ID indeks:BROJ
# Dohvati: lista:ID indeks:BROJ
# Duljina: lista:ID
class P(Parser):
def start(self) -> 'Program':
naredbe = []
while not self > KRAJ: naredbe.append(self.naredba())
return Program(naredbe)
def naredba(self) -> 'Ubaci|Deklaracija|Provjera|Izbaci|Dohvati|Duljina':
if self >= T.LISTA: return Deklaracija(self >> T.ID)
elif self >= T.PRAZNA: return Provjera(self >> T.ID)
elif self >= T.KOLIKO: return Duljina(self >> T.ID)
elif self >= T.DOHVATI: return Dohvati(self >> T.ID, self >> T.BROJ)
elif self >= T.IZBACI: return Izbaci(self >> T.ID, self >> T.BROJ)
elif self >= T.UBACI: return Ubaci(self >> T.ID,
self >> {T.BROJ,T.MINUSBROJ}, self >> T.BROJ)
else: raise self.greška()
class Program(AST):
"""Program u jeziku listâ."""
naredbe: 'naredba*'
def izvrši(self):
rt.mem = Memorija(redefinicija=False)
for nar in self.naredbe: print(nar, ' --> ', nar.izvrši())
class Deklaracija(AST):
"""Deklaracija liste."""
lista: 'ID'
def izvrši(self): rt.mem[self.lista] = []
class Provjera(AST):
"""Je li lista prazna?"""
lista: 'ID'
def izvrši(self): return not rt.mem[self.lista]
class Duljina(AST):
"""Broj elemenata u listi."""
lista: 'ID'
def izvrši(self): return len(rt.mem[self.lista])
class Dohvati(AST):
"""Element zadanog indeksa (brojeći od 0). Prevelik indeks javlja grešku."""
lista: 'ID'
indeks: 'BROJ'
def izvrši(self):
l, i = rt.mem[self.lista], self.indeks.vrijednost()
if i < len(l): return l[i]
else: raise self.iznimka('Prevelik indeks')
class Izbaci(AST):
"""Izbacuje element zadanog indeksa iz liste ili javlja grešku izvođenja."""
lista: 'ID'
indeks: 'BROJ'
def izvrši(self):
l, i = rt.mem[self.lista], self.indeks.vrijednost()
if i < len(l): del l[i]
else: raise self.iznimka('Prevelik indeks')
class Ubaci(AST):
"""Ubacuje vrijednost u listu na zadanom indeksu, ili javlja grešku."""
lista: 'ID'
element: 'BROJ|MINUSBROJ'
indeks: 'BROJ'
def izvrši(self):
l, i = rt.mem[self.lista], self.indeks.vrijednost()
if i <= len(l): l.insert(i, self.element.vrijednost())
else: raise self.iznimka('Prevelik indeks')
listlexer('lista L1 prazna ubaci-2345izbaci L9 dohvati 3 koliko')
P('''
lista L1 lista L3 ubaci L3 45 0 dohvati L3 0
koliko L1 koliko L3 prazna L1 prazna L3
Lista L5 ubaci L5 6 0 ubaci L5 -7 1 ubaci L5 8 1 ubaci L5 9 0
koliko L5 dohvati L5 0 dohvati L5 1 dohvati L5 2 dohvati L5 3
izbaci L5 1 koliko L5 dohvati L5 0 dohvati L5 1 dohvati L5 2
''').izvrši()
for ime, lista in rt.mem: print(ime, '=', lista)
with LeksičkaGreška: listlexer('L0')
with SintaksnaGreška: P('ubaci L5 6 -2')
with SemantičkaGreška: P('ubaci L7 5 0').izvrši()
with LeksičkaGreška: listlexer('ubaci L3 5 -0')
with GreškaIzvođenja: P('lista L1 ubaci L1 7 3').izvrši()
<file_sep># nedovršeno i vjerojatno nepotrebno
from pj import *
class LOOP(enum.Enum):
INC, DEC, MACRO = 'INC', 'DEC', 'macro'
TOČKAZ, VOTV, VZATV = ';{}'
class IME(Token): pass
class R(Token):
@property
def broj(self): return int(self.sadržaj[1:])
def loop_lex(prog):
lex = Tokenizer(prog)
for znak in iter(lex.čitaj, ''):
if znak.isspace(): lex.token(E.PRAZNO)
elif znak.isalpha():
lex.zvijezda(str.isalnum)
ime = lex.sadržaj
if ime.startswith('R') and ime[1:].isdigit():
yield lex.token(LOOP.R)
else: yield lex.token(ključna_riječ(LOOP, ime) or LOOP.IME)
else: yield lex.token(operator(LOOP, znak) or lex.greška())
### Beskontekstna gramatika:
# start -> makro_dekl* program
# makro_dekl -> MACRO IME+ p_zagr
# p_zagr -> VOTV program VZATV
# program -> naredba*
# naredba -> opkod arg TOČKAZ | IME arg+ TOČKAZ | arg p_zagr
# opkod -> INC | DEC
# arg -> R | IME
### Apstraktna sintaksna stabla:
# Kôd: makroi:Dict[IME->Program], parametri:Dict[IME->List[IME]], main:Program
# Petlja: registar:R|IME, tijelo:Program
# Inkrement|Dekrement: registar:R|IME
# Program: naredbe:List[Petlja|Inkrement|Dekrement|MakroPoziv]
# MakroPoziv: makro:IME, argumenti:List[R|IME]
class LOOPParser(Parser):
def start(self):
makroi, parametri = {}, {}
while self >> LOOP.MACRO:
ime = self.pročitaj(LOOP.IME)
parametri[ime] = []
while self >> LOOP.IME: parametri[ime].append(self.zadnji)
makroi[ime] = self.program_u_zagradi()
return Kôd(makroi, parametri, self.program())
def program_u_zagradi(self):
self.pročitaj(LOOP.VOTV)
u_zagradi = self.program()
self.pročitaj(LOOP.VZATV)
return u_zagradi
def program(self):
naredbe = [self.naredba()]
while not self >= {E.KRAJ, LOOP.VZATV}: naredbe.append(self.naredba())
return Program(naredbe)
def naredba(self):
if self >> {LOOP.INC, LOOP.DEC}:
opkod = Inkrement if self.zadnji ** LOOP.INC else Dekrement
reg = self.pročitaj(LOOP.R, LOOP.IME)
self.pročitaj(LOOP.TOČKAZ)
return opkod(reg)
početak = self.pročitaj(LOOP.R, LOOP.IME)
if self >= LOOP.VOTV: return Petlja(početak, self.program_u_zagradi())
argumenti = []
while self >> {LOOP.R, LOOP.IME}: argumenti.append(self.zadnji)
self.pročitaj(LOOP.TOČKAZ)
return MakroPoziv(početak, argumenti)
class Kôd(AST('makroi parametri main')):
def izvrši(self, registri):
self.main.izvrši(registri)
class Program(AST('naredbe')):
def izvrši(self, registri):
for naredba in self.naredbe:
naredba.izvrši(registri)
class Inkrement(AST('registar')):
def izvrši(self, registri):
registri[self.registar.broj] += 1
class Dekrement(AST('registar')):
def izvrši(self, registri):
if registri[self.registar.broj]:
registri[self.registar.broj] -= 1
class Petlja(AST('registar tijelo')):
def izvrši(self, registri):
for ponavljanje in range(registri[self.registar.broj]):
self.tijelo.izvrši(registri)
class MakroPoziv(AST('makro argumenti')):
pass
def računaj(program, *ulazi):
registri = collections.Counter()
for indeks, ulaz in enumerate(ulazi, 1):
assert isinstance(ulaz, int) and ulaz >= 0
registri[indeks] = ulaz
program.izvrši(registri)
return registri[0]
if __name__ == '__main__':
program = LOOPParser.parsiraj(loop_lex('''
macro ZERO Rj { Rj { DEC Rj; } }
macro MOVE from to { ZERO to; from { INC to; } }
macro REMOVE from to { MOVE from to; ZERO from; }
ZERO R0; INC R0; INC R0;
'''))
print(program)
<file_sep>"""Interpreter za pseudokod, s funkcijskim pozivima i dva tipa podataka.
Podržane naredbe:
ako je Uvjet naredba inače naredba ime = izraz
ako je Uvjet naredba Ime = Uvjet
ako nije Uvjet naredba vrati izraz
dok je Uvjet naredba vrati Uvjet
dok nije Uvjet naredba (naredba1, naredba2, ...)
Podržani aritmetički izrazi: Podržani logički uvjeti:
cijeli_broj Istina
ime Laž
ime(argumenti) Ime
izraz + izraz Ime(argumenti)
izraz - izraz Uvjet Ili Uvjet
izraz * izraz izraz < izraz
-izraz izraz = izraz
(izraz) (Uvjet)
Program se sastoji od jedne ili više deklaracija funkcija, s ili bez parametara.
Jedna od njih mora biti program(parametri), od nje počinje izvršavanje.
Tipovi varijabli (i povratni tipovi funkcija) se reprezentiraju leksički:
veliko početno slovo označava logički tip (bool)
malo početno slovo označava aritmetički tip (int)
Minimalni kontekst je potreban da bismo zapamtili jesmo li trenutno u definiciji
aritmetičke ili logičke funkcije, kako bi naredba "vrati" znala što očekuje.
"""
from pj import *
class PSK(enum.Enum):
AKO, DOK, INAČE, VRATI = 'ako', 'dok', 'inače', 'vrati'
JE, NIJE, ILI = 'je', 'nije', 'Ili'
OTV, ZATV, ZAREZ, JEDNAKO, MANJE, PLUS, MINUS, ZVJEZDICA = '(),=<+-*'
class AIME(Token):
"""Aritmetičko ime (ime za broj), počinje malim slovom."""
def vrijednost(self, mem): return pogledaj(mem, self)
class LIME(Token):
"""Logičko ime (ime za logičku vrijednost), počinje velikim slovom."""
def vrijednost(self, mem): return pogledaj(mem, self)
class BROJ(Token):
"""Aritmetička konstanta (prirodni broj)."""
def vrijednost(self, mem): return int(self.sadržaj)
class ISTINA(Token):
literal = 'Istina'
def vrijednost(self, _): return True
class LAŽ(Token):
literal = 'Laž'
def vrijednost(self, _): return False
def pseudokod_lexer(program):
lex = Tokenizer(program)
for znak in iter(lex.čitaj, ''):
if znak.isspace(): lex.zanemari()
elif znak.islower():
lex.zvijezda(str.isalpha)
yield lex.literal(PSK.AIME)
elif znak.isalpha():
lex.zvijezda(str.isalpha)
if lex.sadržaj in {'Istina', 'Laž'}: yield lex.token(PSK.LKONST)
else: yield lex.literal(PSK.LIME)
elif znak.isdigit():
lex.zvijezda(str.isdigit)
yield lex.token(PSK.BROJ)
elif znak == '#':
lex.pročitaj_do('\n')
lex.zanemari()
else: yield lex.literal(PSK)
### BKG (ne sasvim BK:)
# naredba -> pridruži | OTV naredbe? ZATV | (AKO | DOK) (JE | NIJE) log naredba
# | AKO JE log naredba INAČE naredba | VRATI argument
# ime -> AIME | LIME
# parametri -> ime (ZAREZ parametri)?
# naredbe -> naredba (ZAREZ naredbe)?
# program -> ime OTV parametri? ZATV JEDNAKO naredba program?
# pridruži -> AIME JEDNAKO aritm | LIME JEDNAKO log
# log -> log ILI disjunkt | disjunkt
# disjunkt -> aritm (MANJE | JEDNAKO) aritm | LIME | LKONST |
# LIME OTV argumenti ZATV | OTV log ZATV
# aritm -> aritm PLUS član | aritm MINUS član
# član -> član ZVJEZDICA faktor | faktor | MINUS faktor
# faktor -> BROJ | AIME | OTV aritm ZATV | AIME OTV argumenti ZATV
# argumenti -> argument (ZAREZ argumenti)?
# argument -> aritm |! log [KONTEKST!]
class PseudokodParser(Parser):
def program(self):
self.funkcije = {}
while not self >> E.KRAJ:
funkcija = self.funkcija()
imef = funkcija.ime
if imef in self.funkcije: raise SemantičkaGreška(
'Dvaput definirana funkcija {}'.format(imef))
self.funkcije[imef] = funkcija
return self.funkcije
def naredba(self):
if self >> {PSK.AKO, PSK.DOK}:
petlja = self.zadnji ^ PSK.DOK
istina = bool(self.pročitaj(PSK.JE, PSK.NIJE) ^ PSK.JE)
uvjet, naredba = self.log(), self.naredba()
if petlja: return Petlja(uvjet, istina, naredba)
inače = self.naredba() if istina and self >> PSK.INAČE else Blok([])
return Grananje(uvjet, istina, naredba, inače)
elif self >> PSK.OTV:
if self >> PSK.ZATV: return Blok([])
u_zagradi = self.naredbe()
self.pročitaj(PSK.ZATV)
return u_zagradi
elif self >> {PSK.AIME, PSK.LIME}:
ime = self.zadnji
self.pročitaj(PSK.JEDNAKO)
vrijednost = self.log() if ime ^ PSK.LIME else self.aritm()
return Pridruživanje(ime, vrijednost)
elif self >> PSK.VRATI:
return Vrati(self.log() if self.logička else self.aritm())
else: raise self.greška()
def funkcija(self):
ime = self.pročitaj(PSK.LIME, PSK.AIME)
self.logička = bool(ime ^ PSK.LIME)
self.pročitaj(PSK.OTV)
if self >> PSK.ZATV: parametri = []
elif self >> {PSK.LIME, PSK.AIME}:
parametri = [self.zadnji]
while self >> PSK.ZAREZ:
parametri.append(self.pročitaj(PSK.LIME, PSK.AIME))
self.pročitaj(PSK.ZATV)
else: raise self.greška()
self.pročitaj(PSK.JEDNAKO)
return Funkcija(ime, parametri, self.naredba())
def naredbe(self):
naredbe = [self.naredba()]
while self >> PSK.ZAREZ:
if self >= PSK.ZATV: return Blok(naredbe)
naredbe.append(self.naredba())
return Blok(naredbe)
def log(self):
disjunkti = [self.disjunkt()]
while self >> PSK.ILI: disjunkti.append(self.disjunkt())
return disjunkti[0] if len(disjunkti) == 1 else Disjunkcija(disjunkti)
def disjunkt(self):
if self >> PSK.LKONST: return self.zadnji
elif self >> PSK.LIME:
ime = self.zadnji
if self >= PSK.OTV: return self.poziv(ime)
else: return ime
lijevo = self.aritm()
manje = bool(self.pročitaj(PSK.JEDNAKO, PSK.MANJE) ^ PSK.MANJE)
desno = self.aritm()
return Usporedba(manje, lijevo, desno)
def poziv(self, ime):
if ime in self.funkcije: funkcija = self.funkcije[ime]
else: raise ime.nedeklaracija()
return Poziv(funkcija, self.argumenti(funkcija.parametri))
def argumenti(self, parametri):
arg = []
prvi = True
for parametar in parametri:
self.pročitaj(PSK.OTV if prvi else PSK.ZAREZ)
prvi = False
arg.append(self.log() if parametar ^ PSK.LIME else self.aritm())
self.pročitaj(PSK.ZATV)
return arg
def aritm(self):
članovi = [self.član()]
while self >> {PSK.PLUS, PSK.MINUS}:
operator = self.zadnji
dalje = self.član()
članovi.append(dalje if operator ^ PSK.PLUS else Suprotan(dalje))
return članovi[0] if len(članovi) == 1 else Zbroj(članovi)
def član(self):
if self >> PSK.MINUS: return Suprotan(self.faktor())
faktori = [self.faktor()]
while self >> PSK.ZVJEZDICA: faktori.append(self.faktor())
return faktori[0] if len(faktori) == 1 else Umnožak(faktori)
def faktor(self):
if self >> PSK.BROJ: return self.zadnji
elif self >> PSK.AIME:
ime = self.zadnji
if self >= PSK.OTV: return self.poziv(ime)
else: return ime
else:
self.pročitaj(PSK.OTV)
u_zagradi = self.aritm()
self.pročitaj(PSK.ZATV)
return u_zagradi
start = program
def izvrši(funkcije, *argv):
program = Token(PSK.AIME, 'program')
if program in funkcije:
izlazna_vrijednost = funkcije[program].pozovi(argv)
print('Program je vratio:', izlazna_vrijednost)
else: raise SemantičkaGreška('Nema glavne funkcije "program"')
class Funkcija(AST('ime parametri naredba')):
def pozovi(self, argumenti):
lokalni = {p.sadržaj: arg for p, arg in zip(self.parametri, argumenti)}
try: self.naredba.izvrši(lokalni)
except Povratak as exc: return exc.povratna_vrijednost
else: raise GreškaIzvođenja('{} nije ništa vratila'.format(self.ime))
class Poziv(AST('funkcija argumenti')):
"""Izraz koji predstavlja funkcijski poziv sa zadanim argumentima."""
def vrijednost(self, mem):
argumenti = [argument.vrijednost(mem) for argument in self.argumenti]
return self.funkcija.pozovi(argumenti)
def _asdict(self): # samo za ispis, da se ne ispiše čitava funkcija
return {'*ime': self.funkcija.ime, 'argumenti': self.argumenti}
class Grananje(AST('uvjet istina naredba inače')):
def izvrši(self, mem):
if self.uvjet.vrijednost(mem) == self.istina: self.naredba.izvrši(mem)
else: self.inače.izvrši(mem)
class Petlja(AST('uvjet istina naredba')):
def izvrši(self, mem):
while self.uvjet.vrijednost(mem) == self.istina:
self.naredba.izvrši(mem)
class Blok(AST('naredbe')):
def izvrši(self, mem):
for naredba in self.naredbe: naredba.izvrši(mem)
class Pridruživanje(AST('ime pridruženo')):
def izvrši(self, mem):
mem[self.ime.sadržaj] = self.pridruženo.vrijednost(mem)
class Vrati(AST('što')):
def izvrši(self, mem): raise Povratak(self.što.vrijednost(mem))
class Disjunkcija(AST('disjunkti')):
def vrijednost(self, mem):
return any(disjunkt.vrijednost(mem) for disjunkt in self.disjunkti)
class Usporedba(AST('manje lijevo desno')):
def vrijednost(self, mem):
l, d = self.lijevo.vrijednost(mem), self.desno.vrijednost(mem)
return l < d if self.manje else l == d
class Zbroj(AST('pribrojnici')):
def vrijednost(self, mem): return sum(pribrojnik.vrijednost(mem)
for pribrojnik in self.pribrojnici)
class Suprotan(AST('od')):
def vrijednost(self, mem): return -self.od.vrijednost(mem)
class Umnožak(AST('faktori')):
def vrijednost(self, mem):
p = 1
for faktor in self.faktori: p *= faktor.vrijednost(mem)
return p
class Povratak(Exception):
@property
def povratna_vrijednost(self): return self.args[0]
modul = '''\
Identiteta(V) = vrati V # potrebno zbog dvoznačnosti: u "ako je V (...",
# ( se interpretira kao poziv a ne kao blok
# "ako je Identiteta(V) (..." nema taj problem
Negacija(V) = ako je V vrati Laž inače vrati Istina
Neparan(x) = (
N = Laž,
dok nije x = 0 (
x = x - 1,
N = Negacija(N),
),
vrati N
)
'''
suma_faktorijela = PseudokodParser.parsiraj(pseudokod_lexer(modul + '''\
fakt(x) = ( # faktorijel, računamo iterativno (mora biti x>0)
f = 1,
dok nije x = 0 (
f = f*x,
x = x-1
),
vrati f
)
program() = ( # suma faktorijelâ neparnih brojeva do isključivo 9
s = 0,
t = 0,
dok je t < 9 (
ako je Neparan(t) s = s + fakt(t),
t = t + 1
),
vrati s
)
'''))
prikaz(suma_faktorijela, dubina=22)
izvrši(suma_faktorijela)
tablice_istinitosti = PseudokodParser.parsiraj(pseudokod_lexer(modul + '''\
Konjunkcija(P, Q) = ako je P vrati Q inače vrati P
Disjunkcija(P, Q) = ako je P vrati P inače vrati Q
Kondicional(P, Q) = vrati Disjunkcija(Negacija(P), Q)
Bikondicional(P, Q) = vrati Konjunkcija(Kondicional(P, Q), Kondicional(Q, P))
Multiplex(m, P, Q) = # rudimentarni switch/case
ako je m = 1 vrati Konjunkcija(P, Q) inače
ako je m = 2 vrati Disjunkcija(P, Q) inače
ako je m = 3 vrati Kondicional(P, Q) inače
ako je m = 4 vrati Bikondicional(P, Q) inače
ako je m = 5 vrati Negacija(P) inače
vrati Laž
# Iako PSK 'nativno' radi samo s logičkim vrijednostima i cijelim brojevima,
# možemo raditi s raznim drugim tipovima podataka pomoću _kodiranja_.
# Primjer: listu malih brojeva (a,b,...,n) kodiramo u broj 6a8b8...8n9
# (mali brojevi su do 5; 6 i 9 su zagrade, 8 je zarez/separator).
# Naravno, logičke vrijednosti kodiramo kao male brojeve 0 odnosno 1.
# Može se činiti umjetnim, ali zapravo je sveprisutno pri funkcioniranju
# modernih računala: svaki objekt je predstavljen nizom bajtova.
broj(Bool) = ako je Bool vrati 1 inače vrati 0
dodaj(lista, Bool) = (
bit = broj(Bool),
lista = lista * 10 + bit,
lista = lista * 10 + 8,
vrati lista
)
program(m) = ( # rudimentarni prijenos argumenta preko "komandne linije"
lista = 6, # alokacija nove liste: počinje otvorenom zagradom
b = 0,
dok je b < 4 (
Prvi = Negacija(b < 2), # ekstrakcija bitova od b
Drugi = Neparan(b),
Rezultat = Multiplex(m, Prvi, Drugi),
lista = dodaj(lista, Rezultat), # lista.append(Rezultat)
b = b + 1
),
vrati lista + 1 # zatvaranje liste: zadnji 8 postaje zatvorena zagrada 9
)
'''))
print()
prikaz(tablice_istinitosti, 13)
izvrši(tablice_istinitosti, 3) # poziv iz komandne linije, prijenos m=3
with očekivano(SemantičkaGreška):
PseudokodParser.parsiraj(pseudokod_lexer('f(x)=() f(x)=()'))
# DZ: dodajte određenu petlju: za ime = izraz .. izraz naredba
# DZ*: dodajte late binding, da se modul i program mogu zasebno kompajlirati
<file_sep>"""Lambda-račun: zadatak s kolokvija 28. lipnja 2019.
https://web.math.pmf.unizg.hr/~veky/B/IP.k2.19-06-28.pdf"""
from vepar import *
class Λ(TipoviTokena):
LAMBDA, TOČKA, OTV, ZATV = 'λ.()'
class SLOVO(Token):
def slobodne(t): return {t}
@lexer
def λex(l):
for znak in l:
if znak.isspace(): l.zanemari()
elif znak in {'λ', '^'}:
yield l.token(Λ.LAMBDA)
if (l >> str.isalpha) == 'λ': raise lex.greška('λ nije slovo!')
yield l.token(Λ.SLOVO)
elif znak.isalpha(): yield l.token(Λ.SLOVO)
else: yield l.literal(Λ)
### Beskontekstna gramatika:
# izraz -> član | LAMBDA slova TOČKA izraz
# slova -> SLOVO | SLOVO slova
# član -> faktor | član faktor
# faktor -> OTV izraz ZATV | SLOVO
# Oneliner BKG: start -> (LAMBDA SLOVO+ TOČKA)* (OTV start ZATV | SLOVO)+
class λ(Parser):
def izraz(p) -> 'aps|član':
if p >= Λ.LAMBDA: return p.aps()
return p.član()
def aps(p) -> 'izraz|Apstrakcija':
if p >= Λ.TOČKA: return p.izraz()
return Apstrakcija(p >> Λ.SLOVO, p.aps())
def član(p) -> 'faktor|Aplikacija':
f = p.faktor()
while p > {Λ.OTV, Λ.SLOVO}: f = Aplikacija(f, p.faktor())
return f
def faktor(p) -> 'izraz|SLOVO':
if p >= Λ.OTV:
u_zagradi = p.izraz()
p >> Λ.ZATV
return u_zagradi
else: return p >> Λ.SLOVO
### Apstraktna sintaksna stabla
# izraz: SLOVO:Token
# Apstrakcija: varijabla:SLOVO doseg:izraz
# Aplikacija: funkcija:izraz argument:izraz
class Apstrakcija(AST):
varijabla: 'SLOVO'
doseg: 'izraz'
def slobodne(apstrakcija):
return apstrakcija.doseg.slobodne() - apstrakcija.varijabla.slobodne()
class Aplikacija(AST):
funkcija: 'izraz'
argument: 'izraz'
def slobodne(aplikacija):
return aplikacija.funkcija.slobodne() | aplikacija.argument.slobodne()
def kombinator(l): return not λ(l).slobodne()
prikaz(λ('(^x.xx)(^x.xx)'), 3)
print(λ('^xy.x') == λ('^x.^y.x'))
print(kombinator('(^yx.(x))x'))
with SintaksnaGreška: λ('^x.x^y.y')
with LeksičkaGreška: λ('λ x.x')
<file_sep>"""Pomoćne klase, funkcije i objekti za neke programe u PJ."""
import collections, types, warnings, fractions
class Polinom(collections.Counter):
@classmethod
def konstanta(klasa, broj): return klasa({0: broj})
@classmethod
def x(klasa, eksponent=1): return klasa({eksponent: 1})
def __add__(p, q):
r = Polinom(p)
for exp in q: r[exp] += q[exp]
return r
def __mul__(p, q):
r = Polinom()
for e1, k1 in p.items():
for e2, k2 in q.items(): r[e1 + e2] += k1 * k2
return r
def __neg__(p): return Polinom.konstanta(-1) * p
def __sub__(p, q): return p + -q
def __str__(p):
monomi = []
for e, k in sorted(p.items(), reverse=True):
if not k: continue
č = format(k, '+')
if e:
if abs(k) == 1: č = č.rstrip('1') # samo '+' ili '-'
č += 'x'
if e > 1: č += str(e)
monomi.append(č)
return ''.join(monomi).lstrip('+') or '0'
class StrojSaStogom:
def __init__(self): self.stog = []
def PUSH(self, vrijednost): self.stog.append(vrijednost)
def ADD(self): self.stog.append(self.stog.pop() + self.stog.pop())
def MUL(self): self.stog.append(self.stog.pop() * self.stog.pop())
def POW(self):
eksponent, baza = self.stog.pop(), self.stog.pop()
self.stog.append(baza ** eksponent)
def izvrši(self, instr, *args): getattr(self, instr)(*args)
def __repr__(self): return '[ ' + ' '.join(map(str, self.stog)) + '<'
@property
def rezultat(self):
[jedini_element_stoga] = self.stog
return jedini_element_stoga
class RAMStroj:
def __init__(self, *ulazi):
self.registri = collections.Counter()
for i, ulaz in enumerate(ulazi, 1): self.registri[i] = ulaz
def inc(self, j): self.registri[j] += 1
def dec(self, j):
if self.registri[j]: self.registri[j] -= 1
@property
def rezultat(self): return self.registri[0]
class PristupLog(types.SimpleNamespace):
"""Broji pristupe pojedinom objektu."""
def __init__(self, objekt):
self.objekt = objekt
self.pristup = 0
def pristupi(self): self.pristup += 1
referentne_atomske_mase = dict(H=1.00797, He=4.00260, Li=6.941, Be=9.01218,
B=10.81, C=12.011, N=14.0067, O=15.9994, F=18.998403, Ne=20.179,
Na=22.98977, Mg=24.305, Al=26.98154, Si=28.0855, P=30.97376, S=32.06,
Cl=35.453, Ar=39.948, K=39.0983, Ca=40.08, Sc=44.9559, Ti=47.90,
V=50.9415, Cr=51.996, Mn=54.9380, Fe=55.847, Co=58.9332, Ni=58.70,
Cu=63.546, Zn=65.38, Ga=69.72, Ge=72.59, As=74.9216, Se=78.96, Br=79.904,
Kr=83.80, Rb=85.4678, Sr=87.62, Y=88.9059, Zr=91.22, Nb=92.9064, Mo=95.94,
Tc=98, Ru=101.07, Rh=102.9055, Pd=106.4, Ag=107.868, Cd=112.41, In=114.82,
Sn=118.69, Sb=121.75, Te=127.60, I=126.9045, Xe=131.30, Cs=132.9054,
Ba=137.33, La=138.9055, Ce=140.12, Pr=140.9077, Nd=144.24, Pm=145,
Sm=150.4, Eu=151.96, Gd=157.25, Tb=158.9254, Dy=162.50, Ho=164.9304,
Er=167.26, Tm=168.9342, Yb=173.04, Lu=174.967, Hf=178.49, Ta=180.9479,
W=183.85, Re=186.207, Os=190.2, Ir=192.22, Pt=195.09, Au=196.9665,
Hg=200.59, Tl=204.37, Pb=207.2, Bi=208.9804, Po=209, At=210, Rn=222,
Fr=223, Ra=226.0254, Ac=227.0278, Th=232.0381, Pa=231.0359, U=238.029,
Np=237.0482, Pu=242, Am=243, Cm=247, Bk=247, Cf=251, Es=252, Fm=257,
Md=258, No=250, Lr=260, Rf=261, Db=262, Sg=263, Bh=262, Hs=255, Mt=256,
Ds=269, Rg=272, Cn=285, Nh=286, Fl=289, Mc=290, Lv=293, Ts=294, Og=294)
def Python_eval(izraz):
"""Kao Pythonov eval, ali bez warninga i grešaka koje nisu sintaksne."""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
try: return eval(izraz)
except TypeError: raise SyntaxError
<file_sep># Interpretacija programa
Repozitorij za razne programčiće u Pythonu koji
predstavljaju programsku podršku gradivu kolegija Interpretacija programa.
<file_sep>Sintaksna analiza
=================
Naš program (niz znakova) pretvorili smo u niz tokena --- sada je vrijeme da taj niz obogatimo dodatnom strukturom. Nizovi su linearni, a nama trebaju grafovi u više dimenzija, koji predstavljaju kako se tokeni slažu u semantički smislene cjeline. U ogromnom broju slučajeva ti grafovi su zapravo stabla, i zovu se apstraktna sintaksna stabla (AST).
U nizu tokena ``BROJ'5'`` ``PLUS'+'`` ``BROJ'12'`` dobivenom leksičkom analizom ``5+12``, tokeni nisu ravnopravni: u izvjesnom smislu ovaj ``PLUS`` je "iznad", predstavlja *vrstu* izraza s kojom radimo (zbroj), a ``BROJ``\ evi su samo operandi, koji dolaze u igru tek nakon što znamo o kojoj vrsti izraza se radi. Čak njihov sintaksni identitet može ovisiti o onom što se očekuje na danom mjestu: recimo, u programskom jeziku C, nakon ``if`` i otvorene zagrade dolazi uvjet, a onda nakon zatvorene dolazi naredba. Svaki uvjet je ujedno i naredba, ali ne i obrnuto. Dakle, na najvišoj razini možemo reći "aha, radi se o ``if``-naredbi, ``IF`` ``OTV`` ``uvjet`` ``ZATV`` ``naredba``", a onda ``uvjet`` i ``naredba`` predstavljaju dijelove koji se na nižim razinama popunjavaju tokenima koji se nalaze između odgovarajućih mjesta. Recimo, ``if(i==3)break;`` bi se moglo prikazati kao
.. code-block:: text
Ako: @[Znakovi #1–#13]
uvjet = Jednakost: @[Znakovi #4–#7]
lijevo = IME'i' @[Znak #4]
desno = BROJ'3' @[Znak #7]
onda = BREAK'break' @[Znakovi #9–#13]
Ta ideja razina odnosno slaganja tokena u stabla, ključna je za sintaksnu analizu. Uglavnom ćemo dalje raditi s aritmetičkim izrazima jer su nam bliski, ali sve se može primijeniti na sintaksnu analizu brojnih formalnih jezika.
Beskontekstne gramatike
-----------------------
Formalizam koji nam omogućuje koncizno zapisivanje sintaksne strukture našeg jezika zove se *beskontekstna gramatika* (skraćeno BKG, engleski *context-free grammar*). BKG se sastoji od jednog ili više pravila oblika ``varijabla -> riječ``, gdje je ``riječ`` konačni niz varijabli i tipova tokena. Pravilo predstavlja jednu moguću realizaciju niza tokena koji pripada jeziku određenom tom varijablom (kažemo da varijabla *izvodi* niz tokena). Više pravila za istu varijablu često se piše u skraćenom obliku kao ``varijabla -> riječ1 | riječ2``.
Recimo, ako hoćemo reprezentirati zbrojeve jednog do tri broja, mogli bismo napisati gramatiku s 3 pravila
.. code-block:: text
# zbroj -> BROJ | BROJ PLUS BROJ | BROJ PLUS BROJ PLUS BROJ
--- ali što ako hoćemo proizvoljno mnogo pribrojnika? U tom slučaju možemo koristiti rekurzivno pravilo
.. code-block:: text
# zbroj -> BROJ | BROJ PLUS zbroj
samo, naravno, moramo paziti da uvijek imamo i pravilo koje završava rekurziju.
Što se samog vepra tiče, ne moramo pisati BKG (u Pythonu pravila pišemo u komentare), ali iskustvo pokazuje da je tako puno lakše napisati sintaksni analizator (parser).
Razine prioriteta
-----------------
Pribrojnici u ``zbroj``\ u ne moraju biti ``BROJ``\ evi. Recimo, za ulazni string ``5+8*12`` dobijemo niz tokena ``BROJ'5'`` ``PLUS'+'`` ``BROJ'8'`` ``PUTA'*'`` ``BROJ'12'``, te znamo (na osnovi dogovora o prioritetu operacija) da predstavlja zbroj broja ``5`` i umnoška brojeva ``8`` i ``12``. (Također predstavlja i broj ``101``, ali o tome tek u sljedećoj fazi.) Dakle, cilj nam je proizvesti nešto poput ``Zbroj(lijevo=BROJ'5', desno=Umnožak(lijevo=BROJ'8', desno=BROJ'12'))``, ili, kako to vepar zna "stabloliko" prikazati:
.. code-block:: text
Zbroj: @[Znakovi #1–#6]
prvi = BROJ'5' @[Znak #1]
drugi = Umnožak: @[Znakovi #3–#6]
prvi = BROJ'8' @[Znak #3]
drugi = BROJ'12' @[Znakovi #5–#6]
Da bismo to zapisali u našoj BKG, moramo uvesti još jednu varijablu. U tom kontekstu ona se obično zove "član" (*term*), jer nam se ne da pisati "pribrojnik" zbog duljine.
.. code-block:: text
# izraz -> član | član PLUS izraz
# član -> BROJ | BROJ PUTA član
Vidimo da smo preimenovali i početnu varijablu iz ``zbroj`` u ``izraz``. Vepru nije previše bitno: ako postoji varijabla imena ``start``, od nje kreće sintaksna analiza, a ako ne, kreće od prve varijable.
Sada je jasno kako bismo dodali još razina prioriteta: možete za vježbu dodati potenciranje. No što je sa zagradama? One nam omogućavaju da u član umjesto ``BROJ``\ a utrpamo cijeli izraz, samo ga moramo staviti u zagrade. Dakle
.. code-block:: text
# izraz -> član | član PLUS izraz
# član -> faktor | faktor PUTA član
# faktor -> BROJ | OTV izraz ZATV
Parser
------
Ovo je već dovoljno komplicirana BKG da je zanimljivo vidjeti kako bi izgledao parser za nju. Parser pišemo kao potklasu veprove klase ``Parser``, čije metode (uglavnom) odgovaraju varijablama gramatike. Svaka metoda prima instancu parsera koja se uobičajeno zove ``p``, ali nitko vam ne brani da pišete tradicionalno ``self`` ili kakvo god ime želite.
Parser ima slično sučelje kao lexer, što se tiče "konzumiranja" tokena:
``p.vidi(T.TIP)``, skraćeno ``p > T.TIP``
ako bi sljedeći pročitani token bio tipa ``T.TIP``, vraća ga (ali ne čita), inače vraća ``nenavedeno``
``p.nužno(T.TIP)``, skraćeno ``p >> T.TIP``
čita sljedeći token koji mora biti tipa ``T.TIP``, i vraća ga; inače prijavljuje grešku
``p.slijedi(T.TIP)``, skraćeno ``p >= T.TIP``
čita sljedeći token (i vraća ga) ako i samo ako je tipa ``T.TIP``; inače vraća ``nenavedeno``.
Umjesto ``T.TIP`` može stajati i skup tipova tokena, koji se shvaća kao disjunkcija.
Za razliku od lexera, gdje možemo čitati bilo kakve znakove (npr. s ``next``) pa ih poslije zgurati nekamo kao dio ``lex.sadržaj``\ a, parser mora svaki token *razriješiti* jednom od gornjih metoda; inače ćemo dobiti sintaksnu grešku. Nju možemo i sami prijaviti pomoću ``raise p.greška(poruka)``; kao i za leksičku grešku, poruku ne moramo navesti ako smo zadovoljni veprovom konstrukcijom poruke. Također, grešku ćemo dobiti ako stanemo prije kraja (jer, opet, nismo razriješili sve tokene); možemo zamisliti da nakon svih lexerovih tokena postoji još jedan token tipa ``KRAJ``, koji ne smijemo pročitati (pročitat će ga vepar na kraju parsiranja) ali ga možemo koristiti (operatorom ``>``) za upravljanje sintaksnom analizom: recimo, ``while not p > KRAJ:``.
Objekt ``nenavedeno`` je specijalni singleton koji predstavlja odsustvo tokena u ASTu (iz tehničkih razloga ne koristi se Pythonov ``None``). Važno je da je lažan (dok su svi tokeni istiniti) pa se može koristiti za grananje potpuno jednako kao ``None``.
Primjer
-------
Na primjer, zadnji red u našoj BKG može se kodirati kao ::
def faktor(p):
if p >= T.OTV:
u_zagradi = p.izraz()
p >> T.ZATV
return u_zagradi
else: return p >> T.BROJ
Pomoću "morž-operatora" ``:=`` možemo određene rezultate gornjih metoda iskoristiti za grananje, a ujedno ih i zapamtiti za kasnije vraćanje. Recimo, ako iz nekog razloga želimo zamijeniti grane u upravo napisanoj metodi, imat ćemo ::
def faktor(p):
if broj := p >= T.BROJ: return broj
p >> T.OTV
u_zagradi = p.izraz()
p >> T.ZATV
return u_zagradi
Sve je to lijepo ako sve mogućnosti za neku varijablu počinju različitim tokenima: tako smo odmah znali koje pravilo za faktor trebamo slijediti ovisno o tome jesmo li započeli faktor tokenom tipa ``T.OTV`` ili tokenom tipa ``T.BROJ``. (Ponekad je potrebno gledati više od jednog tokena unaprijed, ali vepar to ne podržava jednostavno; prvenstveno jer vodi do jezika koji su i ljudima teški za razumijevanje. Stručnim rječnikom, veprovo parsiranje je **LL(1)**.) No kako napisati metodu ``izraz``? Imamo dvije mogućnosti, i obje počinju ``član``\ om. U tom slučaju možemo *faktorizirati*, odnosno "izlučiti" ``član`` slijeva. Drugim riječima, možemo sigurno pročitati ``član``, i onda donijeti odluku što dalje ovisno o tome slijedi li ``PLUS`` ili ne. ::
def izraz(p):
prvi = p.član()
if p >= T.PLUS:
drugi = p.izraz()
return Zbroj(prvi, drugi)
else: return prvi
Sasvim je isto za ``član``: napišite sami za vježbu. Sada od te tri metode možemo sklopiti klasu: važno je da metoda ``izraz`` bude prva, kako bi vepar znao da od nje počinje. Alternativno, mogli bismo je preimenovati u ``start``, ali vjerojatno je svejedno dobro da bude prva. ::
class P(Parser):
def izraz(p): ... # prepišite odozgo
def član(p): ... # napišite sami po uzoru na izraz
def faktor(p): ... # prepišite jednu od varijanti odozgo
Da bismo mogli doista pokrenuti parser, trebamo još implementirati ASTove ``Zbroj`` i ``Umnožak``. Zapravo, dovoljno je samo navesti atribute, a metode i anotacije možemo dodati kasnije. ::
class Zbroj(AST):
lijevo: ...
desno: ...
class Umnožak(Zbroj): pass
Trebali bismo svaku klasu koja predstavlja AST naslijediti od klase ``AST``, ali zapravo, s obzirom na to da imaju iste atribute, možemo jednu naslijediti od druge. Sada napokon možemo vidjeti 1D i 2D prikaz našeg stabla:
.. code-block:: text
>>> P('5+8*12')
Zbroj(prvi=BROJ'5', drugi=Umnožak(prvi=BROJ'8', drugi=BROJ'12'))
>>> prikaz(_)
Zbroj: @[Znakovi #1–#6]
prvi = BROJ'5' @[Znak #1]
drugi = Umnožak: @[Znakovi #3–#6]
prvi = BROJ'8' @[Znak #3]
drugi = BROJ'12' @[Znakovi #5–#6]
Iterativno parsiranje
---------------------
Dosad korišteni (rekurzivni) način pisanja parsera je izuzetno jednostavan (samo prepisujemo pravila gramatike u Python), ali ne radi uvijek, a i kada radi, ponekad ne daje intuitivne rezultate.
Lako je vidjeti (isprobajte) da će upravo napisani parser ``2+3+4``
parsirati na isti način kao ``2+(3+4)`` (kažemo da je ``PLUS`` *desno
asociran*), a ne na isti način kao ``(2+3)+4``. U ovom slučaju nije
toliko bitno jer je zbrajanje asocijativna operacija pa će rezultat
biti isti, ali to ne odgovara baš onome kako smo učili u školi (da
je zbrajanje *lijevo asocirano*); i naravno, imali bismo problema pri
uvođenju oduzimanja, jer ``6-3-2`` nije isto što i ``6-(3-2)`` čak
ni po vrijednosti. Dakle, moramo naučiti parsirati i lijevo asocirane
operatore.
Na prvi pogled, vrlo je jednostavno: samo umjesto ``član PLUS izraz`` u drugo pravilo za ``izraz`` napišemo ``izraz PLUS član``. Iako matematički sasvim točno, to nam ne pomaže za pisanje parsera, jer bi rekurzivna paradigma koju smo dosad koristili zahtijevala da unutar metode ``izraz`` prvo pozovemo metodu ``izraz``, što bi naravno dovelo do rušenja zbog beskonačne rekurzije. Taj fenomen se u teoriji parsiranja zove *lijeva rekurzija* (*left recursion*).
Možemo li bez rekurzije parsirati to? Sjetimo se gramatičkih sustava. Po lemi o fiksnoj točki (lijevolinearno), rješenje od ``izraz = izraz PLUS član | član`` je ``izraz = član (PLUS član)*``. Drugim riječima, samo trebamo pročitati ``član``, i onda nakon toga nula ili više puta (u neograničenoj petlji) čitati ``PLUS`` i ``član`` sve dok možemo. ::
def izraz(p):
stablo = p.član()
while p > T.PLUS:
p >> T.PLUS
novi = p.član()
stablo = Zbroj(stablo, novi)
return stablo
Naravno, koristeći ``>=``, cijela petlja se u jednoj liniji može zapisati kao::
while p >= T.PLUS: stablo = Zbroj(stablo, p.član())
Asociranost
-----------
Potrebno je neko vrijeme da se priviknete na takav način pisanja, ali jednom kad uspijete, vidjet ćete da istu tehniku možete primijeniti na mnogo mjesta. Na primjer, iterativno možete parsirati i *višemjesne* (asocijativne) operatore --- gdje ne želite stablo povećavati u dubinu nego u širinu, držeći sve operande kao neposrednu djecu osnovnog operatora (npr. u listi). ::
def izraz(p):
pribrojnici = [p.član()]
while p >= T.PLUS: pribrojnici.append(p.član())
return Zbroj(pribrojnici)
Zadnji napisani kod ima jedan problem: uvijek vraća ``Zbroj``, čak i kad nikakvog zbrajanja nema (onda će lista biti duljine 1). Da to izbjegnete, možete koristiti alternativni konstruktor ASTova, ``return Zbroj.ili_samo(pribrojnici)``. Način na koji to radi je ono što biste očekivali: ako ``A`` ima točno jedan atribut, i njegova vrijednost je lista s jednim elementom ``[w]``, tada ``A.ili_samo([w])`` umjesto ``A([w])`` vraća ``w``.
Jednostavnom zamjenom ``while`` s ``if``, možete implementirati i *neasocirane* operatore, koji uopće nemaju rekurzivna pravila: recimo, da smo imali pravilo ``izraz -> član | član PLUS član``, bili bi dozvoljeni samo zbrojevi jednog ili dva pribrojnika, i za bilo koji veći broj pribrojnika morali bismo eksplicitno koristiti zagrade.
Idealno, svaka metoda parsera bi trebala koristiti samo rekurzivni
ili samo iterativni pristup. Doista, asociranost je svojstvo *razine
prioriteta*, ne pojedinog operatora. Recimo, ako imamo ``+`` i ``-`` na
istoj razini prioriteta kao što je uobičajeno, ne može ``+`` biti desno
a ``-`` lijevo asociran: tada bi ``6-2+3`` bio dvoznačan (mogao bi imati
vrijednost ``1`` ili ``7``), dok ``6+2-3`` ne bi uopće imao značenje.
Drugim riječima, da bismo parsirali ``a$b¤c``, moramo odlučiti "kome ide ``b``". Ako su operatori ``$`` i ``¤`` različitog prioriteta, dohvatit će ga onaj koji je većeg prioriteta. Ali ako su na istoj razini, tada asociranost te razine određuje rezultat: ako je asocirana lijevo, to je ``(a$b)¤c``, a ako je asocirana desno, to je ``a$(b¤c)``.
U istu paradigmu možemo uklopiti i unarne operatore, zamišljajući da su prefiksni operatori "desno asocirani" (rekurzivno parsirani), dok su postfiksni "lijevo asocirani" (iterativno parsirani). I opet, u skladu s upravo navedenim argumentom, ne možemo imati prefiksne i postfiksne operatore na istoj razini prioriteta, jer ne bismo znali kako parsirati ``$b¤`` ("kome ide ``b``").
<file_sep>Leksička analiza
================
Program (izvorni kod) nam je najčešće zadan kao string, dakle niz
znakova Unikoda. Prvo što trebamo učiniti s njime je prepoznati osnovne
podnizove koji predstavljaju podlogu za dalju obradu. Ti podnizovi
tvore *tokene*. Iako može biti beskonačno mnogo tokena (npr. u mnogim
programskim jezicima, svako legalno ime varijable je mogući token),
ključno je da se svi oni razvrstavaju u konačno mnogo *tipova*.
Tipovi tokena su ono što zapravo upravlja kasnijom fazom sintaksne
analize programa. To znači da, idealno, u sintaksnoj analizi ne bi
smjelo biti bitno koji je točno niz znakova na određenom mjestu u
programu (to zovemo *sadržaj* tokena), već samo njegov tip. Odnosno,
ako je program sintaksno ispravan, ostat će takav i ako bilo koji token
u njemu zamijenimo tokenom drugog sadržaja a istog tipa (recimo, broj
``3`` zamijenimo brojem ``58``, ili ime varijable ``xy`` zamijenimo imenom ``t``).
Pored tipa i sadržaja, tokeni prepoznati u izvornom kodu imaju brojne metapodatke koji kazuju gdje token počinje (u kojem retku odnosno stupcu izvornog koda), gdje završava, je li uspješno obrađen od strane sintaksnog analizatora itd. No svaki token mora imati tip i sadržaj, koji su na tokenu ``t`` dostupni kao ``t.tip`` i ``t.sadržaj``.
Tipovi tokena
-------------
Da bismo započeli leksičku analizu, moramo definirati enumeraciju --- klasu koja nabraja sve moguće tipove tokena. U vepru postoji bazna klasa ``TipoviTokena`` nasljeđivanjem od koje dobijemo svu potrebnu funkcionalnost. Evo primjera::
from vepar import *
class T(TipoviTokena):
PLUS = '+'
MINUS, PUTA, KROZ = '-*/'
STRELICA, RAZLIČITO = '->', '!='
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
class I(Token):
literal = 'i'
def vrijednost(t): return 1j
class IME(Token): pass
Upravo navedeni primjer pokazuje nekoliko mogućnosti za definiranje tokena, od jednostavnijih prema složenijima.
* obične inertne tokene koji uvijek (ili gotovo uvijek) imaju isti sadržaj (*literale*) definiramo navođenjem tipa lijevo od ``=`` i sadržaja desno. Dakle, token tipa ``T.PLUS`` ima podrazumijevani sadržaj ``'+'``.
* više literala možemo definirati koristeći Pythonovo ugrađeno raspakiravanje stringova (za jednoznakovne tokene) i slogova (za višeznakovne). Dakle, token tipa ``T.PUTA`` ima podrazumijevani sadržaj ``'*'``, a token tipa ``T.RAZLIČITO`` ima podrazumijevani sadržaj ``'!='``.
* tokene koji nisu inertni (imaju metode koje sudjeluju u semantičkoj analizi) definiramo kao unutarnje klase koje nasljeđuju klasu ``Token``. Tako ``T.BROJ`` nema podrazumijevani sadržaj, ali jednom kad ga prepoznamo i podvrgnemo semantičkoj analizi, moći ćemo iz njegovog sadržaja dobiti njegovu *vrijednost* kao Pythonov ``int``.
* ako želimo neinertni literal (ima metode za semantičku analizu, a također ima konstantni sadržaj), možemo takvoj unutarnjoj klasi dati atribut ``literal``. Tako se za potrebe prepoznavanja ``T.I`` ponaša kao da je definiran s ``I = 'i'``, a u semantičkoj analizi za bilo koji token ``t`` tipa ``T.I`` možemo pozvati ``t.vrijednost()`` i dobiti Pythonov kompleksni broj ``1j`` (imaginarnu jedinicu).
* u suprotnom smjeru, ako želimo inertni token bez podrazumijevanog sadržaja, možemo jednostavno definirati unutarnju klasu s ``pass`` (ili ``...`` ako želimo signalizirati da je situacija privremena i da ćemo kasnije možda dodati neku semantiku za taj tip tokena).
Lexer
-----
*Lexer* je funkcija (*generator* u Pythonu) koja prolazi kroz ulazni
string i redom daje (``yield``) tokene koje u njemu prepoznaje. Vepar zahtijeva da bude dekorirana
s ``@lexer``. Jedini argument joj se obično zove ``lex``, i predstavlja objekt klase ``Tokenizer`` čije metode pomažu pri leksičkoj analizi. Ovdje navodimo samo najčešće načine korištenja ``lex``\ a --- za potpunije informacije pogledajte dokumentaciju (recimo pomoću ``help(Tokenizer)``).
Lexer najčešće počinje linijom poput ``for znak in lex:``, dakle sastoji se od petlje koja u svakom prolazu varijabli ``znak`` pridružuje sljedeći znak ulaza. Nakon toga obično slijedi grananje s obzirom na to koji odnosno kakav znak smo našli. To utvrđujemo najčešće običnom usporedbom poput ``znak == '$'`` ili pozivom metode klase ``str`` poput ``znak.islower()`` (što se može zapisati i kao ``str.islower(znak)``). Često korištene metode ovdje su:
``str.isspace``
Je li znak bjelina, poput razmaka, tabulatora, prelaska u novi red i sličnog.
``str.isalpha``
Je li znak slovo, poput ``A``, ``č``, ``lj``, ili ``是``. Ako želite samo ASCII-slova, provjerite ``znak in string.ascii_letters``, ali najčešće za tim nema potrebe. Trudite se biti inkluzivni!
``str.isdecimal``
Je li znak znamenka u dekadskom sustavu. Opet, za ASCII-znamenke možete pitati ``znak in string.digits``.
Mnoge ``lex``\ ove metode primaju argument imena ``uvjet``. On može biti pojedini znak koji se traži, metoda oblika ``str.is...`` poput ovih upravo navedenih, bilo koja funkcija (možete je i sami napisati, bilo preko ``def`` ili ``lambda``) koja prima znak i vraća ``bool``; ili pak skup takvih, interpretiran kao disjunkcija. Recimo, ``{str.islower, str.isdecimal, '_', '$'}`` znači "ili malo slovo, ili dekadska znamenka, ili donja crta, ili znak dolara".
Metode lexera
-------------
Raznim metodama možemo unutar jednog prolaza pročitati i više znakova. Ovdje su neke.
``lex.zvijezda(uvjet)``, skraćeno ``lex * uvjet``
čita nula ili više znakova (od trenutne pozicije) koji ispunjavaju uvjet
``lex.plus(uvjet)``, skraćeno ``lex + uvjet``
čita jedan ili više znakova (od trenutne pozicije) koji ispunjavaju uvjet; prijavljuje grešku ako takvih nema
``lex.pročitaj_do(uvjet, *, uključivo=True, više_redova=False)``, skraćeno ``lex - uvjet`` ili ``lex <= uvjet``, ili pak ``lex < uvjet`` za ``uključivo=False``
čita znakove dok ne naiđe na prvi znak koji ispunjava uvjet, prijavljuje grešku ako takvog nema; ``uključivo`` kazuje hoće li pročitati i taj znak, a ``više_redova`` hoće li tražiti znak i u kasnijim recima a ne samo u trenutnom
``lex.prirodni_broj(znak, nula=True)``
čita prirodni broj (niz znamenaka bez vodećih nulâ) s početkom ``znak`` (najčešće znamo da dolazi prirodni broj tek kad vidimo prvu njegovu znamenku, ali ne uvijek --- tada možemo za prvi argument staviti ``''``); ``nula`` kazuje dozvoljavamo li čitanje ``0`` kao prirodnog broja
Također, razne metode su nam na raspolaganju ako želimo pročitati samo jedan znak.
``lex.čitaj()``, skraćeno ``next(lex)``
čita i vraća sljedeći znak bez ikakve provjere; na kraju ulaza vraća ``''``
``lex.vidi(uvjet)``, skraćeno ``lex > uvjet``
ispituje ispunjava li znak, koji bi sljedeći bio pročitan, uvjet
``lex.nužno(uvjet)``, skraćeno ``lex >> uvjet``
čita sljedeći znak ako ispunjava uvjet, inače prijavljuje grešku
``lex.slijedi(uvjet)``, skraćeno ``lex >= uvjet``
čita sljedeći znak ako i samo ako ispunjava uvjet; pokrata za ``if lex > uvjet: lex >> uvjet``.
----
Kad zaključimo da smo pročitali dovoljno znakova (što smo pročitali od zadnjeg stvorenog tokena možemo vidjeti u ``lex.sadržaj``), vrijeme je da od njih konstruiramo neki token. Na raspolaganju nam je nekoliko metoda.
``yield lex.token(T.TIP)``
stvara i šalje dalje token tipa ``T.TIP`` i sadržaja ``lex.sadržaj``
``yield lex.literal(T, *, case=True)``
stvara i šalje dalje literal onog tipa koji ima odgovarajući (pročitani) sadržaj; recimo ako je ``lex.sadržaj == '->'``, uz gore definirani ``T``, to bi odaslalo ``Token(T.STRELICA, '->')`` (skraćeno ``T.STRELICA'->'``); ako takvog nema prijavljuje grešku; ``case`` govori traži li sadržaj uzimajući u obzir razliku velikih i malih slova
``yield lex.literal_ili(T.DEFAULT)``
kao ``lex.literal``, osim što ako takvog literala nema, vraća token tipa ``T.DEFAULT``
``lex.zanemari()``
resetira ``lex.sadržaj``; možemo zamisliti da konstruira neki token, i uništi ga umjesto da ga pošalje dalje; česta linija u lexeru je ``if znak.isspace(): lex.zanemari()``, čime zanemarujemo bjeline u izvornom kodu (ali nam i dalje služe za razdvajanje tokena).
Ako želimo sami prijaviti grešku, to možemo učiniti pomoću ``raise lex.greška(poruka)`` (ne moramo navesti poruku ako vepar ima dovoljno podataka za konstrukciju dovoljno dobre poruke).
Primjer
-------
Jednom kad smo napisali lexer i dekorirali ga s ``@lexer``, možemo ga pozvati s nekim stringom da vidimo kako funkcionira i eventualno ispravimo greške. Evo jednog primjera s obzirom na gornji ``T``::
@lexer
def moj(lex):
for znak in lex:
if znak == '-':
if lex >= '>': yield lex.token(T.STRELICA)
else: yield lex.token(T.MINUS)
elif znak == '!':
lex >> '='
yield lex.token(T.RAZLIČITO)
elif znak.isdecimal():
lex.prirodni_broj(znak, nula=False)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
>>> moj('-+->ii!=234/')
.. code-block:: text
Tokenizacija: -+->ii!=234/
Znak #1 : MINUS'-'
Znak #2 : PLUS'+'
Znakovi #3–#4 : STRELICA'->'
Znak #5 : I'i'
Znak #6 : I'i'
Znakovi #7–#8 : RAZLIČITO'!='
Znakovi #9–#11 : BROJ'234'
Znak #12 : KROZ'/'
<file_sep>from pj import *
class BreakException(Exception): pass
class ContinueException(Exception): pass
class ReturnException(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
class Tokeni(enum.Enum):
#separatori
OOTV, OZATV, UOTV, UZATV, VOTV, VZATV, ZAREZ = '()[]{},'
SEP = ';'
#unarni operatori
USKL, TILDA, MINUS, ZVJ = '!~-*'
#binarni operatori
TOCKA, STRELICA, SLASH, MOD, PLUS, LSHIFT, RSHIFT = '.', '->', '/', '%', '+', '<<', '>>'
LESS, LESSEQ, GRTEQ, GRT, EQ, DISEQ, BITAND, BITEXCLOR, BITOR = '<', '<=', '>=', '>', '==', '!=', '&', '^', '|'
LAND, LOR, CONDQ, CONDDOT = '&&', '||', '?', ':'
#operatori pridruzivanja
PLUSEQ, MINUSEQ, ZVJEQ, SLASHEQ, MODEQ, LSHIFTEQ, RSHIFTEQ, ASSIGN = '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '='
ANDEQ, POTEQ, CRTAEQ = '&=', '^=', '|='
#postfiksni operatori
DECR, INCR = '--', '++'
#escape sekvence
NRED, NTAB, NVERTTAB, BACKSP, RET, FFEED, ALERT = '\n', '\t', '\v', '\b', '\r', '\f', '\a'
QUOTE, DBLQUOTE, ESCSLASH = '\'', '\"', '\\'
#komentari
COMMENT, COM_BEGIN, COM_END = '//', '/*', '*/'
# statementi
IF, ELSE, WHILE, FOR, ASSERT, ERROR = 'if', 'else', 'while', 'for', 'assert', 'error'
# misc
ALLOC, ALLOCA = 'alloc', 'alloc_array'
PRINT = 'print'
class IDENTIFIER(Token):
def vrijednost(self, imena, vrijednosti):
try: return vrijednosti[self]
except KeyError: self.nedeklaracija()
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class DECIMALNI(Token):
def vrijednost(self, imena, vrijednosti):
return int(self.sadržaj)
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class HEKSADEKADSKI(Token):
def vrijednost(self, imena, vrijednosti):
return hex(self.sadržaj)
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class CHRLIT(Token):
def vrijednost(self, imena, vrijednosti):
return self.sadržaj[1 : len(self.sadržaj) - 1]
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class STRLIT(Token):
def vrijednost(self, imena, vrijednosti):
return self.sadržaj[1 : len(self.sadržaj) - 1]
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class BOOLEAN(Token):
def vrijednost(self, imena, vrijednosti):
return self.sadržaj == 'true'
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class NULL(Token):
def vrijednost(self, imena, vrijednosti):
return None
def izvrši(self, imena, vrijednosti):
self.vrijednost(imena, vrijednosti)
class BREAK(Token):
def izvrši(self, imena, vrijednosti):
raise BreakException
class CONTINUE(Token):
def izvrši(self, imena, vrijednosti):
raise ContinueException
class RETURN(Token):
def izvrši(self, imena, vrijednosti):
raise ReturnException
class INT(Token):
def vrijednost(self, imena, vrijednosti):
return int
class BOOL(Token):
def vrijednost(self, imena, vrijednosti):
return bool
class CHAR(Token):
def vrijednost(self, imena, vrijednosti):
return str
class STRING(Token):
def vrijednost(self, imena, vrijednosti):
return str
class VOID(Token):
def vrijednost(self, imena, vrijednosti):
return
class POINTER(Token):
def vrijednost(self, imena, vrijednosti):
return
class ARRAY(Token):
def vrijednost(self, imena, vrijednosti):
return
<file_sep>from Parser import *
#Lista programa se leksira, parsira i interpretira
#svaki program mora imati main funkciju, svaka funkcija ima svoj doseg
#definirana je pomoćna print funkcija, može primiti više izraza (npr. print(a, b)),
#a za svaki izraz ispiše njega i njegovu vrijednost
#za provjeru vrijednosti se također može koristiti i assert
if __name__ == '__main__':
programi = [r"""
int piUsingIsPrime(int a); //Deklaracija funkcije
bool isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int factor = 3; factor <= n/factor; factor += 2) {
if (n % factor == 0)
return false;
}
return true;
}
/* Funkcija koja za broj n vraća broj prostih brojeva od 1 do n */
int piUsingIsPrime(int n) {
int primeCount = 0;
for (int i = 2; i <= n; i++)
//if (isPrime(i) == true) //Poziv funkcije isPrime, deklarirane gore
primeCount++;
return primeCount;
}
//Funkcija vraća reverz broja
int reverseInt(int n) {
int reversedNumber = 0;
int remainder;
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
return reversedNumber;
}
int main() {
int a;
int b;
int c;
c += a += 8;
assert(c == 8);
print(reverseInt(257));
assert(reverseInt(257) == 752);
print(piUsingIsPrime(10));
return 2;
}
""", r"""
int x(bool a);
int x(bool aaa); //dozvoljena redeklaracija, nije bitno što su različita imena argumenata
int x(bool a) {}
int x(bool a) {} //greška, nije dozvoljena redefinicija
int main() {
return 0;
}
""", r"""
int main() {
int a;
{
int a = 0; //greška, redeklaracija varijable
}
return 0;
}
""", r"""
int main() {
int a;
{
int c;
}
c = 3; //greška, izvan dosega
return 0;
}
""", r"""
int main() {
int a;
for ( ; a < 4; a++) { //dozvoljeno je izostaviti i prvi i treći argument
if (a == 3) break;
for(int b = 0; b < 3; ) {
if (b % 2 == 0) {
b += 1;
}
else {
print(a, b);
b += 1;
}
}
}
return 0;
}
""", r"""
int main() {
int a; //svakoj je varijabli automatski dodijeljena defaultna vrijednost
int c;
while (a < 5) {
if (a % 2 == 0) {
c = ~c;
}
else c = c << a;
print(c);
a++;
}
//return 'c'; //greška
} //funkcija ne mora imati povratu vrijednost, bitno je da nije pogrešnog tipa
""", r"""
int main() { //prioriteti operatora
//bool b = "b"; greška
bool a = true;
int c = a ? 2 : -1;
print(c);
int d = c == 2 ? 2 + 6*3 : 8;
print(d);
if (c == 2 && d == 20)
string f = "van dosega";
//print(f); //greška
string f;
if (c == 2 && d == 20)
print(f = "u dosegu");
}
""", r"""
int main() {
int[] a ;
int[] b;
int[] c = alloc_array(int, 9);
a = alloc_array(int, 7);
a[0] = 6;
a[5] += 3;
b = a;
b[4] = -7;
b[3]-=1;
c[8] = a[5] *= 4;
print(a);
print(c);
}
"""]
for program in programi:
try:
print("IZVRŠAVANJE PROGRAMA")
tokeni = list(Lekser(program))
#print(*tokeni)
program = C0Parser.parsiraj(tokeni)
#print(program)
program.izvrši()
print("------------")
except Greška as ex:
print('GREŠKA:', ex)
print("------------")
<file_sep>from Lekser import *
from collections import ChainMap
class Program(AST('naredbe')):
def izvrši(self):
tipovi = ChainMap()
vrijednosti = ChainMap()
rezultati = []
for naredba in self.naredbe:
rezultati.append(naredba.izvrši(tipovi, vrijednosti))
for tip in tipovi:
if(tip.sadržaj == 'main' and tipovi[tip].tip.vrijednost(None, None) == int):
tipovi[tip].izvrijedni(tipovi, vrijednosti, [])
return
raise GreškaIzvođenja("nema main funkcije")
class PrintFunkcija(AST('print')):
def izvrši(izraz, imena, vrijednosti):
for p in izraz.print:
if (isinstance(p.vrijednost(imena, vrijednosti), list) and not isinstance(p.vrijednost(imena,vrijednosti)[0],str) and len(p.vrijednost(imena, vrijednosti)) > 1):
print("Veličina polja ", p.vrijednost(imena, vrijednosti)[0], ", elementi: ", ", ".join("{}".format(x[0]) for x in p.vrijednost(imena, vrijednosti)[1:]))
else:
print (p, p.vrijednost(imena, vrijednosti)[0])
class DeklaracijaFunkcije(AST('tip ime varijable')):
def izvrši(izraz, imena, vrijednosti):
#ako već postoji od prije, provjeri slažu li se argumenti
if (izraz.ime in imena):
izraz.provjeri(imena, vrijednosti)
else:
#registriraj sebe u function and variable namespace
imena[izraz.ime] = izraz
#funkcija = Funkcija(izraz.tip, izraz.ime, izraz.varijable, "")
#funkcija.izvrši(imena, vrijednosti)
def izvrijedni(izraz, imena, vrijednosti, argumenti):
raise GreškaIzvođenja("ne može se izvrijedniti samo deklarirana funkcija")
def provjeri(izraz, imena, vrijednosti):
postojeća = imena[izraz.ime]
if (izraz.tip != postojeća.tip):
raise GreškaIzvođenja("nisu kompatibilni povratni tipovi iste funkcije")
if (len(izraz.varijable) != len(postojeća.varijable)):
raise GreškaIzvođenja("različiti broj argumenata za istu funkciju")
for i in range (0, len(izraz.varijable)):
if (izraz.varijable[i].tip != postojeća.varijable[i].tip):
raise GreškaIzvođenja("nekompatibilni tipovi argumenata iste funkcije")
class DefinicijaFunkcije(AST('tip ime varijable tijelo')):
def izvrši(izraz, imena, vrijednosti):
if (izraz.ime in imena and isinstance(imena[izraz.ime], DefinicijaFunkcije)):
raise GreškaIzvođenja("Ne smiju postojati dvije definicije iste funkcije!")
else:
#registriraj sebe u function and variable namespace
imena[izraz.ime] = izraz
izraz.funkcija = Funkcija(izraz.tip, izraz.ime, izraz.varijable, izraz.tijelo)
izraz.funkcija.izvrši(imena, vrijednosti)
def izvrijedni(izraz, imena, vrijednosti, argumenti):
return izraz.funkcija.izvrijedni(imena, vrijednosti, argumenti)
class Funkcija(AST('tip ime varijable tijelo')):
def izvrši(izraz, imena, vrijednosti):
#svaka funkcija ima svoj scope
varijableUFunkciji = ChainMap()
vrijednostiUFunkciji = ChainMap()
#dodaj sve već postojeće funkcije u scope
for key in imena.keys():
varijableUFunkciji[key] = imena[key]
for varijabla in izraz.varijable:
varijabla.izvrši(varijableUFunkciji, vrijednostiUFunkciji)
izraz.varijableF = varijableUFunkciji
izraz.vrijednostiF = vrijednostiUFunkciji
def izvrijedni(izraz, imena, vrijednosti, argumenti):
if (len(argumenti) != len(izraz.varijable)):
raise SemantičkaGreška("neispravan broj argumenata kod poziva funkcije")
for i in range(0, len(argumenti)):
if (not isinstance(argumenti[i], izraz.varijable[i].tip.vrijednost(izraz.varijableF, izraz.vrijednostiF))):
raise SemantičkaGreška("neispravan tip argumenta")
izraz.vrijednostiF[izraz.varijable[i].ime] = argumenti[i]
izraz.varijableF = izraz.varijableF.new_child()
izraz.vrijednostiF = izraz.vrijednostiF.new_child()
for naredba in izraz.tijelo:
try:
naredba.izvrši(izraz.varijableF, izraz.vrijednostiF)
except ReturnException as ex:
#provjera još jel ispravan povratni tip
povratna = ex.message
temp = povratna
if (povratna is None):
if (not izraz.tip ** Tokeni.VOID):
raise SemantičkaGreška("povratna vrijednost funkcije mora biti void")
else: #tip povratne vrijednosti se mora slagati s tipom povratne vrijednosti funkcije
if(isinstance (povratna, list)):
temp = povratna[0]
if (not isinstance( temp, izraz.tip.vrijednost(izraz.varijableF, izraz.vrijednostiF))):
raise SemantičkaGreška("nekompatibilni povratni tip s povratnim tipom funkcije")
izraz.varijableF = izraz.varijableF.parents
izraz.vrijednostiF = izraz.vrijednostiF.parents
return povratna
izraz.varijableF = izraz.varijableF.parents
izraz.vrijednostiF = izraz.vrijednostiF.parents
class IzvrijedniFunkciju(AST('imeFunkcije argumenti')):
def izvrši(izraz, imena, vrijednosti):
#funkcija mora biti deklarirana prije poziva
if (not izraz.imeFunkcije in imena):
raise SemantičkaGreška("poziv nepostojeće funkcije!")
evaluiraniArgumenti = []
for argument in izraz.argumenti:
if (isinstance(argument.vrijednost(imena, vrijednosti), list)):
evaluiraniArgumenti.append(argument.vrijednost(imena, vrijednosti)[0]) #možda još ovo promijeniti
else:
evaluiraniArgumenti.append(argument.vrijednost(imena, vrijednosti))
return imena[izraz.imeFunkcije].izvrijedni(imena, vrijednosti, evaluiraniArgumenti)
def vrijednost(izraz, imena, vrijednosti):
return izraz.izvrši(imena, vrijednosti)
class If(AST('uvjet naredba')):
def izvrši(izraz, imena, vrijednosti):
if (izraz.uvjet.vrijednost(imena, vrijednosti)): #ako je vrijednost ovog true, izvršava se tijelo if-a
izraz.naredba.izvrši(imena, vrijednosti)
if (isinstance(izraz.naredba, Deklaracija)): #pobriši ju iz namespace-a
del vrijednosti[izraz.naredba.varijabla.ime]
del imena[izraz.naredba.varijabla.ime]
class IfElse(AST('uvjet naredbaIf naredbaElse')):
def izvrši(izraz, imena, vrijednosti):
if (izraz.uvjet.vrijednost(imena, vrijednosti)): #ako je vrijednost ovog true, izvršava se tijelo if-a
izraz.naredbaIf.izvrši(imena, vrijednosti)
if (isinstance(izraz.naredbaIf, Deklaracija)): #pobriši ju iz namespace-a
del vrijednosti[izraz.naredbaIf.varijabla.ime]
del imena[izraz.naredbaIf.varijabla.ime]
else:
izraz.naredbaElse.izvrši(imena, vrijednosti)
if (isinstance(izraz.naredbaElse, Deklaracija)): #pobriši ju iz namespace-a
del vrijednosti[izraz.naredbaElse.varijabla.ime]
del imena[izraz.naredbaElse.varijabla.ime]
class Assert(AST('uvjet')):
def izvrši(izraz, imena, vrijednosti):
value = izraz.uvjet.vrijednost(imena, vrijednosti)
if (not isinstance(value, bool)):
raise GreškaIzvođenja("u assert statement mora ići izraz koji ima bool vrijednost")
if (not value):
print("Provjera izraza nije prošla!", izraz)
raise GreškaIzvođenja()
class Error(AST('poruka')):
def izvrši(izraz, imena, vrijednosti):
message = izraz.poruka.vrijednost(imena, vrijednosti)
if (not isinstance(message, str)):
raise GreškaIzvođenja("u error može ići samo string")
print (message)
raise GreškaIzvođenja()
class Blok(AST('blok')):
def izvrši(izraz, imena, vrijednosti):
#uđi jednu razinu niže sa scope-om
novaImena = imena.new_child()
#izvrši svaku od naredbi u bloku
for naredba in izraz.blok:
naredba.izvrši(novaImena, vrijednosti)
#pobriši iz vrijednosti sve parove koji se ne pojavljuju u imenima
for key in novaImena.keys():
if (not key in imena):
del vrijednosti[key]
class While(AST('uvjet tijeloWhile')):
def izvrši(izraz, imena, vrijednosti):
while (izraz.uvjet.vrijednost(imena, vrijednosti)):
try:
izraz.tijeloWhile.izvrši(imena, vrijednosti)
except BreakException: break
except ContinueException: continue
class For(AST('s1 e s2 s3')):
def izvrši(izraz, imena, vrijednosti):
if (not izraz.s1 == ""):
if (isinstance(izraz.s1, Deklaracija)):
ime = izraz.s1.varijabla.ime
izraz.s1.izvrši(imena, vrijednosti)
while (izraz.e.vrijednost(imena, vrijednosti)):
try:
izraz.s3.izvrši(imena, vrijednosti)
if (not izraz.s2 == ""):
if (isinstance(izraz.s2, Deklaracija)):
raise SemantičkaGreška("nije dopušteno deklarirati varijablu")
izraz.s2.izvrši(imena, vrijednosti)
except BreakException: break
except ContinueException:
if (not izraz.s2 == ""):
if (isinstance(izraz.s2, Deklaracija)):
raise SemantičkaGreška("nije dopoušteno deklarirati varijablu")
izraz.s2.izvrši(imena, vrijednosti)
continue
except ReturnException as e:
if (not izraz.s1 == "" and isinstance(izraz.s1, Deklaracija)):
del vrijednosti[ime]
del imena[ime]
raise ReturnException(e.message)
if (not izraz.s1 == "" and isinstance(izraz.s1, Deklaracija)):
del vrijednosti[ime]
del imena[ime]
class Return(AST('povratnaVrijednost')):
def vrijednost(izraz, imena, vrijednosti):
if (izraz.povratnaVrijednost == ""):
return None
else:
try:
return izraz.povratnaVrijednost.vrijednost(imena, vrijednosti)
except SemantičkaGreška: raise GreškaIzvođenja("varijabla nije nigdje inicijalizirana", izraz.povratnaVrijednost)
def izvrši(izraz, imena, vrijednosti):
raise ReturnException(izraz.vrijednost(imena, vrijednosti))
class Varijabla(AST('tip ime')):
def izvrši(izraz, imena, vrijednosti):
#ako već postoji ova varijabla, digni grešku
if (izraz.ime in imena):
izraz.ime.redeklaracija()
imena[izraz.ime] = izraz.tip
#svakoj se varijabli daje defaultna vrijednost
if izraz.tip ** Tokeni.INT:
vrijednosti[izraz.ime] = [0]
elif izraz.tip ** Tokeni.CHAR:
vrijednosti[izraz.ime] = ['\0']
elif izraz.tip ** Tokeni.STRING:
vrijednosti[izraz.ime] = [""]
elif izraz.tip ** Tokeni.BOOL:
vrijednosti[izraz.ime] = [False]
elif izraz.tip ** Tokeni.POINTER:
# N kao NULL
vrijednosti[izraz.ime] = [['N' + izraz.tip.sadržaj]]
elif izraz.tip ** Tokeni.ARRAY:
vrijednosti[izraz.ime] = [0, [izraz.tip.sadržaj]]
def vrijednost(izraz, imena, vrijednosti):
return izraz
class Deklaracija(AST('varijabla vrijedn')):
def izvrši(izraz, imena, vrijednosti):
izraz.varijabla.izvrši(imena, vrijednosti)
#vidi da li se evaluirati izraz na lijevoj strani
izraz.varijabla.ime.vrijednost(imena, vrijednosti)
value = izraz.vrijedn.vrijednost(imena, vrijednosti)
if (isinstance(value, list) and len(value) < 2):
value = value[0]
if izraz.varijabla.tip ** Tokeni.POINTER:
try:
value = value[0]
except: raise GreškaIzvođenja("Neispravna adresa")
# provjeri tip pointera
tip = izraz.varijabla.tip.sadržaj
if(tip == 'int*'):
if(not isinstance(value, int)):
raise GreškaIzvođenja("Nekompatibilan tip pointera, očekujem " + tip)
elif(tip == 'char*'):
if(not isinstance(value, str) or len(value)!=1):
raise GreškaIzvođenja("Nekompatibilan tip pointera, očekujem " + tip)
elif(tip == 'bool*'):
if(not isinstance(value, bool)):
raise GreškaIzvođenja("Nekompatibilan tip pointera, očekujem " + tip)
elif(tip == 'string*'):
if(not isinstance(value, str)):
raise GreškaIzvođenja("Nekompatibilan tip pointera, očekujem " + tip)
else: raise GreškaIzvođenja("Nepoznat tip pointera")
value = [value]
elif izraz.varijabla.tip ** Tokeni.ARRAY:
try:
if(len(value) < 2):
raise GreškaIzvođenja("Neispravno polje")
except: raise GreškaIzvođenja("Neispravno polje")
# provjeri tip pointera
tip = izraz.varijabla.tip.sadržaj
if(tip == 'int[]'):
if(not isinstance(value[1][0], int)):
raise GreškaIzvođenja("Nekompatibilan tip polja, očekujem " + tip)
elif(tip == 'char[]'):
if(not isinstance(value[1][0], str) or len(value)!=1):
raise GreškaIzvođenja("Nekompatibilan tip polja, očekujem " + tip)
elif(tip == 'bool[]'):
if(not isinstance(value[1][0], bool)):
raise GreškaIzvođenja("Nekompatibilan tip polja, očekujem " + tip)
elif(tip == 'string[]'):
if(not isinstance(value[1][0], str)):
raise GreškaIzvođenja("Nekompatibilan tip polja, očekujem " + tip)
else: raise GreškaIzvođenja("Nepoznat tip polja")
elif (not isinstance(value, izraz.varijabla.tip.vrijednost(imena, vrijednosti))):
raise SemantičkaGreška("nekompatibilni tipovi")
if(len(vrijednosti[izraz.varijabla.ime]) < 2):
vrijednosti[izraz.varijabla.ime][0] = value
else: vrijednosti[izraz.varijabla.ime] = value
class Assignment(AST('lijevaStrana desnaStrana operator')):
"""Pridruživanje van inicijalizacije varijabli. Podržava sve operatore pridruživanja"""
def vrijednost(izraz, imena, vrijednosti):
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if isinstance(lijevi, list) and len(lijevi) < 2:
lijevi = lijevi[0]
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
if isinstance(desni, list) and len(desni) < 2:
desni = desni[0]
if(isinstance(izraz.lijevaStrana, Dohvati)):
nešto = izraz.lijevaStrana.odakle.vrijednost(imena, vrijednosti)
if (isinstance(lijevi, int)):
if (not isinstance(desni, int)):
raise SemantičkaGreška("Nekompatibilni tipovi")
else:
left = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator,imena, vrijednosti, True)
return izraz.lijevaStrana.vrijednost(imena, vrijednosti)
elif (isinstance(lijevi, str) and len(lijevi) == 1):
if (not (isinstance(lijevi, str) and len(lijevi) == 1)):
raise SemantičkaGreška("Nekompatibilni tipovi")
else:
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator,imena, vrijednosti, False)
return [izraz.lijevaStrana.vrijednost(imena, vrijednosti)[1:-1]]
elif isinstance(lijevi, bool):
if (not isinstance(desni, bool)):
raise SemantičkaGreška("Nekompatibilni tipovi")
else:
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator,imena, vrijednosti, False)
return bool(izraz.lijevaStrana.vrijednost(imena, vrijednosti)[0])
elif isinstance(lijevi, str):
if (not isinstance(desni, str)):
raise SemantičkaGreška("Nekompatibilni tipovi")
else:
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator,imena, vrijednosti, False)
return izraz.lijevaStrana.vrijednost(imena, vrijednosti)
elif isinstance(lijevi, list) and len(lijevi) >= 2:
# onda je array
if(not isinstance(desni, list) or len(desni) < 2):
raise GreškaIzvođenja("Nekompatibilni tipovi")
else:
# dohvati tip polja
try:
tipl = izraz.lijevaStrana.vrijednost(imena, vrijednosti)[1][0][:-2]
except: tipl = type(izraz.lijevaStrana.vrijednost(imena, vrijednosti)[1][0]).__name__
try:
tipr = izraz.desnaStrana.vrijednost(imena, vrijednosti)[1][0][:-2]
except: tipr= type(izraz.desnaStrana.vrijednost(imena, vrijednosti)[1][0]).__name__
# provjeri da su isti s lijeve i desne strane
if(tipl != tipr):
raise GreškaIzvođenja("Nekompatibilan tip polja, očekujem " + tipl + "[], dobio " + tipr + "[].")
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator, imena, vrijednosti, False)
return izraz.lijevaStrana.vrijednost(imena, vrijednosti)
elif isinstance(lijevi, list):
if (not isinstance(desni, list)):
raise GreškaIzvođenja("Nekompatibilni tipovi")
else:
# provjeri tip pointera
try:
tipl = izraz.lijevaStrana.vrijednost(imena, vrijednosti)[0][0][1:-1]
except: tipl = izraz.lijevaStrana.tip.sadržaj
try:
tipr = izraz.desnaStrana.vrijednost(imena, vrijednosti)[0][0][1:-1]
except: tipr = izraz.desnaStrana.tip.sadržaj
if(tipl != tipr):
raise GreškaIzvođenja("Nekompatibilan tip pointera, očekujem " + tipl + "*, dobio " + tipr + "*.")
Assignment.pridruži(izraz.lijevaStrana, desni, izraz.operator,imena, vrijednosti, False)
return izraz.lijevaStrana.vrijednost(imena, vrijednosti)
else:
raise SemantičkaGreška("Ne znam assignati operande ovog tipa!")
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
def pridruži(lijevo, desno, operator,imena, vrijednosti, je_int):
lijevo_val = lijevo.vrijednost(imena, vrijednosti)
if (isinstance(lijevo_val, list)) :
if(len(lijevo_val) < 2):
lijevo_val = lijevo_val[0]
if operator ** Tokeni.ASSIGN:
lijevo_val = desno
elif je_int:
if operator ** Tokeni.PLUSEQ:
lijevo_val = lijevo_val + desno
elif operator ** Tokeni.MINUSEQ:
lijevo_val = lijevo_val - desno
elif operator ** Tokeni.ZVJEQ:
lijevo_val = lijevo_val * desno
elif operator ** Tokeni.SLASHEQ:
lijevo_val = int(lijevo_val/desno)
elif operator ** Tokeni.MODEQ:
lijevo_val = lijevo_val % desno
elif operator ** Tokeni.LSHIFTEQ:
lijevo_val = lijevo_val << desno
elif operator ** Tokeni.RSHIFTEQ:
lijevo_val = lijevo_val >> desno
elif operator ** Tokeni.ANDEQ:
lijevo_val = lijevo_val & desno
elif operator ** Tokeni.POTEQ:
lijevo_val = lijevo_val ^ desno
elif operator ** Tokeni.CRTAEQ:
lijevo_val = lijevo_val | desno
else:
raise SemantičkaGreška("Ovaj tip ne podržava operator " + operator.sadržaj + ".")
if(isinstance(lijevo.vrijednost(imena, vrijednosti), list) and len(lijevo.vrijednost(imena, vrijednosti)) < 2):
lijevo.vrijednost(imena, vrijednosti)[0] = lijevo_val
elif(isinstance(lijevo.vrijednost(imena, vrijednosti), list)):
lijevo.vrijednost(imena, vrijednosti)[:] = lijevo_val[:]
else: vrijednosti[lijevo] = lijevo_val
class Comparison(AST('lijevaStrana desnaStrana operator')):
def vrijednost(izraz, imena, vrijednosti):
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if (isinstance(lijevi, list)):
lijevi = lijevi[0]
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
if (isinstance(desni, list)):
desni = desni[0]
#dozvoljeni su samo int i char
if ((isinstance(lijevi, int) and isinstance(desni, int))
or (isinstance(lijevi, str) and len(lijevi) == 1 and
isinstance(desni, str) and len(desni) == 1)):
if (type(lijevi) != type(desni)):
raise SemantičkaGreška("neispravno uspoređivanje")
if izraz.operator ** Tokeni.LESS: return lijevi < desni
elif izraz.operator ** Tokeni.LESSEQ: return lijevi <= desni
elif izraz.operator ** Tokeni.GRT: return lijevi > desni
elif izraz.operator ** Tokeni.GRTEQ: return lijevi >= desni
else: assert not 'slučaj'
else:
raise SemantičkaGreška("neispravna usporedba")
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Equality(AST('lijevaStrana desnaStrana operator')):
def vrijednost(izraz, imena, vrijednosti):
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if (isinstance(lijevi, list)):
lijevi = lijevi[0]
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
if (isinstance(desni, list)):
desni = desni[0]
if (type(lijevi) != type(desni)):
raise SemantičkaGreška("neispravno uspoređivanje")
if izraz.operator ** Tokeni.EQ: return lijevi == desni
elif izraz.operator ** Tokeni.DISEQ: return lijevi != desni
else: assert not 'slučaj'
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class BinarnaOperacija(AST('lijevaStrana desnaStrana operacija')):
def vrijednost(izraz, imena, vrijednosti):
try:
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if(isinstance(lijevi, list)):
lijevi = lijevi[0]
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
if(isinstance(desni, list)):
desni = desni[0]
except ValueError:
raise SemantičkaGreška("neispravna binarna operacija")
if izraz.operacija ** Tokeni.PLUS:
rezultat = lijevi + desni
elif izraz.operacija ** Tokeni.MINUS:
rezultat = lijevi - desni
elif izraz.operacija ** Tokeni.ZVJ:
rezultat = lijevi * desni
elif izraz.operacija ** Tokeni.SLASH:
rezultat = int(lijevi / desni)
elif izraz.operacija ** Tokeni.MOD:
rezultat = lijevi % desni
elif izraz.operacija ** Tokeni.LSHIFT:
rezultat = lijevi << desni
elif izraz.operacija ** Tokeni.RSHIFT:
rezultat = lijevi >> desni
return rezultat
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class BitwiseOperacija(AST('lijevaStrana desnaStrana operacija')):
def vrijednost(izraz, imena, vrijednosti):
try:
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
lijevi = lijevi[0]
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
desni = desni[0]
except ValueError:
raise SemantičkaGreška("neispravna bitwise operacija")
if izraz.operacija ** Tokeni.BITAND:
rezultat = lijevi & desni
elif izraz.operacija ** Tokeni.BITOR:
rezultat = lijevi | desni
elif izraz.operacija ** Tokeni.BITEXCLOR:
rezultat = lijevi ^ desni
return rezultat
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class LogičkaOperacija(AST('lijevaStrana desnaStrana operacija')):
def vrijednost(izraz, imena, vrijednosti):
# prvo evaluiraj lijevu stranu, ovisno o njenoj vrijednosti evaluiraj desnu
if(isinstance(izraz.lijevaStrana.vrijednost(imena, vrijednosti), list)):
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)[0]
else: lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if(not isinstance(lijevi, bool)):
raise SemantičkaGreška("neispravna logička operacija")
if izraz.operacija ** Tokeni.LAND:
if (lijevi is False): return False
elif izraz.operacija ** Tokeni.LOR:
if (lijevi is True): return True
if(isinstance(izraz.desnaStrana.vrijednost(imena, vrijednosti), list)):
desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)[0]
else: desni = izraz.desnaStrana.vrijednost(imena, vrijednosti)
if(not isinstance(desni, bool)):
raise SemantičkaGreška("neispravna logička operacija")
if izraz.operacija ** Tokeni.LAND:
rezultat = bool(lijevi and desni)
elif izraz.operacija ** Tokeni.LOR:
rezultat = bool(lijevi or desni)
return rezultat
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class TernarniOperator(AST('lijevaStrana prviUvjet drugiUvjet')):
def vrijednost(izraz, imena, vrijednosti):
if (isinstance(izraz.lijevaStrana.vrijednost(imena, vrijednosti), list)):
lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)[0]
else: lijevi = izraz.lijevaStrana.vrijednost(imena, vrijednosti)
if (isinstance(izraz.prviUvjet.vrijednost(imena, vrijednosti), list)):
prvi = izraz.prviUvjet.vrijednost(imena, vrijednosti)[0]
else: prvi = izraz.prviUvjet.vrijednost(imena, vrijednosti)
if (isinstance(izraz.drugiUvjet.vrijednost(imena, vrijednosti), list)):
drugi = izraz.drugiUvjet.vrijednost(imena, vrijednosti)[0]
else: drugi = izraz.drugiUvjet.vrijednost(imena, vrijednosti)
if(lijevi):
return prvi
else:
return drugi
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Negacija(AST('iza')):
"""Negacija izraza."""
def vrijednost(izraz, imena, vrijednosti):
value = izraz.iza.vrijednost(imena, vrijednosti)[0]
if (not isinstance(value, bool)):
raise SemantičkaGreška("unarna negacija se izvršava samo na boolu")
return [not value]
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Tilda(AST('iza')):
"""Bitwise unary complement"""
def vrijednost(izraz, imena, vrijednosti):
value = izraz.iza.vrijednost(imena, vrijednosti)[0]
if (not isinstance(value, int)):
raise SemantičkaGreška("bitwise unary complement se izvršava samo na intu")
return [~value]
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Minus(AST('iza')):
def vrijednost(izraz, imena, vrijednosti):
if(isinstance(izraz.iza.vrijednost(imena, vrijednosti), list)):
value = izraz.iza.vrijednost(imena, vrijednosti)[0]
else: value = izraz.iza.vrijednost(imena, vrijednosti)
if (not isinstance(value, int)):
raise SemantičkaGreška("unarni minus se izvršava samo na intu")
return [-value]
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Dereferenciraj(AST('iza')):
def vrijednost(izraz, imena, vrijednosti):
argument = izraz.iza.vrijednost(imena, vrijednosti)
if(isinstance(argument, list)):
argument = argument[0]
else: raise SemantičkaGreška("Ne znam dereferencirati nešto što nije pointer!")
if(isinstance(argument, list)):
if len(argument) == 0:
raise SemantičkaGreška("Ne znam dereferencirati NULL!")
return (izraz.iza.vrijednost(imena, vrijednosti))[0]
else: raise SemantičkaGreška("Ne znam dereferencirati nešto što nije pointer!")
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Dohvati(AST('odakle koga')):
def vrijednost(izraz, imena, vrijednosti):
if(int(izraz.koga.sadržaj) >= izraz.odakle.vrijednost(imena, vrijednosti)[0]):
raise GreškaIzvođenja("Indeks izvan granica array-a")
return (izraz.odakle.vrijednost(imena, vrijednosti))[int(izraz.koga.sadržaj)+1]
class Inkrement(AST('broj')):
"""Postfix inkrement, vraća inkrementirani broj"""
def vrijednost(izraz, imena, vrijednosti):
lijevi = izraz.broj.vrijednost(imena, vrijednosti)
vrijednosti[izraz.broj][0] = lijevi[0] + 1
return lijevi[0] + 1
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Dekrement(AST('broj')):
"""Postfix dekrement, vraća dekrementirani broj"""
def vrijednost(izraz, imena, vrijednosti):
lijevi = izraz.broj.vrijednost(imena, vrijednosti)
vrijednosti[izraz.broj][0] = lijevi[0] - 1
return lijevi[0] - 1
def izvrši(izraz, imena, vrijednosti):
izraz.vrijednost(imena, vrijednosti)
class Alociraj(AST('tip')):
def vrijednost(izraz, imena, vrijednosti):
if izraz.tip ** Tokeni.INT:
return [[0]]
elif izraz.tip ** Tokeni.CHAR:
return [['\0']]
elif izraz.tip ** Tokeni.STRING:
return [[""]]
elif izraz.tip ** Tokeni.BOOL:
return [[False]]
elif izraz.tip ** Tokeni.POINTER:
return [[0]]
else: raise SintaksnaGreška("Nepoznat tip!")
class AlocirajArray(AST('tip koliko')):
# nema polja pointera
def vrijednost(izraz, imena, vrijednosti):
temp_list =[int(izraz.koliko.sadržaj)]
if izraz.tip ** Tokeni.INT:
for i in range(int(izraz.koliko.sadržaj)): temp_list.append([0])
elif izraz.tip ** Tokeni.CHAR:
for i in range(int(izraz.koliko.sadržaj)): temp_list.append(['\0'])
elif izraz.tip ** Tokeni.STRING:
for i in range(int(izraz.koliko.sadržaj)): temp_list.append([""])
elif izraz.tip ** Tokeni.BOOL:
for i in range(int(izraz.koliko.sadržaj)): temp_list.append([False])
#elif izraz.tip ** Tokeni.POINTER:
# return [[[0]]*izraz.koliko]
else: raise SintaksnaGreška("Nepoznat tip!")
return temp_list
<file_sep>from util import *
from KA import NedeterminističniKonačniAutomat as NKA
class RegularniIzraz(types.SimpleNamespace, abc.ABC):
"""Svaki RegularniIzraz predstavlja neki regularni jezik,
dobiven pomoću operacija unije, konkatenacije te Kleenejevih operatora
iz inicijalnih jezika (∅, ε, te elementarnih jezika)."""
@abc.abstractmethod
def prazan(self): """Je li jezik jednak ∅?"""
@abc.abstractmethod
def trivijalan(self): """Je li jezik jednak ∅ ili ε?"""
@abc.abstractmethod
def konačan(self): """Je li jezik konačan?"""
@abc.abstractmethod
def korišteni_znakovi(self): """Skup znakova korištenih u izrazu."""
@abc.abstractmethod
def NKA(self, Σ=None): # page 67 lemma 1.55
"""NKA (nad Σ ili korišteni_znakovi) koji prepoznaje regularni jezik."""
@abc.abstractmethod
def enumerator(self): """Generator riječi iz regularnog jezika."""
def __iter__(self):
"""Omogućuje iteriranje kroz regularni jezik, primjerice for-petljom."""
dosad = set()
for riječ in self.enumerator():
if riječ not in dosad: (yield riječ), dosad.add(riječ)
def __mul__(self, other): return Konkatenacija(self, other)
def __or__(self, other): return Unija(self, other)
@property
def p(self): return Plus(self)
@property
def z(self): return Zvijezda(self)
@property
def u(self): return Upitnik(self)
def __pow__(self, n):
"""ri ** n je n-struka konkatenacija regularnog jezika."""
assert n >= 0
return self * self**(n-1) if n else epsilon
def KA(self, Σ=None):
"""Konačni automat koji prepoznaje regularni jezik."""
return self.NKA(Σ).optimizirana_partitivna_konstrukcija().prirodni()
def početak(self, n=10):
"""Lista "prvih" n riječi u regularnom jeziku."""
return list(itertools.islice(self, n))
@property
def abeceda(self):
"""Skup korištenih znakova, pod uvjetom da je neprazan."""
znakovi = self.korišteni_znakovi()
assert znakovi # abeceda ne smije biti prazna
return znakovi
class Inicijalni(RegularniIzraz, abc.ABC):
"""Inicijalni jezik: ∅, ε, ili elementarni jezik."""
def konačan(self): return True
class Prazni(Inicijalni):
"""Prazni jezik: ne sadrži nijednu riječ."""
def __str__(self): return '∅'
def prazan(self): return True
def trivijalan(self): return True
def korišteni_znakovi(self): return set()
def NKA(self, Σ): # page 67 lemma 1.55.3
return NKA.iz_komponenti({1}, Σ, set(), 1, set())
def enumerator(self): yield from set()
class Epsilon(Inicijalni):
"""Jezik ε: sadrži točno jednu riječ, i to praznu."""
def __str__(self): return 'ε'
def prazan(self): return False
def trivijalan(self): return True
def korišteni_znakovi(self): return set()
def NKA(self, Σ): # page 67 lemma 1.55.2
return NKA.iz_komponenti({1}, Σ, set(), 1, {1})
def enumerator(self): yield ε
class Elementarni(Inicijalni):
"""Elementarni(α) je jezik od točno 1 riječi, koja ima točno 1 znak α."""
def __init__(self, znak):
assert isinstance(znak, str) and len(znak) == 1
self.znak = znak
def __str__(self): return self.znak
def prazan(self): return False
def trivijalan(self): return False
def korišteni_znakovi(self): return {self.znak}
def NKA(self, Σ=None): # page 67 lemma 1.55.1
if Σ is None: Σ = self.korišteni_znakovi()
return NKA.iz_komponenti({1, 2}, Σ, {(1, self.znak, 2)}, 1, {2})
def enumerator(self): yield self.znak
prazni, epsilon = Prazni(), Epsilon()
a, b, c = Elementarni('a'), Elementarni('b'), Elementarni('c')
nula, jedan = Elementarni('0'), Elementarni('1')
class Binarni(RegularniIzraz, abc.ABC):
"""Zajednička natklasa za binarne operacije: uniju i konkatenaciju."""
def __init__(self, r1, r2):
assert isinstance(r1, RegularniIzraz) and isinstance(r2, RegularniIzraz)
self.lijevo, self.desno = r1, r2
def korišteni_znakovi(self):
return self.lijevo.korišteni_znakovi() | self.desno.korišteni_znakovi()
def trivijalan(ri):
return ri.prazan() or ri.lijevo.trivijalan() and ri.desno.trivijalan()
class Unija(Binarni):
"""L ∪ M = {w : w ∈ L ∨ w ∈ M}"""
def __str__(self): return f'({self.lijevo}|{self.desno})'
def prazan(self): return self.lijevo.prazan() and self.desno.prazan()
def konačan(self): return self.lijevo.konačan() and self.desno.konačan()
def NKA(self, Σ=None):
if Σ is None: Σ = self.korišteni_znakovi()
return self.lijevo.NKA(Σ).unija(self.desno.NKA(Σ))
def enumerator(self):
if self.lijevo.konačan():
yield from self.lijevo
yield from self.desno
elif self.desno.konačan():
yield from self.desno
yield from self.lijevo
else:
for lijevo, desno in zip(self.lijevo, self.desno):
yield lijevo
yield desno
class Konkatenacija(Binarni):
"""LM = {uv : u ∈ L ∧ v ∈ M}"""
def __str__(self): return f'({self.lijevo}{self.desno})'
def prazan(self): return self.lijevo.prazan() or self.desno.prazan()
def konačan(self):
if self.prazan(): return True
return self.lijevo.konačan() and self.desno.konačan()
def NKA(self, Σ=None):
if Σ is None: Σ = self.korišteni_znakovi()
return self.lijevo.NKA(Σ).konkatenacija(self.desno.NKA(Σ))
def enumerator(self):
if self.desno.konačan():
for lijevo in self.lijevo:
for desno in self.desno: yield lijevo + desno
elif self.lijevo.konačan():
for desno in self.desno:
for lijevo in self.lijevo: yield lijevo + desno
else: # enumeracija po sporednim dijagonalama
dosad = []
for lijevo in self.lijevo:
dosad.append(lijevo)
for lijevo, desno in zip(reversed(dosad), self.desno):
yield lijevo + desno
class Zvijezda(RegularniIzraz):
"""L* := ε ∪ L ∪ LL ∪ LLL ∪ ...."""
def __init__(self, ri):
assert isinstance(ri, RegularniIzraz)
self.ispod = ri
def __str__(self): return f'{self.ispod}*'
def prazan(self): return False
def trivijalan(self): return self.ispod.trivijalan()
def konačan(self): return self.trivijalan()
def korišteni_znakovi(self): return self.ispod.korišteni_znakovi()
def NKA(self, Σ=None):
if Σ is None: Σ = self.korišteni_znakovi()
return self.ispod.NKA(Σ).zvijezda()
def enumerator(self): yield from Upitnik(Plus(self.ispod))
def Plus(ri): return Konkatenacija(Zvijezda(ri), ri)
def Upitnik(ri): return Unija(epsilon, ri)
<file_sep>"""Primjer kako python (interpreter) obrađuje Python (programski jezik)."""
import tokenize, io, keyword, ast, dis, warnings, textwrap
def tokeni(string):
lex = tokenize.tokenize(io.BytesIO(string.encode('utf8')).readline)
for tok in list(lex)[1:-1]:
if keyword.iskeyword(tok.string): tip = tok.string.upper()
else: tip = tokenize.tok_name[tok.exact_type]
print('\t' + tip + repr(tok.string))
def stablo_parsiranja(string):
warnings.simplefilter('ignore')
try: import parser
except ImportError: return print(textwrap.dedent('''\
U verziji 3.10 Python je prešao na novi parser, koji više nije
zasnovan na beskontekstnoj gramatici (i nije dostupan kroz
Pythonovu standardnu biblioteku). To je u skladu s onim što smo
rekli na nastavi, da sve više parsera producira direktno AST umjesto
stabala parsiranja. Više o razlozima možete pročitati u PEP617.
Ako ipak želite vidjeti stablo parsiranja za gornji komad koda,
pokrenite ovaj program pod Pythonom 3.9 ili nižim.'''))
def ispis(t, razina, nastavak=False):
if not nastavak: print(end=' '*2*razina)
if len(t) == 2:
if isinstance(t[~0], str):
tip, sadržaj = t
if keyword.iskeyword(sadržaj): tip = sadržaj.upper()
else: tip = tokenize.tok_name[tip]
print(tip + repr(sadržaj))
else:
print(t[0] - 256, end='>')
ispis(t[1], razina, True)
else:
print(t[0] - 256)
for podstablo in t[1:]:
ispis(podstablo, razina + 1)
ispis(parser.suite(string).tolist(), 0)
def apstablo(string):
try: print(ast.dump(ast.parse(string), indent=4))
except TypeError:
print(ast.dump(ast.parse(string)))
print('Za ljepši ispis pokrenite ovo pod Pythonom 3.9 ili kasnijim.')
def bytecode(string): dis.dis(string)
def izvršavanje(string): exec(string)
def source(string): print(string)
if __name__ == '__main__':
primjer = textwrap.dedent('''\
for x in 2, 3:
print(x)
''') # slobodno eksperimentirajte!
for funkcija in source, tokeni, stablo_parsiranja, \
apstablo, bytecode, izvršavanje:
print(funkcija.__name__.join('[]').center(75, '-'))
print()
funkcija(primjer)
print()
# Module:
# body = [...]:
# For:
# target = Name(id='x', ctx=Store())
# iter = Tuple(elts=[Num(n=2), Num(n=3)], ctx=Load())
# body = [...]
# Expr:
# value = Call:
# func = Name(id='print', ctx=Load())
# args = [Name(id='x', ctx=Load())]
# keywords = []
# orelse = []
<file_sep># Interpretacija
Druga zadaća iz interpretacije programa
## Što je trebalo napraviti...
Trebalo je implemetnirati (što više) funkcionalnosti coin-a, interpretera za jezik c0.
## Što nismo implemetnirali...
struct, typedef, operator . , operator ->, #use
## Što jesmo implementirali...
Sve ostalo. Testni primjeri su u main.py i moguće je dodati nove appendanjem novog stringa u listu programi.
<NAME> i <NAME>
<file_sep>import subprocess, pathlib, re, runpy, sys, operator, contextlib, io, \
difflib, time, webbrowser, argparse, tempfile, os, filecmp
t00 = time.perf_counter()
službeni = pathlib.Path('out_test.txt')
argv = argparse.ArgumentParser()
argv.add_argument('--replace', action='store_true')
argv = argv.parse_args()
izlaz = io.StringIO()
datoteke = sorted((datoteka for datoteka in pathlib.Path().glob('*/*.py')
if re.match('\d\d_', datoteka.stem)), key=operator.attrgetter('stem'))
for datoteka in datoteke:
t0 = time.perf_counter()
print(datoteka.stem.center(78, '#'), flush=True, file=izlaz)
rezultat = subprocess.run([sys.executable, datoteka],
capture_output=True, check=True, text=True, input='2\n')
print(rezultat.stdout, end='', file=izlaz)
print(format(time.perf_counter() - t0, '.3f'), datoteka)
print(f'Ukupno {time.perf_counter()-t00:.3f}s')
if argv.replace: službeni.write_text(izlaz.getvalue())
else:
fromlines = službeni.read_text().splitlines()
tolines = izlaz.getvalue().splitlines()
if fromlines == tolines: print('Nema razlike.')
else:
diff = difflib.HtmlDiff(wrapcolumn=79)
diff = diff.make_file(fromlines, tolines, context=True)
with tempfile.NamedTemporaryFile(
mode='w', prefix='_vepar_', delete=False) as tmp:
print(diff, file=tmp)
webbrowser.open(tmp.name, 2)
time.sleep(6)
pathlib.Path(tmp.name).unlink()
<file_sep>"""Računanje polinomima u jednoj varijabli s cjelobrojnim koeficijentima.
Aritmetika cijelih brojeva je specijalni slučaj, kad se x ne pojavljuje.
Dozvoljeno je ispuštanje zvjezdice za množenje u slučajevima poput
23x, xxxx, 2(3+1), (x+1)x, (x)(7) -- ali ne x3: to znači potenciranje!
Također, zabranjeni su izrazi poput (x+2)3, te (već leksički) 2 3.
Semantički analizator je napravljen u obliku prevoditelja (kompajlera) u
klasu Polinom, čiji objekti podržavaju operacije prstena i lijep ispis."""
from vepar import *
from backend import Polinom
class T(TipoviTokena):
PLUS, MINUS, PUTA, OTVORENA, ZATVORENA = '+-*()'
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
def prevedi(t): return Polinom.konstanta(t.vrijednost())
class X(Token):
literal = 'x'
def prevedi(t): return Polinom.x()
@lexer
def az(lex):
for znak in lex:
if znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
### Beskontekstna gramatika:
# izraz -> član | izraz PLUS član | izraz MINUS član
# član -> faktor | član PUTA faktor | član faktorxz
# faktor -> MINUS faktor | BROJ | faktorxz
# faktorxz -> X | X BROJ | OTVORENA izraz ZATVORENA
class P(Parser):
def izraz(p) -> 'Zbroj|član':
t = p.član()
while ...:
if p >= T.PLUS: t = Zbroj(t, p.član())
elif p >= T.MINUS: t = Zbroj(t, Suprotan(p.član()))
else: return t
def član(p) -> 'Umnožak|faktor':
trenutni = p.faktor()
while p >= T.PUTA or p > {T.X, T.OTVORENA}:
trenutni = Umnožak(trenutni, p.faktor())
return trenutni
def faktor(p) -> 'Suprotan|BROJ|Xna|X|izraz':
if p >= T.MINUS: return Suprotan(p.faktor())
elif broj := p >= T.BROJ: return broj
elif x := p >= T.X:
if eksponent := p >= T.BROJ: return Xna(eksponent)
else: return x
elif p >> T.OTVORENA:
u_zagradi = p.izraz()
p >> T.ZATVORENA
return u_zagradi
### Apstraktna sintaksna stabla:
# izraz: BROJ: Token
# X: Token
# Zbroj: lijevo:izraz desno:izraz
# Umnožak: lijevo:izraz desno:izraz
# Suprotan: od:izraz
# Xna: eksponent:BROJ
class Zbroj(AST):
lijevo: 'izraz'
desno: 'izraz'
def prevedi(zbroj): return zbroj.lijevo.prevedi() + zbroj.desno.prevedi()
class Umnožak(AST):
lijevo: 'izraz'
desno: 'izraz'
def prevedi(umnožak):
return umnožak.lijevo.prevedi() * umnožak.desno.prevedi()
class Suprotan(AST):
od: 'izraz'
def prevedi(self): return -self.od.prevedi()
class Xna(AST):
eksponent: 'BROJ'
def prevedi(self): return Polinom.x(self.eksponent.vrijednost())
def izračunaj(zadatak): print(zadatak, '=', P(zadatak).prevedi())
izračunaj('(5+2*8-3)(3-1)-(-4+2*19)')
izračunaj('x-2+5x-(7x-5)')
izračunaj('(((x-2)x+4)x-8)x+7')
izračunaj('xx-2x+3')
izračunaj('(x+1)' * 7)
izračunaj('-'.join(['(x2-2x3-(7x+5))'] * 2))
izračunaj('x0+x0')
with SintaksnaGreška: izračunaj('(x)x+(x)3')
with LeksičkaGreška: izračunaj('x x')
<file_sep>"""Jednostavni SQL parser, samo za nizove CREATE i SELECT naredbi.
Ovaj fragment SQLa je zapravo regularan -- nigdje nema ugnježđivanja!
Semantički analizator u obliku name resolvera:
provjerava jesu li svi selektirani stupci prisutni, te broji pristupe.
Na dnu je lista ideja za dalji razvoj.
"""
from pj import *
from backend import PristupLog
import pprint
class SQL(enum.Enum):
class IME(Token): pass
class BROJ(Token): pass
SELECT, FROM, CREATE, TABLE = 'select', 'from', 'create', 'table'
OTVORENA, ZATVORENA, ZVJEZDICA, ZAREZ, TOČKAZAREZ = '()*,;'
def sql_lex(kôd):
lex = Tokenizer(kôd)
for znak in iter(lex.čitaj, ''):
if znak.isspace(): lex.zanemari()
elif znak.isdigit():
lex.zvijezda(str.isdigit)
yield lex.token(SQL.BROJ)
elif znak == '-':
lex.pročitaj('-')
lex.pročitaj_do('\n')
lex.zanemari()
elif znak.isalpha():
lex.zvijezda(str.isalnum)
yield lex.literal(SQL.IME, case=False)
else: yield lex.literal(SQL)
### Beskontekstna gramatika:
# start -> naredba | naredba start
# naredba -> ( select | create ) TOČKAZAREZ
# select -> SELECT ( ZVJEZDICA | stupci ) FROM IME
# stupci -> IME ZAREZ stupci | IME
# create -> CREATE TABLE IME OTVORENA spec_stupci ZATVORENA
# spec_stupci -> spec_stupac ZAREZ spec_stupci | spec_stupac
# spec_stupac -> IME IME (OTVORENA BROJ ZATVORENA)?
### Apstraktna sintaksna stabla:
# Skripta: naredbe - niz SQL naredbi, svaka završava znakom ';'
# Create: tablica, specifikacije - CREATE TABLE naredba
# Select: tablica, stupci - SELECT naredba; stupci == nenavedeno za SELECT *
# Stupac: ime, tip, veličina - specifikacija stupca u tablici (za Create)
class SQLParser(Parser):
def select(self):
if self >> SQL.ZVJEZDICA: stupci = nenavedeno
elif self >> SQL.IME:
stupci = [self.zadnji]
while self >> SQL.ZAREZ: stupci.append(self.pročitaj(SQL.IME))
else: raise self.greška()
self.pročitaj(SQL.FROM)
return Select(self.pročitaj(SQL.IME), stupci)
def spec_stupac(self):
ime, tip = self.pročitaj(SQL.IME), self.pročitaj(SQL.IME)
if self >> SQL.OTVORENA:
veličina = self.pročitaj(SQL.BROJ)
self.pročitaj(SQL.ZATVORENA)
else: veličina = nenavedeno
return Stupac(ime, tip, veličina)
def create(self):
self.pročitaj(SQL.TABLE)
tablica = self.pročitaj(SQL.IME)
self.pročitaj(SQL.OTVORENA)
stupci = [self.spec_stupac()]
while self >> SQL.ZAREZ: stupci.append(self.spec_stupac())
self.pročitaj(SQL.ZATVORENA)
return Create(tablica, stupci)
def naredba(self):
if self >> SQL.SELECT: rezultat = self.select()
elif self >> SQL.CREATE: rezultat = self.create()
else: raise self.greška()
self.pročitaj(SQL.TOČKAZAREZ)
return rezultat
def start(self):
naredbe = [self.naredba()]
while not self >> E.KRAJ: naredbe.append(self.naredba())
return Skripta(naredbe)
class Skripta(AST('naredbe')):
"""Niz SQL naredbi, svaka završava znakom ';'."""
def razriješi(self):
imena = {}
for naredba in self.naredbe: naredba.razriješi(imena)
return imena
class Create(AST('tablica specifikacije')):
"""CREATE TABLE naredba."""
def razriješi(self, imena):
tb = imena[self.tablica.sadržaj] = {}
for stupac in self.specifikacije:
tb[stupac.ime.sadržaj] = PristupLog(stupac.tip)
class Select(AST('tablica stupci')):
"""SELECT naredba."""
def razriješi(self, imena):
tn = self.tablica.sadržaj
if tn not in imena: raise self.tablica.nedeklaracija('nema tablice')
tb = imena[tn]
if self.stupci is nenavedeno:
for sl in tb.values(): sl.pristupi()
else:
for st in self.stupci:
sn = st.sadržaj
if sn not in tb:
raise st.nedeklaracija('stupca nema u {}'.format(tn))
tb[sn].pristupi()
class Stupac(AST('ime tip veličina')): """Specifikacija stupca u tablici."""
if __name__ == '__main__':
skripta = SQLParser.parsiraj(sql_lex('''\
CREATE TABLE Persons
(
PersonID int,
Name varchar(255), -- neki stupci imaju zadanu veličinu
Birthday date, -- a neki nemaju...
Married bool,
City varchar(9) -- zadnji nema zarez!
); -- Sada krenimo nešto selektirati
SELECT Name, City FROM Persons;
SELECT * FROM Persons;
CREATE TABLE Trivial (ID void(0)); -- još jedna tablica
SELECT*FROM Trivial; -- između simbola i riječi ne mora ići razmak
SELECT Name, Married FROM Persons;
SELECT Name from Persons;
'''))
prikaz(skripta, 4)
# Skripta(naredbe=[
# Create(tablica=IME'Persons', specifikacije=[
# Stupac(ime=IME'PersonID', tip=IME'int', veličina=nenavedeno),
# Stupac(ime=IME'Name', tip=IME'varchar', veličina=BROJ'255'),
# Stupac(ime=IME'Birthday', tip=IME'date', veličina=nenavedeno),
# Stupac(ime=IME'Married', tip=IME'bool', veličina=nenavedeno),
# Stupac(ime=IME'City', tip=IME'varchar', veličina=BROJ'9')
# ]),
# Select(tablica=IME'Persons', stupci=[IME'Name', IME'City']),
# Select(tablica=IME'Persons', stupci=nenavedeno),
# Create(tablica=IME'Trivial', specifikacije=
# [Stupac(ime=IME'ID', tip=IME'void', veličina=BROJ'0')]),
# Select(tablica=IME'Trivial', stupci=nenavedeno),
# Select(tablica=IME'Persons', stupci=[IME'Name', IME'Married']),
# Select(tablica=IME'Persons', stupci=[IME'Name'])
# ])
#raise SystemExit
pprint.pprint(skripta.razriješi())
# ideje za dalji razvoj:
# PristupLog.pristup umjesto samog broja može biti lista brojeva linija \
# skripte u kojima počinju SELECT naredbe koje pristupaju pojedinom stupcu
# za_indeks(skripta): lista natprosječno dohvaćivanih tablica/stupaca
# optimizacija: brisanje iz CREATE stupaca kojima nismo uopće pristupili
# implementirati INSERT INTO, da možemo doista nešto i raditi s podacima
# povratni tip za SELECT (npr. (varchar(255), bool) za predzadnji)
# interaktivni način rada (online - naredbu po naredbu analizirati)
<file_sep>"""Kulinarski recepti: po uzoru na kolokvij 6. srpnja 2021.
https://web.math.pmf.unizg.hr/~veky/B/IP.k2.21-07-06.pdf"""
from vepar import *
class T(TipoviTokena):
IMA, G, SASTOJCI, PRIPREMA = '--ima--', 'g', '-SASTOJCI-', '-PRIPREMA-'
class SASTOJCIOSOBE(Token):
def vrijednost(self):
return int(''.join(filter(str.isdigit, self.sadržaj)))
class BROJ(Token):
def vrijednost(self):
return int(self.sadržaj)
class RIJEČ(Token): pass
class KOMENTAR(Token): pass
@lexer
def rec(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == '-':
if lex >= '-':
lex.pročitaj_do('-', više_redova=True)
lex >> '-'
yield lex.literal_ili(T.KOMENTAR)
elif lex >= 'S':
lex - 'I'
if lex.sadržaj == '-SASTOJCI':
if lex >= '-': yield lex.token(T.SASTOJCI)
else:
for znak in ' ZA ': lex >> znak
lex.prirodni_broj('', nula = False)
lex >> '-'
yield lex.token(T.SASTOJCIOSOBE)
else: raise lex.greška('nepostojeće zaglavlje')
else:
lex - '-'
yield lex.literal(T)
elif znak.isdigit():
lex.prirodni_broj(znak, nula = False)
yield lex.token(T.BROJ)
elif znak.isalpha():
lex * str.isalpha
if lex.sadržaj == 'ml' : yield lex.token(T.G)
else: yield lex.literal_ili(T.RIJEČ)
else: raise lex.greška()
### Beskontekstna gramatika:
# recept -> KOMENTAR (SASTOJCI | SASTOJCIOSOBE) podrecept
# podrecept -> sastojak+ priprema
# sastojak -> (BROJ G)? RIJEČ (SASTOJCI podrecept | IMA? KOMENTAR?)?
# priprema -> PRIPREMA RIJEČ BROJ RIJEČ KOMENTAR?
class P(Parser):
def recept(self): return Recept(self >> T.KOMENTAR,
self >> {T.SASTOJCI, T.SASTOJCIOSOBE},
self.sastojci(), self.priprema())
def sastojci(self):
sastojci = []
while self > {T.BROJ, T.RIJEČ}: sastojci.append(self.sastojak())
return sastojci
def sastojak(self):
if količina := self >= T.BROJ: mjera = self >> T.G
ime = self >> T.RIJEČ
if self >= T.SASTOJCI: return Podrecept(količina, mjera, ime,
self.sastojci(), self.priprema())
elif ima := self >= T.IMA: self >= T.KOMENTAR
elif self >= T.KOMENTAR: pass
if količina: return Sastojak(količina, mjera, ime, ima)
else: return SastojakZanemariveMase(ime, ima)
def priprema(self):
self >> T.PRIPREMA, self >> T.RIJEČ
minute = self >> T.BROJ
self >> T.RIJEČ, self >= T.KOMENTAR
return minute
### AST
# Recept: naslov:KOMENTAR broj_osoba:SASTOJCIOSOBE
# sastojci:[sastojak] minute:BROJ
# sastojak: Podrecept: količina:BROJ? mjera:G? ime:RIJEČ
# sastojci:[sastojak] minute:BROJ
# Sastojak: količina:BROJ? mjera:G? ime:RIJEČ ima:IMA?
# SastojakZanemariveMase: ime:RIJEČ ima:IMA?
class Recept(AST):
naslov: 'KOMENTAR'
broj_osoba: 'SASTOJCIOSOBE'
sastojci: 'sastojak+'
minute: 'BROJ'
def provjera(self): return all(s.provjera() for s in self.sastojci)
def popis(self):
rt.popis=Memorija()
for s in self.sastojci: s.popis(self.broj_osoba.vrijednost())
return rt.popis
def vrijeme(self): return sum((s.vrijeme() for s in self.sastojci),
self.minute.vrijednost())
class Podrecept(AST):
količina: 'BROJ?'
mjera: 'G?'
ime: 'RIJEČ'
sastojci: 'sastojak+'
minute: 'BROJ'
def provjera(self):
return self.količina.vrijednost() == sum(s.masa() for s in self.sastojci)
def popis(self, broj_osoba):
for s in self.sastojci: s.popis(broj_osoba)
vrijeme = Recept.vrijeme
class Sastojak(AST):
količina: 'BROJ?'
mjera: 'G?'
ime: 'RIJEČ'
ima: 'IMA?'
def masa(self):
return self.količina.vrijednost()
def popis(self, broj_osoba):
if not self.ima:
if self.ime not in rt.popis: rt.popis[self.ime] = 0
rt.popis[self.ime] += self.masa() / broj_osoba
def provjera(self): return True
def vrijeme(self): return 0
class SastojakZanemariveMase(AST):
ime: 'RIJEČ'
ima: 'IMA?'
def masa(self): return 0
def popis(self, broj_osoba):
if not self.ima: rt.popis[self.ime] = ''
def provjera(self): return True
def vrijeme(self): return 0
ulaz = '''
--NAAAJBOLJA PIZZA NA SVIJETU!!!1--
-SASTOJCI ZA 2-
503 g tijesto
-SASTOJCI-
300 g brašno--ima--
200 ml voda --pukla cijev pred
zgradom, kupiti--
kvasac--ima-- sol --ima--3 g šećer
-PRIPREMA-
odležati 60 minuta --hmmm... ja ili tijesto?--
405 g umak
-SASTOJCI-
400 g pelati sol 5 g šećer
bosiljak --ima----barem se nadam da je to u fridžu bosiljak--
-PRIPREMA-
krčkati 15 minuta
300 g sir --ima--
-PRIPREMA-
peći 10 minuta
'''
rec(ulaz)
prikaz(P(ulaz))
if P(ulaz).provjera(): print('OK', end=' --- ')
else: print('NOTOK', end=' --- ')
print(P(ulaz).vrijeme(), end=' --- ')
print(', '.join(f'{ime.sadržaj} {količina}'.rstrip()
for ime, količina in P(ulaz).popis()))
<file_sep>"""Renderer za XHTML dokumente koji sadrže samo liste.
Kolokvij 2. veljače 2015. (Puljić)"""
from vepar import *
class T(TipoviTokena):
HTML, HEAD, BODY = '<html>', '<head>', '<body>'
ZHTML, ZHEAD, ZBODY = '</html>', '</head>', '</body>'
OL, UL, LI = '<ol>', '<ul>', '<li>'
ZOL, ZUL, ZLI = '</ol>', '</ul>', '</li>'
class TEKST(Token):
def render(t): print(t.sadržaj, end=' ')
@lexer
def html(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == '<':
lex - '>'
try: token = lex.literal(T, case=False)
except LeksičkaGreška: lex.zanemari()
else: yield token
else:
lex < {'', '<', str.isspace}
yield lex.token(T.TEKST)
### Beskontekstna gramatika
# dokument -> HTML HEAD TEKST+ ZHEAD BODY element* ZBODY ZHTML
# element -> TEKST | OL stavka+ ZOL | UL stavka+ ZUL
# stavka -> LI element ZLI
class P(Parser):
def start(p) -> 'Dokument':
p >> T.HTML, p >> T.HEAD
zaglavlje = p.tekst()
p >> T.ZHEAD, p >> T.BODY
tijelo = []
while not p >= T.ZBODY: tijelo.append(p.element())
p >> T.ZHTML
return Dokument(zaglavlje, tijelo)
def tekst(p) -> 'Tekst':
dijelovi = [p >> T.TEKST]
while tekst := p >= T.TEKST: dijelovi.append(tekst)
return Tekst(dijelovi)
def element(p) -> 'Lista|tekst':
if vrsta := p >= {T.OL, T.UL}:
stavke = [p.stavka()]
while p > T.LI: stavke.append(p.stavka())
if vrsta ^ T.OL: p >> T.ZOL
elif vrsta ^ T.UL: p >> T.ZUL
else: assert False, 'nepoznata vrsta liste'
return Lista(vrsta, stavke)
else: return p.tekst()
def stavka(p) -> 'element':
p >> T.LI
rezultat = p.element()
p >> T.ZLI
return rezultat
### Apstraktna sintaksna stabla
# Dokument: zaglavlje:Tekst tijelo:[element]
# element: Lista: vrsta:OL|UL stavke:[element]
# Tekst: dijelovi:[TEKST]
class Dokument(AST):
zaglavlje: 'Tekst'
tijelo: 'element*'
def render(dokument):
for element in dokument.tijelo: element.render([''])
print()
class Lista(AST):
vrsta: 'OL|UL'
stavke: 'element*'
def render(lista, prefiks):
prethodni, zadnji = prefiks[:-1], prefiks[-1]
for i, stavka in enumerate(lista.stavke, 1):
if i > 1 and zadnji.endswith('\t'): zadnji = '\t'
if lista.vrsta ^ T.OL: marker = f'{i}.'
elif lista.vrsta ^ T.UL: marker = '*#@o-.,_ '[len(prethodni)] + ' '
stavka.render(prethodni + [zadnji, f'{marker:>7}\t'])
class Tekst(AST):
dijelovi: 'TEKST*'
def render(tekst, prefiks):
print('\n', *prefiks, sep='', end='')
for dio in tekst.dijelovi: dio.render()
r = P('''
<html>
<head>
bla bla
</head>
<body>
&hmm;
hm hm
<ol>
<li>Ovo je <a?> prvi item.</li>
<li>A ovo je drugi.</li>
<li> Ovo je --- ne bi čovjek vjerovao --- treći.</li>
<li>
<ul>
<li>
<ol>
<li>Trostruka dubina!</li>
</ol>
</li>
<li>Dvostruka!</li>
</ul>
</li>
<li>nastavak...</li>
</ol>
I još malo<ul><li>uvučeno</li></ul>
</body>
</html>
''')
n = P('''
<html>
<head>_</head>
<body><ol>
<li><ol>
<li>tekst a</li>
<li><ol>
<li>tekst b</li>
<li>tekst c</li>
<li>tekst d</li>
</ol></li>
<li><ul>
<li>tekst e</li>
<li>tekst f</li>
</ul></li>
<li>tekst g</li>
<li><ol>
<li>tekst h</li>
</ol></li>
<li>tekst i</li>
</ol></li>
</ol>
I još malo<ul><li>uvučeno</li></ul>
</body>
</html>
''')
v = P('''
<html>
<head>_</head>
<body>
<ol>
<li>jedan</li>
<li>dva</li>
</ol>
</body>
</html>
''')
prikaz(r, 7)
r.render()
<file_sep>from Tokeni import *
from uuid import uuid1
import re
separatoriZnakovi = '()[]{},;'
escapeZnakovi = ['\n', '\t', '\v', '\b', '\r', '\f', '\a', '\'', '\"', '\\']
escapeChars = ['n', 't', 'v', 'b', 'r', 'f', 'a', "'", '"', '\\']
naredbe = {'if', 'else', 'while', 'for', 'assert', 'error', 'print'}
assignOperators = {Tokeni.PLUSEQ, Tokeni.MINUSEQ, Tokeni.ZVJEQ, Tokeni.SLASHEQ, Tokeni.MODEQ, Tokeni.LSHIFTEQ, Tokeni.RSHIFTEQ, Tokeni.ASSIGN, Tokeni.ANDEQ, Tokeni.POTEQ, Tokeni.CRTAEQ}
primitivniTipovi = {Tokeni.INT, Tokeni.BOOL, Tokeni.STRING, Tokeni.CHAR, Tokeni.POINTER, Tokeni.ARRAY}
osnovniIzrazi = {Tokeni.DECIMALNI, Tokeni.HEKSADEKADSKI, Tokeni.STRLIT, Tokeni.CHRLIT,
Tokeni.BOOLEAN, Tokeni.NULL}
def isxdigit(znak):
"""Provjerava je li znak hex znamenka"""
return znak != '' and (znak.isdigit() or znak in 'ABCDEFabcdef')
def isuzatv(znak):
"""Provjerava je li znak UZATV"""
return znak ==']'
def isNChar(znak):
"""Provjerava je li znak nchar"""
p = re.compile('^[ -~]$')
if (p.match(znak) is None or znak == '"'):
return False
return True
def isSChar(znak):
"""Provjerava je li znak schar"""
if (isNChar(znak) or znak in escapeZnakovi):
return True
return False
def Lekser(kôd):
lex = Tokenizer(kôd)
citamString = False
for znak in iter(lex.čitaj, ''):
if (citamString):
if znak == '\\':
idući = lex.čitaj()
if (idući not in escapeChars):
lex.greška("Neispravan string")
elif isNChar(znak):
continue
elif znak == '"':
citamString = False
yield lex.token(Tokeni.STRLIT)
else:
lex.greška("Neispravan string")
elif znak == ' ':
lex.token(E.PRAZNO) #enter i tabulator su nam tokeni
elif znak == '"': #prelazimo u stanje citanja stringa
citamString = True
continue
elif znak.isalpha() or znak == '_':
# onda je identifier
lex.zvijezda(identifikator)
if lex.sadržaj in {'true', 'false'}: yield lex.token(Tokeni.BOOLEAN)
elif (lex.sadržaj == 'NULL'): yield lex.token(Tokeni.NULL)
elif (lex.sadržaj in naredbe): yield lex.token(Tokeni(lex.sadržaj))
elif (lex.sadržaj == 'break'): yield lex.token(Tokeni.BREAK)
elif (lex.sadržaj == 'continue'): yield lex.token(Tokeni.CONTINUE)
elif (lex.sadržaj == 'return'): yield lex.token(Tokeni.RETURN)
elif (lex.sadržaj == 'alloc'): yield lex.token(Tokeni.ALLOC)
elif (lex.sadržaj == 'alloc_array'): yield lex.token(Tokeni.ALLOCA)
elif (lex.sadržaj == 'int'):
sljedeći = lex.pogledaj()
if sljedeći == '*':
lex.čitaj()
yield lex.token(Tokeni.POINTER)
elif sljedeći == '[':
lex.čitaj()
lex.pročitaj(']')
yield lex.token(Tokeni.ARRAY)
else: yield lex.token(Tokeni.INT)
elif (lex.sadržaj == 'bool'):
sljedeći = lex.pogledaj()
if sljedeći == '*':
lex.čitaj()
yield lex.token(Tokeni.POINTER)
elif sljedeći == '[':
lex.čitaj()
lex.pročitaj(']')
yield lex.token(Tokeni.ARRAY)
yield lex.token(Tokeni.BOOL)
elif (lex.sadržaj == 'char'):
sljedeći = lex.pogledaj()
if sljedeći == '*':
lex.čitaj()
yield lex.token(Tokeni.POINTER)
elif sljedeći == '[':
lex.čitaj()
lex.pročitaj(']')
yield lex.token(Tokeni.ARRAY)
yield lex.token(Tokeni.CHAR)
elif (lex.sadržaj == 'string'):
sljedeći = lex.pogledaj()
if sljedeći == '*':
lex.čitaj()
yield lex.token(Tokeni.POINTER)
elif sljedeći == '[':
lex.čitaj()
lex.pročitaj(']')
yield lex.token(Tokeni.ARRAY)
yield lex.token(Tokeni.STRING)
elif (lex.sadržaj == 'void'):
sljedeći = lex.pogledaj()
if sljedeći == '*':
lex.čitaj()
yield lex.token(Tokeni.POINTER)
elif sljedeći == '[':
lex.čitaj()
lex.pročitaj(']')
yield lex.token(Tokeni.ARRAY)
yield lex.token(Tokeni.VOID)
else:
yield lex.token(Tokeni.IDENTIFIER)
elif znak.isdigit():
# onda je dec ili hex
if znak == '0':
sljedeći = lex.pogledaj()
if sljedeći == 'x' or sljedeći == 'X':
# onda je hex
lex.čitaj()
lex.plus(isxdigit)
yield lex.token(Tokeni.HEKSADEKADSKI)
elif sljedeći.isdigit():
lex.greška('očekujem x ili X')
else:
yield lex.token(Tokeni.DECIMALNI)
else:
lex.pogledaj()
# onda je dec
lex.zvijezda(str.isdigit)
yield lex.token(Tokeni.DECIMALNI)
# je li chrlit?
elif znak == "'":
idući = lex.čitaj()
if (not isNChar(idući) and not idući in escapeZnakovi and not idući == '"' and not idući == '\0'):
raise LeksičkaGreška("Neispravan chrlit")
kraj = lex.čitaj()
if (kraj == "'"):
yield lex.token(Tokeni.CHRLIT)
else:
raise LeksičkaGreška("Neispravan chrlit")
#je li escape sekvenca ili separator?
elif znak in separatoriZnakovi:
yield lex.token(Tokeni(znak))
elif znak in escapeZnakovi:
if (znak.isspace()):
lex.token(Tokeni(znak))
else:
yield lex.token(Tokeni(znak))
# je li operator?
# !, !=
elif znak == '!':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.DISEQ)
else:
yield lex.token(Tokeni.USKL)
# ~
elif znak == '~':
yield lex.token(Tokeni.TILDA)
# *, *=
elif znak == '*':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.ZVJEQ)
else:
yield lex.token(Tokeni.ZVJ)
# .
elif znak == '.':
yield lex.token(Tokeni.TOCKA)
# -, ->, -=, --
elif znak == '-':
sljedeći = lex.pogledaj()
if sljedeći == '>':
lex.čitaj()
yield lex.token(Tokeni.STRELICA)
elif sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.MINUSEQ)
elif sljedeći == '-':
lex.čitaj()
yield lex.token(Tokeni.DECR)
else:
yield lex.token(Tokeni.MINUS)
# /, /=
elif znak == '/':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.SLASHEQ)
elif sljedeći == '/':
lex.zvijezda(lambda znak: znak != '\n')
lex.pročitaj('\n')
lex.token(Tokeni.COMMENT)
elif sljedeći == '*': #komentari tipa /* */
lex.pročitaj('*')
while not (lex.čitaj() == '*' and lex.pogledaj() == '/'): pass
lex.pročitaj('/')
lex.token(Tokeni.COMMENT)
else:
yield lex.token(Tokeni.SLASH)
# %, %=
elif znak == '%':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.MODEQ)
else:
yield lex.token(Tokeni.MOD)
# +, +=, ++
elif znak == '+':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.PLUSEQ)
elif sljedeći == '+':
lex.čitaj()
yield lex.token(Tokeni.INCR)
else:
yield lex.token(Tokeni.PLUS)
#operatori <, <<, <<=, <=
elif znak == '<':
sljedeći = lex.pogledaj()
if sljedeći == '<':
lex.čitaj()
ssljedeći = lex.pogledaj()
if ssljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.LSHIFTEQ)
else:
yield lex.token(Tokeni.LSHIFT)
elif sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.LESSEQ)
else:
yield lex.token(Tokeni.LESS)
# >, >>, >>=, >=
elif znak == '>':
sljedeći = lex.pogledaj()
if sljedeći == '>':
lex.čitaj()
ssljedeći = lex.pogledaj()
if ssljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.RSHIFTEQ)
else:
yield lex.token(Tokeni.RSHIFT)
elif sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.GRTEQ)
else:
yield lex.token(Tokeni.GRT)
# =, ==
elif znak == '=':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.EQ)
else:
yield lex.token(Tokeni.ASSIGN)
# &, &=, &&
elif znak == '&':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.ANDEQ)
elif sljedeći == '&':
lex.čitaj()
yield lex.token(Tokeni.LAND)
else:
yield lex.token(Tokeni.BITAND)
# |, |=, ||
elif znak == '|':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.CRTAEQ)
elif sljedeći == '|':
lex.čitaj()
yield lex.token(Tokeni.LOR)
else:
yield lex.token(Tokeni.BITOR)
# ^, ^=
elif znak == '^':
sljedeći = lex.pogledaj()
if sljedeći == '=':
lex.čitaj()
yield lex.token(Tokeni.POTEQ)
else:
yield lex.token(Tokeni.BITEXCLOR)
# ?
elif znak == '?':
yield lex.token(Tokeni.CONDQ)
# :
elif znak == ':':
yield lex.token(Tokeni.CONDDOT)<file_sep>"""Aritmetika u skupu racionalnih brojeva, s detekcijom grešaka.
Po uzoru na https://web.math.pmf.unizg.hr/~veky/B/IP.k2p.17-09-08.pdf."""
from vepar import *
import fractions
class T(TipoviTokena):
PLUS, MINUS, PUTA, KROZ, JEDNAKO, OTV, ZATV, NOVIRED = '+-*/=()\n'
class BROJ(Token):
def izračunaj(t): return fractions.Fraction(t.sadržaj)
class IME(Token):
def izračunaj(t):
if t in rt.memorija: return rt.memorija[t]
else: raise t.nedeklaracija(f'pri pridruživanju {rt.pridruženo}')
@lexer
def aq(lex):
for znak in lex:
if znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak.isalnum():
lex * {str.isalnum, '_'}
yield lex.token(T.IME)
elif znak.isspace() and znak != '\n': lex.zanemari()
else: yield lex.literal(T)
### BKG
# program -> '' | program naredba
# naredba -> IME JEDNAKO izraz NOVIRED
# izraz -> član | izraz PLUS član | izraz MINUS član
# član -> faktor | član PUTA faktor | član KROZ faktor
# faktor -> BROJ | IME | MINUS faktor | OTV izraz ZATV
class P(Parser):
def program(p) -> 'Program':
pridruživanja = []
while ime := p >= T.IME:
p >> T.JEDNAKO
pridruživanja.append((ime, p.izraz()))
p >> T.NOVIRED
return Program(pridruživanja)
def izraz(p) -> 'član|Op':
t = p.član()
while op := p >= {T.PLUS, T.MINUS}: t = Op(op, t, p.član())
return t
def član(p) -> 'faktor|Op':
t = p.faktor()
while op := p >= {T.PUTA, T.KROZ}: t = Op(op, t, p.faktor())
return t
def faktor(p) -> 'Op|IME|BROJ|izraz':
if op := p >= T.MINUS: return Op(op, nenavedeno, p.faktor())
if elementarni := p >= {T.IME, T.BROJ}: return elementarni
elif p >> T.OTV:
u_zagradi = p.izraz()
p >> T.ZATV
return u_zagradi
### AST
# Program: pridruživanja:[(IME,izraz)]
# izraz: BROJ: Token
# IME: Token
# Op: op:PLUS|MINUS|PUTA|KROZ lijevo:izraz? desno:izraz
class Program(AST):
pridruživanja: '(IME,izraz)*'
def izvrši(program):
rt.memorija = Memorija()
for ime, vrijednost in program.pridruživanja:
rt.pridruženo = ime
rt.memorija[ime] = vrijednost.izračunaj()
del rt.pridruženo
return rt.memorija
class Op(AST):
op: 'T'
lijevo: 'izraz?'
desno: 'izraz'
def izračunaj(self):
if self.lijevo is nenavedeno: l = 0 # unarni minus: -x = 0-x
else: l = self.lijevo.izračunaj()
o, d = self.op, self.desno.izračunaj()
if o ^ T.PLUS: return l + d
elif o ^ T.MINUS: return l - d
elif o ^ T.PUTA: return l * d
elif d: return l / d
else: raise self.iznimka(
f'dijeljenje nulom pri pridruživanju {rt.pridruženo}')
# Moramo staviti backslash na početak jer inače program počinje novim redom.
ast = P('''\
a = 3 / 7
b = a + 3
c = b - b
b = a * -a
d = a / (c + 1)
e = -3 / 3
''')
prikaz(ast)
for ime, vrijednost in ast.izvrši(): print(ime.sadržaj, vrijednost, sep='=')
<file_sep>import random, itertools, operator, types, pprint, contextlib, collections
import textwrap, string, pdb, copy, abc, functools
memoiziraj = functools.lru_cache(maxsize=None)
def djeljiv(m, n):
"""Je li m djeljiv s n?"""
return not m % n
def ispiši(automat):
"""Relativno uredan ispis (konačnog ili potisnog) automata."""
pprint.pprint(automat.komponente)
def Kartezijev_produkt(*skupovi):
"""Skup uređenih n-torki."""
return set(itertools.product(*skupovi))
def funkcija(f, domena, kodomena):
"""Je li f:domena->kodomena?"""
return f.keys() == domena and set(f.values()) <= kodomena
class fset(set):
"""Ponaša se kao frozenset, ispisuje se kao set."""
def __repr__(self):
return repr(set(self)) if self else '∅'
def __or__(self, other):
return fset(set(self) | set(other))
def __and__(self, other):
return fset(set(self) & set(other))
def __sub__(self, other):
return fset(set(self) - set(other))
def __xor__(self, other):
return fset(set(self) ^ set(other))
__ror__, __rand__, __rsub__, __rxor__ = __or__, __and__, __sub__, __xor__
def __hash__(self):
return hash(frozenset(self))
def __iand__(self, other):
return NotImplemented
def __ior__(self, other):
return NotImplemented
def __isub__(self, other):
return NotImplemented
def __ixor__(self, other):
return NotImplemented
def add(self, value):
raise TypeError('fset is immutable')
def clear(self):
raise TypeError('fset is immutable')
def difference_update(self, other):
raise TypeError('fset is immutable')
def intersection_update(self, other):
raise TypeError('fset is immutable')
def discard(self, value):
raise TypeError('fset is immutable')
def pop(self):
raise TypeError('fset is immutable')
def remove(self, value):
raise TypeError('fset is immutable')
def symmetric_difference_update(self, other):
raise TypeError('fset is immutable')
def update(self, other):
raise TypeError('fset is immutable')
def difference(self, other):
return self - other
def intersection(self, other):
return self & other
def symmetric_difference(self, other):
return self ^ other
def union(self, other):
return self | other
def copy(self):
return self
def __dir__(self):
return dir(frozenset)
def partitivni_skup(skup):
"""Skup svih podskupova zadanog skupa."""
return {fset(itertools.compress(skup, χ))
for χ in itertools.product({False, True}, repeat=len(skup))}
def relacija(R, *skupovi):
"""Je li R relacija među zadanim skupovima?"""
return R <= Kartezijev_produkt(*skupovi)
def sažmi(vrijednost):
"""Sažimanje 1-torki u njihove elemente. Ostale n-torke ne dira."""
with contextlib.suppress(TypeError, ValueError):
komponenta, = vrijednost
return komponenta
return vrijednost
def naniži(vrijednost):
"""Pretvaranje vrijednosti koja nije n-torka u 1-torku."""
return vrijednost if isinstance(vrijednost, tuple) else (vrijednost,)
def funkcija_iz_relacije(relacija, *domene):
"""Pretvara R⊆A×B×C×D×E (uz domene A, B) u f:A×B→℘(C×D×E)."""
m = len(domene)
funkcija = {sažmi(x): set() for x in Kartezijev_produkt(*domene)}
for n_torka in relacija:
assert len(n_torka) > m
for x_i, domena_i in zip(n_torka, domene):
assert x_i in domena_i
x, y = n_torka[:m], n_torka[m:]
if len(x) == 1: x, = x
if len(y) == 1: y, = y
funkcija[sažmi(x)].add(sažmi(y))
return funkcija
def relacija_iz_funkcije(funkcija):
"""Pretvara f:A×B→℘(C×D×E) u R⊆A×B×C×D×E."""
return {naniži(x) + naniži(y) for x, yi in funkcija.items() for y in yi}
def unija_familije(familija):
"""Unija familije skupova."""
return fset(x for skup in familija for x in skup)
def disjunktna_unija(*skupovi):
"""Unija skupova, osiguravajući da su u parovima disjunktni."""
for skup1, skup2 in itertools.combinations(skupovi, 2):
assert skup1.isdisjoint(skup2)
return set().union(*skupovi)
def ε_proširenje(Σ):
"""Σ∪{ε}"""
return disjunktna_unija(Σ, {ε})
def primijeni(pravilo, riječ, mjesto):
"""Primjenjuje gramatičko pravilo na zadanom mjestu (indeksu) u riječi."""
varijabla, *zamjena = pravilo
assert riječ[mjesto] == varijabla
rezultat = list(riječ[:mjesto]) + zamjena + list(riječ[mjesto+1:])
return ''.join(rezultat) if isinstance(riječ, str) else rezultat
class Kontraprimjer(Exception):
"""Jezik se ne slaže sa zadanom specifikacijom."""
def __init__(self, test, spec):
self.args = "Jezik {}sadrži {!r}".format('ne '*bool(spec), test),
class PrazniString(str):
"""Klasa koja određuje ponašanje objekta ε."""
def __add__(self, other):
return other
def __mul__(self, n):
return self
def __len__(self):
return 0
def __repr__(self):
return 'ε'
__radd__, __rmul__, __str__ = __add__, __mul__, __repr__
ε = PrazniString()
def parsiraj_tablicu_KA(tablica):
"""Parsiranje tabličnog zapisa konačnog automata (Sipser page 36).
Prvo stanje je početno, završna su označena znakom # na kraju reda."""
prva, *ostale = tablica.strip().splitlines()
znakovi = prva.split()
assert all(len(znak) == 1 for znak in znakovi)
abeceda = set(znakovi)
stanja, završna = set(), set()
prijelaz, početno = {}, None
for linija in ostale:
stanje, *dolazna = linija.split()
if početno is None: početno = stanje
extra = len(dolazna) - len(znakovi)
assert extra in {0, 1}
if extra == 1:
assert dolazna.pop() == '#'
završna.add(stanje)
for znak, dolazno in zip(znakovi, dolazna):
prijelaz[stanje, znak] = dolazno
stanja.add(stanje)
return stanja, abeceda, prijelaz, početno, završna
def parsiraj_tablicu_NKA(tablica):
"""Parsiranje tabličnog zapisa nedeterminističnog KA (Sipser page 54).
Prvo stanje je početno, završna su označena znakom # na kraju reda.
ε-prijelazi su nakon svih znak-prijelaza (stupac čije zaglavlje nema znaka).
Izostanak prijelaza označava se znakom / na odgovarajućem mjestu.
Višestruki prijelazi za isto stanje i znak razdvojeni su znakom /."""
prva, *ostale = tablica.strip().splitlines()
znakovi = prva.split()
assert all(len(znak) == 1 for znak in znakovi)
abeceda = set(znakovi)
stanja, završna = set(), set()
prijelaz, početno = set(), None
for linija in ostale:
stanje, *dolazna = linija.split()
if početno is None: početno = stanje
extra = len(dolazna) - len(znakovi)
assert extra >= 0
if extra > 0 and dolazna[~0] == '#':
del dolazna[~0]
završna.add(stanje)
for znak, dolazno in zip(znakovi, dolazna):
for dolazno1 in filter(None, dolazno.split('/')):
prijelaz.add((stanje, znak, dolazno1))
for dolazno in dolazna[len(znakovi):]:
for dolazno2 in dolazno.split('/'):
prijelaz.add((stanje, ε, dolazno2))
stanja.add(stanje)
return stanja, abeceda, prijelaz, početno, završna
def parsiraj_tablicu_PA(tablica):
"""Parsiranje tabličnog zapisa (relacije prijelaza) potisnog automata.
Svaki redak ima polazno stanje, čitani znak, pop znak, dolazno, push znak.
Prvo polazno stanje je početno, završna su označena znakom # na kraju reda.
ε se označava znakom /. Završno stanje iz kojeg ne izlazi strelica je #."""
stanja, abeceda, abeceda_stoga, prijelaz = set(), set(), set(), set()
početno, završna = None, set()
def dodaj(znak, skup):
if znak in {'/', 'ε'}:
return ε
skup.add(znak)
return znak
for linija in tablica.strip().splitlines():
trenutno_završno = False
ćelije = linija.split()
if len(ćelije) == 6:
assert ćelije.pop() == '#'
trenutno_završno = True
polazno, znak, stog_pop, dolazno, stog_push = ćelije
if početno is None:
početno = polazno
stanja |= {polazno, dolazno}
assert len(znak) == 1
znak = dodaj(znak, abeceda)
stog_pop = dodaj(stog_pop, abeceda_stoga)
stog_push = dodaj(stog_push, abeceda_stoga)
if trenutno_završno:
završna.add(polazno)
prijelaz.add((polazno, znak, stog_pop, dolazno, stog_push))
if '#' in stanja: završna.add('#')
return stanja, abeceda, abeceda_stoga, prijelaz, početno, završna
def parsiraj_tablicu_TS(tablica):
"""Parsiranje tabličnog zapisa (funkcije prijelaza) Turingovog stroja.
Prvo stanje je početno, . prihvaća, ! odbija (beskonačna petlja udesno).
Prijelazi: znak+stanje ili znak-stanje. Ako nešto ne piše, ostaje isto.
Praznina je _, i njena pozicija označava kraj ulazne abecede."""
prva, *ostale = tablica.strip().splitlines()
znakovi = prva.split()
assert all(len(znak) == 1 for znak in znakovi) and '_' in znakovi
radna_abeceda = set(znakovi)
abeceda = set(znakovi[:znakovi.index('_')])
stanja, prijelaz, početno = {'.'}, {}, None
for linija in ostale:
stanje, *prijelazi = linija.split()
if početno is None: početno = stanje
assert len(prijelazi) == len(znakovi)
for znak, trojka in zip(znakovi, prijelazi):
if trojka in set('.!'): nstanje, nznak, smjer = trojka, znak, ''
elif trojka.endswith(tuple('.!')):
nstanje, nznak, smjer = trojka[-1], trojka[:-1], ''
else:
for smjer in '+-':
nznak, smjer, nstanje = trojka.partition(smjer)
if smjer: break
assert smjer
if not nznak: nznak = znak
if not nstanje: nstanje = stanje
stanja.add(nstanje)
prijelaz[stanje, znak] = (nstanje, nznak, int(smjer + '1'))
stanja.add(stanje)
if '!' in stanja:
for znak in znakovi: prijelaz['!', znak] = ('!', znak, 1)
return stanja, abeceda, radna_abeceda, '_', prijelaz, početno, '.'
def parsiraj_strelice_BKG(strelice):
"""Čitanje gramatike zapisane u standardnom obliku pomoću strelica.
Svaki red je oblika varijabla -> ds1 | ds2 | ... (moguće desne strane).
ε se može i ne mora pisati. Prvi red s lijeve strane ima početnu varijablu.
Znakovi u svakoj desnoj strani moraju biti razdvojeni razmacima."""
varijable, simboli, pravila, početna = set(), set(), set(), None
for linija in strelice.strip().splitlines():
linija = linija.replace('->', ' -> ', 1)
varijabla, strelica, ostalo = linija.split(None, 2)
varijable.add(varijabla)
if početna is None:
početna = varijabla
for zamjena in ostalo.split('|'):
zamjene = tuple(zamjena.split())
if zamjene == ('ε',): zamjene = ()
pravila.add((varijabla,) + zamjene)
simboli.update(zamjene)
return varijable, simboli - varijable, pravila, početna
def strelice(gramatika):
"""Ispis gramatike u standardnom obliku pomoću strelicâ.
Pogledati funkciju util.parsiraj_strelice_BKG za detalje."""
grupe = {V: set() for V in gramatika.varijable}
for varijabla, *zamjene in gramatika.pravila:
grupe[varijabla].add(' '.join(map(str, zamjene)) or 'ε')
print(gramatika.početna, '->',
' | '.join(grupe.pop(gramatika.početna)) or '∅')
for varijabla, grupa in sorted(grupe.items()):
print(varijabla, '->', ' | '.join(grupa) or '∅')
print()
def slučajni_testovi(abeceda, koliko, maxduljina):
"""Generator slučajno odabranih riječi nad abecedom."""
znakovi = list(abeceda)
yield ε
for znak in znakovi:
yield znak,
for _ in range(koliko):
duljina = random.randint(2, maxduljina)
yield tuple(random.choice(znakovi) for _ in range(duljina))
def provjeri(objekt, specifikacija, koliko=999, maxduljina=9):
"""Osigurava da se objekt drži specifikacije, slučajnim testiranjem."""
import RI, BKG
if isinstance(objekt, RI.RegularniIzraz):
jezik = objekt.KA().prihvaća
elif isinstance(objekt, BKG.BeskontekstnaGramatika):
jezik = objekt.CYK
else:
jezik = objekt.prihvaća
for test in slučajni_testovi(objekt.abeceda, koliko, maxduljina):
lijevo = jezik(test)
if isinstance(test, tuple) and all(
isinstance(znak, str) and len(znak) == 1 for znak in test):
test = ''.join(test)
desno = specifikacija(test)
if lijevo != bool(desno):
raise Kontraprimjer(test, desno)
def označi1(stanje, *ls):
"""Dodaje oznaci stanja dodatne oznake u ls."""
return naniži(stanje) + ls
def novo(prefiks, iskorišteni):
"""Novi element koji počinje prefiksom i ne pripada skupu iskorišteni."""
if prefiks in iskorišteni:
for broj in itertools.count():
kandidat = prefiks + str(broj)
if kandidat not in iskorišteni:
return kandidat
return prefiks
def DOT_PA(automat):
"""Dijagram danog PA u formatu DOT. ε se piše kao e."""
Q, Σ, Γ, Δ, q0, F = automat.komponente
r = {q: i for i, q in enumerate(Q, 1)}
obrazac = [
'digraph {',
'rankdir = LR',
'node [ style = invis ] 0',
'node [ style = solid ]',
]
for oznaka, broj in r.items():
obrazac.append('node [ peripheries={}, label="{}" ] {}'
.format(2 if oznaka in F else 1, oznaka, broj))
obrazac.append('0 -> ' + str(r[q0]))
brid = collections.defaultdict(set)
for p, α, t, q, s in Δ:
brid[p, q, t, s].add(α)
for (p, q, t, s), znakovi in brid.items():
linija = ','.join(map(str, znakovi))
if not s == t == ε:
if linija == 'ε': linija = ''
else: linija += ','
linija += '{}:{}'.format(t if t != ε else '', s if s != ε else '')
obrazac.append('{} -> {} [ label="{}" ]'.format(r[p], r[q], linija))
obrazac.append('}')
return '\n'.join(obrazac).replace('ε', 'e')
def prikaz(stanje, pozicija, traka):
print(*traka[:pozicija], '[{}>'.format(stanje),
*traka[pozicija:], '_', sep='')
<file_sep>from KA import *
from RI import *
from PA import *
from BKG import *
from TS import *
tests = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
tests |= {21, 22, 23, 24, 25, 26, 27, 28, 29, 30}
tests |= {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
tests |= {41, 42, 43, 44, 45, 46, 47, 48, 49, 50}
tests |= {51, 52, 53, 54}
tests |= {90}
def test(i):
if i in tests:
print('#' * 30, 'Test', i, '#' * 30)
return True
if test(1): # page 34 figure 1.4 # page 36 figure 1.6
M1 = KonačniAutomat.iz_tablice('''
0 1
q1 q1 q2
q2 q3 q2 #
q3 q2 q2 ''')
print(*M1.izračunavanje('1101'))
for riječ in '1','01','11','0101010101','100','0100','110000','0101000000':
assert M1.prihvaća(riječ)
for riječ in '0', '10', '101000':
assert not M1.prihvaća(riječ)
provjeri(M1, lambda ulaz: djeljiv(ulaz[::-1].find('1'), 2))
if test(2): # page 37 example 1.7 figure 1.8
M2 = KonačniAutomat.iz_tablice('''
0 1
q1 q1 q2
q2 q1 q2 # ''')
print(*M2.izračunavanje('1101'), *M2.izračunavanje('110'))
provjeri(M2, lambda ulaz: ulaz.endswith('1'))
if test(3): # page 38 example 1.9 figure 1.10
M3 = KonačniAutomat.iz_tablice('''
0 1
q1 q1 q2 #
q2 q1 q2 ''')
provjeri(M3, lambda ulaz: ulaz == ε or ulaz.endswith('0'))
if test(4): # page 38 example 1.11 figure 1.12
M4 = KonačniAutomat.iz_tablice('''
a b
s q1 r1
q1 q1 q2 #
q2 q1 q2
r1 r2 r1 #
r2 r2 r1 ''')
for riječ in 'a', 'b', 'aa', 'bb', 'bab':
assert M4.prihvaća(riječ)
for riječ in 'ab', 'ba', 'bbba':
assert not M4.prihvaća(riječ)
provjeri(M4, lambda ulaz: ulaz and ulaz[0] == ulaz[~0])
if test(5): # page 39 example 1.13 figure 1.14
M5 = KonačniAutomat.iz_tablice('''
R 0 1 2
q0 q0 q0 q1 q2 #
q1 q0 q1 q2 q0
q2 q0 q2 q0 q1 ''')
print(*M5.izračunavanje('10R22R012')) # page 41 example 1.17
def M5_spec(ulaz):
zbroj = 0
for znak in ulaz:
if znak == 'R': zbroj = 0
else: zbroj += int(znak)
return djeljiv(zbroj, 3)
provjeri(M5, M5_spec)
if test(6): # page 40 example 1.15
for i in range(1, 10):
def Ai(ulaz):
zbroj = 0
for znak in ulaz:
if znak == '<RESET>': zbroj = 0
else: zbroj += int(znak)
return djeljiv(zbroj, i)
Qi = set(range(i))
Σ = {'<RESET>', 0, 1, 2}
δi = {}
for j in Qi:
δi[j, '<RESET>'] = 0
δi[j, 0] = j
δi[j, 1] = (j + 1) % i
δi[j, 2] = (j + 2) % i
Bi = KonačniAutomat.iz_komponenti(Qi, Σ, δi, 0, {0})
provjeri(Bi, Ai)
print(i, end=' OK ')
if test(7): # page 43 figure 1.20
E1 = KonačniAutomat.iz_tablice('''
0 1
qeven qeven qodd
qodd qodd qeven # ''')
provjeri(E1, lambda ulaz: ulaz.count('1') % 2)
if test(8): # page 44 example 1.21 figure 1.22
E2 = KonačniAutomat.iz_tablice('''
0 1
q q0 q
q0 q00 q
q00 q00 q001
q001 q001 q001 # ''')
provjeri(E2, lambda ulaz: '001' in ulaz)
if test(9):
E1u2 = E1.unija(E2)
provjeri(E1u2, lambda ulaz: E1.prihvaća(ulaz) or E2.prihvaća(ulaz))
ispiši(E1u2)
E1n2 = E1.presjek(E2)
provjeri(E1n2, lambda ulaz: E1.prihvaća(ulaz) and E2.prihvaća(ulaz))
print(*E1n2.izračunavanje('101'))
E1n2.prirodni().crtaj()
E1k = E1.komplement()
provjeri(E1k, lambda ulaz: not E1.prihvaća(ulaz))
E1b2 = E1.razlika(E2)
provjeri(E1b2, lambda ulaz: E1.prihvaća(ulaz) > E2.prihvaća(ulaz))
E1t2 = E1.optimizirana_simetrična_razlika(E2)
provjeri(E1t2, lambda ulaz: E1.prihvaća(ulaz) ^ E2.prihvaća(ulaz))
if test(10): # page 48 figure 1.27
N1 = NedeterminističniKonačniAutomat.iz_komponenti({'q1', 'q2', 'q3', 'q4'},
{'0', '1'}, {('q1', '0', 'q1'), ('q1', '1', 'q1'), ('q1', '1', 'q2'),
('q2', '0', 'q3'), ('q2', ε, 'q3'), ('q3', '1', 'q4'),
('q4', '0', 'q4'), ('q4', '1', 'q4')}, 'q1', {'q4'})
assert N1 == NedeterminističniKonačniAutomat.iz_tablice('''
0 1
q1 q1 q1/q2
q2 q3 / q3
q3 / q4
q4 q4 q4 #''') # page 54 example 1.38
provjeri(N1, lambda ulaz: '101' in ulaz or '11' in ulaz)
print(*N1.izračunavanje('010110')) # page 49 figure 1.29
print(*N1.izračunavanje('010'))
N1b = NedeterminističniKonačniAutomat.iz_komponenti({1,2,3,4}, {0,1},
{(1,0,1),(1,1,1),(1,1,2),(2,0,3),(2,ε,3),(3,1,4),(4,0,4),(4,1,4)}, 1, {4})
D1b = N1b.optimizirana_partitivna_konstrukcija()
if test(11): # page 51 example 1.30 figure 1.31
N2 = NedeterminističniKonačniAutomat.iz_tablice('''
0 1
q1 q1 q1/q2
q2 q3 q3
q3 q4 q4
q4 / / # ''')
provjeri(N2, lambda ulaz: len(ulaz) >= 3 and ulaz[~2] == '1')
D2 = N2.optimizirana_partitivna_konstrukcija()
D2.prirodni().crtaj()
print(len(D2.stanja), len(D2.prijelaz))
N2c = copy.deepcopy(N2)
N2c.prijelaz |= {('q2', ε, 'q3'), ('q3', ε, 'q4')}
provjeri(N2c, lambda ulaz: '1' in ulaz[~2:])
if test(12): # page 52 example 1.33
N3 = NedeterminističniKonačniAutomat.iz_tablice('''
0
0 / 20 30
20 21 #
21 20
30 31 #
31 32
32 30''')
for ulaz in ε, '00', '000', '0000', '000000':
assert N3.prihvaća(ulaz)
for ulaz in '0', '00000':
assert not N3.prihvaća(ulaz)
provjeri(N3, lambda ulaz: djeljiv(len(ulaz), 2) or djeljiv(len(ulaz), 3))
if test(13): # page 52 example 1.35 figure 1.36
N4 = NedeterminističniKonačniAutomat.iz_tablice('''
a b
q1 / q2 q3 #
q2 q2/q3 q3
q3 q1 /''')
for ulaz in ε, 'a', 'baba', 'baa':
assert N4.prihvaća(ulaz)
for ulaz in 'b', 'bb', 'babba':
assert not N4.prihvaća(ulaz)
D4 = N4.partitivna_konstrukcija() # page 58 example 1.41
D4.prirodni().crtaj() # figure 1.43
N4.optimizirana_partitivna_konstrukcija().crtaj() # figure 1.44
if test(14):
N1 = NedeterminističniKonačniAutomat.iz_komponenti(
{0, 1}, {'a'}, {(0, 'a', 1), (1, 'a', 0)}, 0, {0})
N2 = NedeterminističniKonačniAutomat.iz_komponenti(
{0, 1, 2}, {'a'}, {(0, 'a', 1), (1, 'a', 2), (2, 'a', 0)}, 0, {0})
N1u2 = N1.unija(N2)
N1o2 = N1.konkatenacija(N2)
N1o2.crtaj()
if test(21):
binarni = nula | jedan * (nula|jedan).z
print(binarni.početak())
binarni.NKA().crtaj()
if test(22):
primjer1 = (nula | jedan) * nula.z # page 63
print(primjer1.početak())
provjeri(primjer1, lambda ulaz: ulaz != ε and '1' not in ulaz[1:])
if test(23): # page 64 example 1.51
sve = (nula|jedan).z
print(sve.početak())
provjeri(sve, lambda ulaz: True)
provjeri(nula*sve | sve*jedan,
lambda ulaz: ulaz.startswith('0') or ulaz.endswith('1'))
if test(24): # page 65 example 1.53
sigma = nula | jedan
r1 = nula.z * jedan * nula.z
provjeri(r1, lambda ulaz: ulaz.count('1') == 1)
r2 = sigma.z * jedan * sigma.z
provjeri(r2, lambda ulaz: '1' in ulaz)
r3 = sigma.z * nula * nula * jedan * sigma.z
provjeri(r3, lambda ulaz: '001' in ulaz)
r4 = jedan.z * (nula*jedan.p).z
provjeri(r4, lambda ulaz: '00' not in ulaz and not ulaz.endswith('0'))
r5 = (sigma**2).z
provjeri(r5, lambda ulaz: djeljiv(len(ulaz), 2))
r6 = (sigma**3).z
provjeri(r6, lambda ulaz: djeljiv(len(ulaz), 3))
r7 = nula * jedan | jedan * nula
print(r7.konačan(), r7.početak())
r8 = nula*sigma.z*nula | jedan*sigma.z*jedan | sigma
provjeri(r8, lambda ulaz: ulaz and ulaz[0] == ulaz[~0])
r9 = nula.u * jedan.z
print(r9.početak())
r10 = nula.u * jedan.u
print(r10.konačan(), r10.početak())
r11 = jedan.z * prazni
print(r11.prazan())
r12 = prazni.z
print(r12.prazan(), r12.trivijalan())
if test(25): # page 68 example 1.56
e1 = (a*b|a).z
e1.NKA().crtaj()
if test(26): # page 69 example 1.58
e2 = (a|b).z * a * b * a
e2.NKA().crtaj()
provjeri(e2, lambda ulaz: ulaz.endswith('aba'))
if test(27): # page 76 figure 1.69
p = (a**2|b).z
t = (b*a | a) * p
r = (a*p*a).u * b * (t|b**2).z * t.u | a * p
print(r)
if test(28): # page 88 excercise 1.28
ra = a * (a*b*b).z | b
rb = a.p | (a*b).p
rc = (a | b.p) * a.p * b.p
ra.NKA().crtaj()
rb.NKA().crtaj()
rc.NKA().crtaj()
if test(31): # page 114 example 2.14
Ֆ = '$'
M21 = PotisniAutomat.iz_komponenti({1, 2, 3, 4}, {0, 1}, {0, Ֆ},
{(1,ε,ε,2,Ֆ), (2,0,ε,2,0), (2,1,0,3,ε), (3,1,0,3,ε), (3,ε,Ֆ,4,ε)},
1, {1, 4})
ispiši(M21)
M21.crtaj() # page 115 figure 2.15
print(M21.prihvaća((0, 0, 1, 1)), M21.prihvaća((0, 1, 0, 1)))
if test(32): # page 114 example 2.14
M21b = PotisniAutomat.iz_tablice('''
q1 / / q2 $ #
q2 0 / q2 0
q2 1 0 q3 /
q3 1 0 q3 /
q3 / $ # /
''')
provjeri(M21b, lambda w: w.count('0') == w.count('1') and '10' not in w)
if test(33): # page 115 example 2.16
M22 = PotisniAutomat.iz_tablice('''
q1 / / q2 $
q2 a / q2 a
q2 / / q3 /
q2 / / q5 /
q3 b a q3 /
q3 / $ q4 /
q4 c / q4 / #
q5 b / q5 /
q5 / / q6 /
q6 c a q6 /
q6 / $ # /
''')
M22.crtaj() # page 115 figure 2.17
provjeri(M22, lambda w: w.count('a') in {w.count('b'), w.count('c')} and
'ba' not in w and 'cb' not in w and 'ca' not in w)
if test(34): # page 116 example 2.18
M23 = PotisniAutomat.iz_tablice('''
q1 / / q2 $
q2 0 / q2 0
q2 1 / q2 1
q2 / / q3 /
q3 0 0 q3 /
q3 1 1 q3 /
q3 / $ # /
''')
M23.crtaj() # page 116 figure 2.19
provjeri(M23, lambda w: w == w[::-1] and djeljiv(len(w), 2))
if test(35): # page 120 example 2.25
P1 = PotisniAutomat.iz_tablice('''
qstart / / p1 $
p1 / / qloop S
qloop / S a1 b
a1 / / a2 T
a2 / / qloop a
qloop / T b1 a
b1 / / qloop T
qloop / S qloop b
qloop / T qloop /
qloop a a qloop /
qloop b b qloop /
qloop / $ # / ''') # može beskonačno računati
P1m = PotisniAutomat.iz_tablice('''
qstart / / p1 $
p1 / / qloop S
qloop / S a1 b
a1 / / a2 T
a2 / / qloop a
qloop / T b1 T
b1 / / qloop a
qloop / S qloop b
qloop / T qloop /
qloop a a qloop /
qloop b b qloop /
qloop / $ # / ''') # uvijek konačno računa
provjeri(P1m, lambda w: w == 'a' * (len(w) - 1) + 'b')
if test(41): # page 102
G1 = BeskontekstnaGramatika.iz_strelica('''
A -> 0 A 1
A -> B
B -> #
''')
assert G1.varijable == {'A', 'B'} and G1.početna == 'A'
assert G1.abeceda == {'0', '1', '#'} and len(G1.pravila) == 3
assert G1.validan('A 0A1 00A11 000A111 000B111 000#111'.split())
if test(42): # page 103
G2 = BeskontekstnaGramatika.iz_strelica('''
<SENTENCE> -> <NOUN-PHRASE> _ <VERB-PHRASE>
<NOUN-PHRASE> -> <CMPLX-NOUN> | <CMPLX-NOUN> _ <PREP-PHRASE>
<VERB-PHRASE> -> <CMPLX-VERB> | <CMPLX-VERB> _ <PREP-PHRASE>
<PREP-PHRASE> -> <PREP> _ <CMPLX-NOUN>
<CMPLX-NOUN> -> <ARTICLE> _ <NOUN>
<CMPLX-VERB> -> <VERB> | <VERB> _ <NOUN-PHRASE>
<ARTICLE> -> a | t h e
<NOUN> -> b o y | g i r l | f l o w e r
<VERB> -> t o u c h e s | l i k e s | s e e s
<PREP> -> w i t h ''')
assert len(G2.varijable) == 10
G2.abeceda |= set(string.ascii_lowercase + '_')
assert len(G2.abeceda) == 27
assert len(G2.pravila) == 18
assert G2.CYK('a_boy_sees')
assert G2.CYK('the_boy_sees_a_flower')
assert G2.CYK('a_girl_with_a_flower_likes_the_boy')
assert G2.CYK('the_girl_touches_the_boy_with_the_flower')
assert G2.validan([linija.split() for linija in [
'<SENTENCE>',
'<NOUN-PHRASE> _ <VERB-PHRASE>',
'<CMPLX-NOUN> _ <VERB-PHRASE>',
'<ARTICLE> _ <NOUN> _ <VERB-PHRASE>',
'a _ <NOUN> _ <VERB-PHRASE>',
'a _ b o y _ <VERB-PHRASE>',
'a _ b o y _ <CMPLX-VERB>',
'a _ b o y _ <VERB>',
'a _ b o y _ s e e s',
]]) # page 104
if test(43): # page 105 example 2.3
G3 = BeskontekstnaGramatika.iz_strelica('S -> a S b | S S | ε')
G3k = BeskontekstnaGramatika.iz_komponenti(
{'S'}, {'a', 'b'}, {'SaSb', 'SSS', 'S'}, 'S')
G3z = BeskontekstnaGramatika.iz_strelica('S -> ( S ) | S S | ε')
for riječ in 'abab', 'aaabbb', 'aababb':
assert G3k.CYK(riječ)
def G3_spec(riječ):
brojač = 0
for znak in riječ:
if znak == '(': brojač += 1
elif znak == ')': brojač -= 1
else: return False
if brojač < 0: return False
return brojač == 0
provjeri(G3z, G3_spec)
if test(44): # page 105 example 2.4
G4 = BeskontekstnaGramatika.iz_strelica('''
E -> E + T | T
T -> T * F | F
F -> ( E ) | a
''')
assert G4.CYK('a+a*a') and G4.CYK('(a+a)*a')
assert G4.validan('E E+T T+T F+T a+T a+T*F a+F*F a+a*F a+a*a'.split())
assert G4.validan('''E T T*F T*a F*a (E)*a (E+T)*a
(T+T)*a (T+F)*a (F+F)*a (a+F)*a (a+a)*a'''.split())
if test(45): # page 107
G5 = BeskontekstnaGramatika.iz_strelica('E -> E + E | E * E | ( E ) | a')
assert G5.validan('E E*E E+E*E a+E*E a+a*E a+a*a'.split())
assert G5.validan('E E+E E+E*E a+E*E a+a*E a+a*a'.split())
if test(46): # https://goo.gl/FmMNY7
GwpDEL = BeskontekstnaGramatika.iz_strelica('''
S0 -> A b B | C
B -> A A | A C
C -> b | c
A -> a | ε ''')
GwpDEL.faza_DEL()
strelice(GwpDEL)
if test(47): # https://en.wikipedia.org/wiki/Chomsky_normal_form#Example
Gwp = BeskontekstnaGramatika.iz_strelica('''
Expr -> Term | Expr AddOp Term | AddOp Term
Term -> Factor | Term MulOp Factor
Factor -> Primary | Factor ^ Primary
Primary -> number | variable | ( Expr )
AddOp -> + | −
MulOp -> * | / ''')
GwpČ = Gwp.ChNF()
assert len(GwpČ.pravila) == 37
if test(48): # page 110 example 2.10
G6 = BeskontekstnaGramatika.iz_strelica('''
S -> A S A | a B
A -> B | S
B -> b | ε ''')
strelice(G6.ChNF())
if test(49): # page 106
G01 = BeskontekstnaGramatika.iz_strelica('S -> 0 S 1 | ε')
G10 = BeskontekstnaGramatika.iz_strelica('S -> 1 S 0 | ε')
strelice(G01.unija(G10))
strelice(G1.zvijezda())
if test(50): # 2019-dz1-Z2a
g = BeskontekstnaGramatika.iz_strelica('''
S->S S|A B
A->B a|ε
B->B b A a|c A|b
''')
c = g.ChNF()
strelice(g)
strelice(c)
if test(51): # page 171 example 3.7
ts = TuringovStroj.iz_tablice('''0 _ x
q1 _+q2 ! !
q2 x+q3 . +
q3 +q4 -q5 +
q4 x+q3 ! +
q5 - +q2 - ''')
for n in range(9): print(n, ts.prihvaća('0' * n), end=' ', sep=':')
print()
for konf in ts.izračunavanje('0000'): prikaz(*konf)
if test(52): # page 173 example 3.9
ts = TuringovStroj.iz_tablice('''0 1 # _ x
q1 x+q2 x+q3 +q8 ! !
q2 + + +q4 ! !
q3 + + +q5 ! !
q4 x-q6 ! ! ! +
q5 ! x-q6 ! ! +
q6 - - -q7 ! -
q7 - - ! ! +q1
q8 ! ! ! . + ''')
print(ts)
for konf in ts.izračunavanje('#'.join(['011000'] * 2)): prikaz(*konf)
if test(53): # Komputonomikon, Primjer 4.6
tsh = TuringovStroj.iz_tablice('''a b _ c d
A c+B d+B . ! !
B + + -C ! !
C _-D _-D ! ! !
D - - ! a+A b+A''')
for korak, konf in enumerate(tsh.izračunavanje('aba')):
prikaz(*konf)
if korak > 9: break
print()
for konf in tsh.izračunavanje('abaa'): prikaz(*konf)
print(tsh.rezultat('abaa'))
print()
for konf in tsh.izračunavanje('aababa'): prikaz(*konf)
print(tsh.rezultat('aababa'))
print('\n', tsh.prihvaća('aabbaba'), tsh.rezultat('aabbaba'))
if test(54): # Komputonomikon, Lema 4.16
def tsid(Σ):
_ = novo('_', Σ)
Γ = Σ | {_}
δ = {(0, α): (1, α, 1) for α in Γ}
return TuringovStroj.iz_komponenti({0, 1}, Σ, Γ, _, δ, 0, 1)
print(tsid(set('abc_')).rezultat('a_c_a_b_'))
if test(55):
...
if test(90): # 2019-k1-z3
zadatak = jedan.p * nula * jedan.z | jedan.u * nula.z * jedan.p
naivno = zadatak.KA()
službeno_rješenje = ''' 0 1
S / J/N N
J Z J
N N Z
Z / Z # '''
službeni_NKA = NedeterminističniKonačniAutomat.iz_tablice(službeno_rješenje)
službeni_KA = službeni_NKA.optimizirana_partitivna_konstrukcija()
rješenje = ''' 0 1
q0 q2 q3/q1
q1 q3 q1
q2 q2 q3
q3 q2 q3 #
'''
rješenje = NedeterminističniKonačniAutomat.iz_tablice(rješenje)
print(*rješenje.izračunavanje('0101'))
deterministični = rješenje.optimizirana_partitivna_konstrukcija()
razlika = deterministični.optimizirana_simetrična_razlika(službeni_KA)
nedet = NedeterminističniKonačniAutomat.iz_konačnog_automata(razlika)
je_li_prazan = nedet.optimizirana_partitivna_konstrukcija()
je_li_prazan.prirodni().crtaj()
print(je_li_prazan.završna)
<file_sep>"""Istinitosna vrijednost, optimizacija, i lijep ispis, formula logike sudova.
Standardna definicija iz [Vuković, Matematička logika]:
* Propozicijska varijabla (P0, P1, P2, ..., P9, P10, P11, ....) je formula
* Ako je F formula, tada je i !F formula (negacija)
* Ako su F i G formule, tada su i (F&G), (F|G), (F->G) i (F<->G) formule
Sve zagrade (oko binarnih veznika) su obavezne!
Interpretaciju zadajemo imenovanim argumentima: vrijednost(F, P2=True, P7=False)
Optimizacija piše svaku formulu u obliku G ili !G, gdje u G nema negacije."""
from vepar import *
subskript = str.maketrans('0123456789', '₀₁₂₃₄₅₆₇₈₉')
class T(TipoviTokena):
NEG, KONJ, DISJ, OTV, ZATV, KOND, BIKOND = *'!&|()', '->', '<->'
class PVAR(Token):
def vrijednost(self): return rt.interpretacija[self]
def makni_neg(self): return self, True
def ispis(self): return self.sadržaj.translate(subskript)
@lexer
def ls(lex):
for znak in lex:
if znak == 'P':
lex.prirodni_broj('')
yield lex.token(T.PVAR)
elif znak == '-':
lex >> '>'
yield lex.token(T.KOND)
elif znak == '<':
lex >> '-', lex >> '>'
yield lex.token(T.BIKOND)
else: yield lex.literal(T)
### Beskontekstna gramatika:
# formula -> PVAR | NEG formula | OTV formula binvez formula ZATV
# binvez -> KONJ | DISJ | KOND | BIKOND
class P(Parser):
def formula(p) -> \
'PVAR|Negacija|Konjunkcija|Disjunkcija|Kondicional|Bikondicional':
if varijabla := p >= T.PVAR: return varijabla
elif p >= T.NEG:
ispod = p.formula()
return Negacija(ispod)
elif p >> T.OTV:
l, klasa, d = p.formula(), p.binvez(), p.formula()
p >> T.ZATV
return klasa(l, d)
def binvez(p):
if p >= T.KONJ: return Konjunkcija
elif p >= T.DISJ: return Disjunkcija
elif p >= T.KOND: return Kondicional
elif p >= T.BIKOND: return Bikondicional
else: raise p.greška()
### Apstraktna sintaksna stabla (i njihovi atributi):
# formula: PVAR: Token
# Negacija: ispod:formula
# Konjunkcija: Binarna
# Disjunkcija: Binarna
# Kondicional: Binarna
# Bikondicional: Binarna
# Binarna: lijevo:formula desno:formula
class Negacija(AST):
ispod: 'formula'
veznik = '¬'
def vrijednost(negacija): return not negacija.ispod.vrijednost()
def makni_neg(negacija):
bez_neg, pozitivna = negacija.ispod.makni_neg()
return bez_neg, not pozitivna
def ispis(negacija): return negacija.veznik + negacija.ispod.ispis()
class Binarna(AST):
lijevo: 'formula'
desno: 'formula'
def vrijednost(self):
klasa = type(self)
l, d = self.lijevo.vrijednost(), self.desno.vrijednost()
return klasa.tablica(l, d)
def makni_neg(self):
klasa = type(self)
l, lp = self.lijevo.makni_neg()
d, dp = self.desno.makni_neg()
return klasa.xform(l, d, lp, dp), klasa.tablica(lp, dp)
def ispis(self): return '(' + self.lijevo.ispis() + \
self.veznik + self.desno.ispis() + ')'
class Disjunkcija(Binarna):
veznik = '∨'
def tablica(l, d): return l or d
def xform(l, d, lp, dp):
if lp and dp: return Disjunkcija(l, d)
if not lp and dp: return Kondicional(l, d)
if lp and not dp: return Kondicional(d, l)
return Konjunkcija(l, d)
class Konjunkcija(Binarna):
veznik = '∧'
def tablica(l, d): return l and d
def xform(l, d, lp, dp): return Disjunkcija.xform(l, d, not lp, not dp)
class Kondicional(Binarna):
veznik = '→'
def tablica(l, d):
if l: return d
return True
def xform(l, d, lp, dp): return Disjunkcija.xform(l, d, not lp, dp)
class Bikondicional(Binarna):
veznik = '↔'
def tablica(l, d): return l == d
def xform(l, d, lp, dp): return Bikondicional(l, d)
def optim(formula):
"""Pretvara formulu (AST) u oblik s najviše jednom negacijom."""
bez_neg, pozitivna = formula.makni_neg()
if pozitivna: return bez_neg
else: return Negacija(bez_neg)
def istinitost(formula, **interpretacija):
rt.interpretacija = Memorija(interpretacija)
return formula.vrijednost()
for ulaz in '!(P5&!!(P3->P0))', '(!P0&(!P1<->!P5))':
ls(ulaz)
prikaz(F := P(ulaz))
print(F.ispis())
prikaz(F := optim(F))
print(F.ispis())
print(f'{istinitost(F, P0=False, P3=True, P5=False, P1=True)=}')
print('-' * 60)
for nije_formula in 'P007', 'P1 P2', 'P34<>P56', 'P05', 'P-2':
with LeksičkaGreška: ls(nije_formula)
<file_sep>"""Transpiler Logo -> JavaScript, prema kolokviju 24. veljače 2017."""
from vepar import *
import itertools, math, pathlib, webbrowser, time, random
class T(TipoviTokena):
OTV, ZATV, REPEAT = '[', ']', 'repeat'
class FORWARD(Token): literal, predznak = 'forward', +1
class BACKWARD(Token): literal, predznak = 'backward', -1
class LEFT(Token): literal, predznak = 'left', +1
class RIGHT(Token): literal, predznak = 'right', -1
class PENUP(Token): literal, opkod = 'penup', 'move'
class PENDOWN(Token): literal, opkod = 'pendown', 'line'
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
alias = {'fd': T.FORWARD, 'fw': T.FORWARD,
'bk': T.BACKWARD, 'back': T.BACKWARD, 'bw': T.BACKWARD,
'lt': T.LEFT, 'rt': T.RIGHT, 'pu': T.PENUP, 'pd': T.PENDOWN}
@lexer
def logo(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak.isalpha():
lex * str.isalpha
try: yield lex.token(alias[lex.sadržaj.casefold()])
except KeyError: yield lex.literal(T, case=False)
else: yield lex.literal(T)
### Beskontekstna gramatika
# program -> naredba | program naredba
# naredba -> naredba1 BROJ | PENUP | PENDOWN | REPEAT BROJ OTV program ZATV
# naredba1 -> FORWARD | BACKWARD | LEFT | RIGHT
### Apstraktna sintaksna stabla
# Program: naredbe:[naredba]
# naredba: Pomak: pikseli:BROJ smjer:FORWARD|BACKWARD
# Okret: stupnjevi:BROJ smjer:LEFT|RIGHT
# Ponavljanje: koliko:BROJ naredbe:[naredba]
# Olovka: položaj:PENUP|PENDOWN
class P(Parser):
def program(p) -> 'Program':
naredbe = [p.naredba()]
while not p > KRAJ: naredbe.append(p.naredba())
return Program(naredbe)
def naredba(p) -> 'Pomak|Okret|Olovka|Ponavljanje':
if smjer := p >= {T.FORWARD, T.BACKWARD}:
return Pomak(smjer, p >> T.BROJ)
elif smjer := p >= {T.LEFT, T.RIGHT}:
return Okret(smjer, p >> T.BROJ)
elif položaj := p >= {T.PENUP, T.PENDOWN}:
return Olovka(položaj)
elif p >> T.REPEAT:
koliko = p >> T.BROJ
p >> T.OTV
tijelo = [p.naredba()]
while not p >= T.ZATV: tijelo.append(p.naredba())
return Ponavljanje(koliko, tijelo)
class Program(AST):
naredbe: 'naredba*'
def js(program):
rt.repeat = Registri(prefiks='r', start=1)
yield from [
"var canvas = document.getElementById('output');",
"var ctx = canvas.getContext('2d');",
'var x = canvas.width / 2, y = canvas.height / 2, h = 0;',
'var to = ctx.lineTo;',
'ctx.moveTo(x, y);',
]
for naredba in program.naredbe: yield from naredba.js()
yield 'ctx.stroke();'
class Pomak(AST):
smjer: 'FORWARD|BACKWARD'
pikseli: 'BROJ'
def js(pomak):
d = pomak.smjer.predznak * pomak.pikseli.vrijednost()
yield f'to.apply(ctx, [x-=Math.sin(h)*{d}, y-=Math.cos(h)*{d}]);'
class Okret(AST):
smjer: 'LEFT|RIGHT'
stupnjevi: 'BROJ'
def js(okret):
φ = okret.smjer.predznak * okret.stupnjevi.vrijednost()
yield f'h += {math.radians(φ)};'
class Ponavljanje(AST):
koliko: 'BROJ'
naredbe: 'naredba*'
def js(petlja):
r, n = next(rt.repeat), petlja.koliko.vrijednost()
yield f'for (var {r} = 0; {r} < {n}; {r} ++) '
yield '{'
for naredba in petlja.naredbe: yield from naredba.js()
yield '}'
class Olovka(AST):
položaj: 'PENUP|PENDOWN'
def js(olovka): yield f'to = ctx.{olovka.položaj.opkod}To'
direktorij = pathlib.Path(__file__).parent
def prevedi_string(kôd): return '\n'.join(P(kôd).js())
def prevedi_datoteku(datoteka):
if isinstance(datoteka, str): datoteka = zb[datoteka]
(direktorij/'a.js').write_text(prevedi_string(datoteka.read_text()))
def nacrtaj(ime):
print('Crtam:', ime)
prevedi_datoteku(zb[ime])
webbrowser.open(str(direktorij/'loader.html'))
# print(pathlib.Path(__file__).parent.parent)
zb = {f.stem: f for f in (direktorij/'crteži').iterdir()}
crteži = sorted(zb)
def nacrtaj_sve():
for crtež in crteži:
nacrtaj(crtež)
time.sleep(4)
if __name__ == '__main__':
for i, crtež in enumerate(crteži): print(i, crtež)
utipkano = input('Što da nacrtam? (samo Enter: slučajni odabir, *: sve) ')
if not utipkano: nacrtaj(random.choice(crteži))
elif utipkano == '*': nacrtaj_sve()
elif utipkano.isdecimal(): nacrtaj(crteži[int(utipkano)])
else: print('Ne razumijem.')
# DZ: dodajte REPCOUNT (pogledajte na webu kako se koristi)
# DZ: pogledati http://www.mathcats.com/gallery/15wordcontest.html
# i implementirati neke od tih crteža (za mnoge trebaju varijable!)
# DZ: dodati *varijable i **procedure (pogledati 09_ za inspiraciju)
<file_sep>"""Funkcijski jezik simboličkih definicija primitivno rekurzivnih funkcija.
Slažemo funkcije od osnovnih (tzv. inicijalnih) funkcija:
nulfunkcija: Z(x) := 0
sljedbenik: Sc(x) := x + 1
koordinatna projekcija: Ink(x1,...,xk) := xn
pomoću dva operatora:
kompozicija:
(H o (G1,...,Gl)) (x1,...,xk) := H(G1(x1,...,xk),...,Gl(x1,...xk))
primitivna rekurzija:
(G PR H) (x1,...,xk,0) := G(x1,...xk)
(G PR H) (x1,...,xk,y+1) := H(x1,...,xk,y,(G PR H)(x1,...,xk,y))"""
from vepar import *
kriva_mjesnost = SemantičkaGreška('Mjesnosti ne odgovaraju')
class T(TipoviTokena):
ZAREZ, OTV, ZATV, KOMPOZICIJA, JEDNAKO = ',()o='
PR = 'PR'
class FIME(Token):
"""Ime primitivno rekurzivne funkcije."""
def mjesnost(self): return rt.symtab[self][0]
def izračunaj(self, *argumenti):
k, f = rt.symtab[self]
assert k == self.mjesnost() == len(argumenti)
return f.izračunaj(*argumenti)
class NULFUNKCIJA(Token):
literal = 'Z'
def mjesnost(self): return 1
def izračunaj(self, _): return 0
class SLJEDBENIK(Token):
literal = 'Sc'
def mjesnost(self): return 1
def izračunaj(self, argument): return argument + 1
class KPROJEKCIJA(Token):
"""Koordinatna projekcija, mjesnosti najviše 9."""
def mjesnost(self): return int(self.sadržaj[2])
def izračunaj(self, *argumenti):
n = int(self.sadržaj[1])
return argumenti[n - 1]
@lexer
def pr(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == 'I':
n, k = divmod(lex.prirodni_broj(''), 10)
if 1 <= n <= k: yield lex.token(T.KPROJEKCIJA)
else: raise lex.greška('krivo formirani token Ink')
elif znak.isalpha():
lex * str.isalnum
yield lex.literal_ili(T.FIME)
else: yield lex.literal(T)
### BKG
# program -> definicija | program definicija
# definicija -> FIME JEDNAKO funkcija
# funkcija -> komponenta | komponenta PR komponenta
# komponenta -> lijevo | komponenta KOMPOZICIJA desno
# lijevo -> osnovna | OTV funkcija ZATV
# desno -> osnovna | OTV funkcije ZATV
# osnovna -> FIME | NULFUNKCIJA | SLJEDBENIK | KPROJEKCIJA
# funkcije -> funkcija | funkcije ZAREZ funkcija
class P(Parser):
def program(p) -> 'Memorija':
rt.symtab = Memorija(redefinicija=False)
while not p > KRAJ:
imef = p >> T.FIME
p >> T.JEDNAKO
f = p.funkcija()
rt.symtab[imef] = (f.mjesnost(), f)
if not rt.symtab: raise SemantičkaGreška('Prazan program')
return rt.symtab
def funkcija(p) -> 'PRekurzija|komponenta':
baza = p.komponenta()
if p >= T.PR: return PRekurzija(baza, p.komponenta())
else: return baza
def osnovna(p) -> 'FIME|NULFUNKCIJA|SLJEDBENIK|KPROJEKCIJA':
return p >> {T.FIME, T.NULFUNKCIJA, T.SLJEDBENIK, T.KPROJEKCIJA}
def komponenta(p) -> 'funkcija|osnovna|Kompozicija':
if p >= T.OTV:
t = p.funkcija()
p >> T.ZATV
else: t = p.osnovna()
while p >= T.KOMPOZICIJA: t = Kompozicija(t, p.desno())
return t
def desno(p) -> 'funkcija*|osnovna':
if p >= T.OTV:
rezultat = [p.funkcija()]
while p >= T.ZAREZ: rezultat.append(p.funkcija())
p >> T.ZATV
return rezultat
else: return [p.osnovna()]
### AST
# funkcija: FIME|NULFUNKCIJA|SLJEDBENIK|KPROJEKCIJA:Token
# Kompozicija: lijeva:funkcija desne:[funkcija]
# PRekurzija: baza:funkcija korak:funkcija
class Kompozicija(AST):
lijeva: 'funkcija'
desne: 'funkcija*'
def mjesnost(self):
l = self.lijeva.mjesnost()
if len(self.desne) != l: raise kriva_mjesnost
G1, *ostale = self.desne
k = G1.mjesnost()
if any(G.mjesnost() != k for G in ostale): raise kriva_mjesnost
return k
def izračunaj(self, *argumenti):
međurezultati = (G.izračunaj(*argumenti) for G in self.desne)
return self.lijeva.izračunaj(*međurezultati)
class PRekurzija(AST):
baza: 'funkcija'
korak: 'funkcija'
def mjesnost(self):
k = self.baza.mjesnost()
if self.korak.mjesnost() != k + 2: raise kriva_mjesnost
return k + 1
def izračunaj(self, *argumenti):
*xevi, y = argumenti
z = self.baza.izračunaj(*xevi)
for i in range(y): z = self.korak.izračunaj(*xevi, i, z)
return z
def izračunaj(imef, *argumenti):
k, f = rt.symtab[imef]
if len(argumenti) == k: return f.izračunaj(*argumenti)
else: raise kriva_mjesnost
prikaz(P('''
C01 = Z
C11 = Sc o C01
C21 = Sc o C11
C23 = C21 o I13
C58 = Sc o Sc o Sc o Sc o Sc o Z o I18
'''))
print('C11(5) =', izračunaj('C11', 5))
prikaz(P('''
add2 = I11 PR Sc o I33
mul2 = Z PR add2 o (I13, I33)
pow = Sc o Z PR mul2 o (I13, I33)
'''))
print(b:=3, '^', e:=7, '=', izračunaj('pow', b, e))
# DZ**: dokažite ekvivalentnost ovog sustava i programskog jezika LOOP
<file_sep>"""Jednostavni kalkulator s (približnim) kompleksnim brojevima po IEEE-754.
Ulaz je nula ili više naredbi pridruživanja izraz -> ime,
nakon kojih slijedi izraz čija vrijednost se računa i vraća.
Svaki izraz može koristiti sva prethodno definirana imena.
Prikazano je čitanje decimalnih brojeva, aliasi, postfiksni operatori, ...
Također imamo kompajliranje u jednostavni TAC (two/three-address code)."""
from vepar import *
class T(TipoviTokena):
PLUS, MINUS, PUTA, KROZ, NA, OTV, ZATV, KONJ = '+-*/^()~'
STRELICA = '->'
class BROJ(Token):
def vrijednost(self): return complex(self.sadržaj)
def tac(self):
yield [r:=next(rt.reg), '=', float(self.sadržaj)]
return r
class I(Token):
literal = 'i'
def vrijednost(self): return 1j
def tac(self):
yield [r:=next(rt.reg), '=', self.literal]
return r
class IME(Token):
def vrijednost(self): return rt.okolina[self]
def tac(self):
yield [r:=next(rt.reg), '=', self.sadržaj]
return r
@lexer
def ac(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == '-': yield lex.token(T.STRELICA if lex >= '>' else T.MINUS)
elif znak == '*': yield lex.token(T.NA if lex >= '*' else T.PUTA)
elif znak.isdecimal():
lex * str.isdecimal
if lex >= '.': lex * str.isdecimal
if lex >= 'e':
lex >= '-'
lex + str.isdecimal
yield lex.token(T.BROJ)
elif znak.isalpha():
lex * str.isalnum
yield lex.literal_ili(T.IME)
else: yield lex.literal(T)
### Beskontekstna gramatika
# start -> izraz | izraz STRELICA IME start
# izraz -> član | izraz PLUS član | izraz MINUS član
# član -> faktor | član PUTA faktor | član KROZ faktor
# faktor -> baza | baza NA faktor | MINUS faktor
# baza -> BROJ | IME | I | OTV izraz ZATV | baza KONJ
class P(Parser):
def start(p) -> 'Program':
definicije = []
izraz = p.izraz()
while p >= T.STRELICA:
definicije.append((p >> T.IME, izraz))
izraz = p.izraz()
return Program(definicije, izraz)
def izraz(p) -> 'član|Binarna':
t = p.član()
while op := p >= {T.PLUS, T.MINUS}: t = Binarna(op, t, p.član())
return t
def član(p) -> 'faktor|Binarna':
t = p.faktor()
while op := p >= {T.PUTA, T.KROZ}: t = Binarna(op, t, p.faktor())
return t
def faktor(p) -> 'Unarna|baza|Binarna':
if op := p >= T.MINUS: return Unarna(op, p.faktor())
baza = p.baza()
if op := p >= T.NA: return Binarna(op, baza, p.faktor())
else: return baza
def baza(p) -> 'izraz|BROJ|IME|I|Unarna':
if p >= T.OTV:
trenutni = p.izraz()
p >> T.ZATV
else: trenutni = p >> {T.BROJ, T.IME, T.I}
while op := p >= T.KONJ: trenutni = Unarna(op, trenutni)
return trenutni
### Apstraktna sintaksna stabla
# Program: definicije:[(IME,izraz)] završni:izraz
# izraz: BROJ: Token
# I: Token
# IME: Token
# Binarna: op:PLUS|MINUS|PUTA|KROZ|NA lijevo:izraz desno:izraz
# Unarna: op:MINUS|KONJ ispod:izraz
class Program(AST):
definicije: '(IME,izraz)*'
završni: 'izraz'
def izvrši(program):
rt.okolina = Memorija()
for ime, izraz in program.definicije:
rt.okolina[ime] = izraz.vrijednost()
return program.završni.vrijednost()
def kompajliraj(program):
rt.reg = Registri()
for ime, izraz in program.definicije:
r = yield from izraz.tac()
yield [ime.sadržaj, '=', r]
r = yield from program.završni.tac()
yield ['OUT', r]
class Binarna(AST):
op: 'T'
lijevo: 'izraz'
desno: 'izraz'
def vrijednost(self):
o = self.op
x, y = self.lijevo.vrijednost(), self.desno.vrijednost()
try:
if o ^ T.PLUS: return x + y
elif o ^ T.MINUS: return x - y
elif o ^ T.PUTA: return x * y
elif o ^ T.KROZ: return x / y
elif o ^ T.NA: return x ** y
else: assert False, f'nepokriveni slučaj binarnog operatora {o}'
except ArithmeticError as ex: raise self.iznimka(ex)
def tac(self):
r1 = yield from self.lijevo.tac()
r2 = yield from self.desno.tac()
yield [r:=next(rt.reg), '=', r1, self.op.tip.value, r2]
return r
class Unarna(AST):
op: 'T'
ispod: 'izraz'
def vrijednost(self):
o, z = self.op, self.ispod.vrijednost()
if o ^ T.MINUS: return -z
elif o ^ T.KONJ: return z.conjugate()
else: assert False, f'nepokriveni slučaj unarnog operatora {o}'
def tac(self):
r1 = yield from self.ispod.tac()
yield [r:=next(rt.reg), '=', self.op.tip.value, r1]
return r
def izračunaj(string):
print('-' * 60)
prikaz(program := P(string))
for instrukcija in program.kompajliraj(): print('\t\t', '|', *instrukcija)
print(string.rstrip(), '=', program.izvrši())
izračunaj('2+2*3')
izračunaj('(1+6*i)/(3*i-4)~^2~')
izračunaj('i^i')
izračunaj('''
i+1 -> t
t/2^2^-1 -> a
a^2^2^2^2^0 -> b
b
''')
izračunaj(f'''
8 -> d
10^d -> n
(1+1/n)^n -> e
355/113 -> pi
e^(i*pi) + 1 -> skoro0
skoro0
''')
izračunaj('6.02214076e23->NA 1.6605e-27->u 1/(NA*u)')
with LeksičkaGreška: izračunaj('2e+3')
with GreškaIzvođenja: izračunaj('2+2/0')
with GreškaIzvođenja: izračunaj('0**i')
# DZ: Dodajte implicitno množenje (barem s i, tako da radi npr. 2+3i)
# DZ: Stritkno držanje IEEE-754 zahtijeva i ispravno tretiranje dijeljenja nulom
# (a ako želite biti sasvim compliant, i potenciranja poput 0^-1): učinite to!
<file_sep>from pj import *
from backend import Polinom
class T(enum.Enum):
PLUS = '+'
MINUS = '-'
PUTA = '*'
OTVORENA = '('
ZATVORENA = ')'
class BROJ(Token):
def vrijednost(self): return int(self.sadržaj)
def prevedi(self): return Polinom.konstanta(self.vrijednost())
class X(Token):
literal = 'x'
def prevedi(self): return Polinom.x()
def az_lex(izraz):
lex = Tokenizer(izraz)
for znak in iter(lex.čitaj, ''):
if znak.isdigit():
lex.zvijezda(str.isdigit)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
### Beskontekstna gramatika:
# izraz -> izraz PLUS član | izraz MINUS član | član
# član -> član PUTA faktor | faktor | član faktor *> osim: član BROJ!
# faktor -> MINUS faktor | BROJ | X | X BROJ | OTVORENA izraz ZATVORENA
### Apstraktna sintaksna stabla:
# izraz: BROJ: Token
# X: Token
# Zbroj: lijevo:izraz desno:izraz
# Umnožak: lijevo:izraz desno:izraz
# Suprotan: od:izraz
# Xna: eksponent:BROJ
class T(Parser):
def izraz(self):
t = self.član()
while True:
if self >> T.PLUS: t = Zbroj(t, self.član())
elif self >> T.MINUS: t = Zbroj(t, Suprotan(self.član()))
else: return t
def član(self):
trenutni = self.faktor()
while True:
if self >> T.PUTA or self >= {T.X, T.OTVORENA}:
trenutni = Umnožak(trenutni,self.faktor())
else: return trenutni
def faktor(self):
if self >> T.MINUS: return Suprotan(self.faktor())
elif self >> T.BROJ: return self.zadnji
elif self >> T.X:
x = self.zadnji
if self >= T.BROJ: return Xna(self.pročitaj(T.BROJ))
else: return x
elif self >> T.OTVORENA:
u_zagradi = self.izraz()
self.pročitaj(T.ZATVORENA)
return u_zagradi
else: raise self.greška()
start = izraz
class Zbroj(AST('lijevo desno')):
def prevedi(self): return self.lijevo.prevedi() + self.desno.prevedi()
class Umnožak(AST('lijevo desno')):
def prevedi(self): return self.lijevo.prevedi() * self.desno.prevedi()
class Suprotan(AST('od')):
def prevedi(self): return -self.od.prevedi()
class Xna(AST('eksponent')):
def prevedi(self): return Polinom.x(self.eksponent.vrijednost())
def izračunaj(zadatak):
print(zadatak, '=', P.parsiraj(az_lex(zadatak)).prevedi())
if __name__ == '__main__':
izračunaj('(5+2*8-3)(3-1)-(-4+2*19)')
izračunaj('x-2+5x-(7x-5)')
izračunaj('(((x-2)x+4)x-8)x+7')
izračunaj('xx-2x+3')
izračunaj('(x+1)' * 7)
izračunaj('-'.join(['(x2-2x3-(7x+5))'] * 2))
with očekivano(SintaksnaGreška): izračunaj('(x)x+(x)3')
with očekivano(LeksičkaGreška): izračunaj('x x')
<file_sep>"""Računanje molarne mase kemijskog spoja: po uzoru na kolokvij 7. rujna 2018.
https://web.math.pmf.unizg.hr/~veky/B/IP.k2p.18-09-07.pdf"""
from vepar import *
from backend import referentne_atomske_mase
class T(TipoviTokena):
OOTV, OZATV, UOTV, UZATV = '()[]'
class N(Token):
literal = 'n'
def vrijednost(t):
try: return rt.n
except AttributeError: raise t.nedeklaracija('n nije naveden')
class ATOM(Token):
def masa(t): return rt.tablica[t]
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
@lexer
def kemija(lex):
može_n = False
for znak in lex:
if znak == 'n':
if može_n: yield lex.token(T.N)
else: raise lex.greška('n ne može doći ovdje')
elif znak.isdecimal():
lex.prirodni_broj(znak, nula=False)
yield lex.token(T.BROJ)
elif znak.isupper():
lex >= str.islower
yield lex.token(T.ATOM)
else: yield lex.literal(T)
može_n = znak in {']', ')'}
### BKG
# formula -> skupina | formula skupina
# skupina -> ATOM | ATOM BROJ | zagrade | zagrade BROJ | zagrade N
# zagrade -> OOTV formula OZATV | UOTV formula UZATV
class spoj(Parser):
def formula(p) -> 'Formula':
l = [p.skupina()]
while p > {T.ATOM, T.OOTV, T.UOTV}: l.append(p.skupina())
return Formula(l)
def skupina(p) -> 'Skupina':
if p >= T.OOTV:
što = p.formula()
p >> T.OZATV
elif p >= T.UOTV:
što = p.formula()
p >> T.UZATV
else: što = p >> T.ATOM
return Skupina(što, p >= {T.BROJ, T.N})
### AST
# Formula: skupine:[Skupina]
# Skupina: čega:ATOM|Formula koliko:(BROJ|N)?
class Formula(AST):
skupine: 'Skupina*'
def masa(spoj):
return sum(skupina.ukupno() for skupina in spoj.skupine)
def Mr(spoj, **mase):
del rt.n
if 'n' in mase: rt.n = mase.pop('n')
rt.tablica = Memorija(referentne_atomske_mase | mase)
return spoj.masa()
class Skupina(AST):
čega: 'ATOM|Formula'
koliko: '(BROJ|N)?'
def ukupno(skupina):
m = skupina.čega.masa()
if skupina.koliko: m *= skupina.koliko.vrijednost()
return m
natrijev_trikarbonatokobaltat = spoj('Na3[Co(CO3)3]')
prikaz(natrijev_trikarbonatokobaltat)
print(natrijev_trikarbonatokobaltat.Mr())
for krivo in 'SnABcdefG', 'O Be', 'Es(n)':
with LeksičkaGreška: kemija(krivo)
print()
kemija(']nB')
print('Molarna masa butana je', spoj('CH3(CH2)nCH3').Mr(n=2))
<file_sep>"""Interpreter za pseudokod, s funkcijskim pozivima i dva tipa podataka.
Podržane naredbe:
ako je Uvjet naredba inače naredba ime = izraz
ako je Uvjet naredba Ime = Uvjet
ako nije Uvjet naredba vrati izraz
dok je Uvjet naredba vrati Uvjet
dok nije Uvjet naredba (naredba1, naredba2, ...)
Podržani aritmetički izrazi: Podržani logički uvjeti:
cijeli_broj Istina
ime Laž
ime(argumenti) Ime
izraz + izraz Ime(argumenti)
izraz - izraz Uvjet Ili Uvjet
izraz * izraz izraz < izraz
-izraz izraz = izraz
(izraz)
Program se sastoji od jedne ili više deklaracija funkcija, s ili bez parametara.
Jedna od njih mora biti program(parametri), od nje počinje izvršavanje.
Tipovi varijabli (i povratni tipovi funkcija) se reprezentiraju leksički:
* veliko početno slovo označava logički tip (u Pythonu bool)
* malo početno slovo označava aritmetički tip (u Pythonu int)
Minimalni kontekst je potreban da bismo zapamtili jesmo li trenutno u definiciji
aritmetičke ili logičke funkcije, kako bi naredba "vrati" znala što očekuje.
Dozvoljeni su i (ne uzajamno!) rekurzivni pozivi, tako da se za vrijeme
parsiranja i izvršavanja prati u kojoj smo funkciji.
Memorija se također dinamički preoblikuje: svaka funkcija ima svoj prostor."""
from vepar import *
class T(TipoviTokena):
AKO, DOK, INAČE, VRATI = 'ako', 'dok', 'inače', 'vrati'
JE, NIJE, ILI = 'je', 'nije', 'Ili'
OTV, ZATV, ZAREZ, JEDNAKO, MANJE, PLUS, MINUS, ZVJEZDICA = '(),=<+-*'
class AIME(Token):
def vrijednost(self, mem, unutar): return mem[self]
class LIME(AIME): pass
class BROJ(Token):
def vrijednost(self, mem, unutar): return int(self.sadržaj)
class ISTINA(Token):
literal = 'Istina'
def vrijednost(self, mem, unutar): return True
class LAŽ(Token):
literal = 'Laž'
def vrijednost(self, mem, unutar): return False
@lexer
def pseudokod(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.islower():
lex * str.isalnum
yield lex.literal_ili(T.AIME)
elif znak.isupper():
lex * str.isalnum
yield lex.literal_ili(T.LIME)
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak == '#':
lex - '\n'
lex.zanemari()
else: yield lex.literal(T)
### ne sasvim BKG
# program -> funkcija | funkcija program
# funkcija -> ime OTV parametri? ZATV JEDNAKO naredba
# parametri -> ime | parametri ZAREZ ime
# ime -> AIME | LIME
# naredba -> pridruži | OTV ZATV | OTV naredbe ZATV | VRATI argument
# | (AKO|DOK) (JE|NIJE) log naredba | AKO JE log naredba INAČE naredba
# naredbe -> naredba | naredbe ZAREZ naredba
# pridruži -> AIME JEDNAKO aritm | LIME JEDNAKO log
# log -> disjunkt | log ILI disjunkt
# disjunkt -> aritm MANJE aritm | aritm JEDNAKO aritm
# | ISTINA | LAŽ | LIME | LIME poziv
# aritm -> član | aritm PLUS član | aritm MINUS član
# član -> faktor | član ZVJEZDICA faktor
# faktor -> BROJ | AIME | AIME poziv | OTV aritm ZATV | MINUS faktor
# poziv -> OTV ZATV | OTV argumenti ZATV
# argumenti -> argument | argumenti ZAREZ argument
# argument -> aritm |! log [!KONTEKST]
class P(Parser):
def program(p) -> 'Memorija':
p.funkcije = Memorija(redefinicija=False)
while not p > KRAJ:
funkcija = p.funkcija()
p.funkcije[funkcija.ime] = funkcija
return p.funkcije
def funkcija(p) -> 'Funkcija':
atributi = p.imef, p.parametrif = p.ime(), p.parametri()
p >> T.JEDNAKO
return Funkcija(*atributi, p.naredba())
def ime(p) -> 'AIME|LIME': return p >> {T.AIME, T.LIME}
def parametri(p) -> 'ime*':
p >> T.OTV
if p >= T.ZATV: return []
param = [p.ime()]
while p >= T.ZAREZ: param.append(p.ime())
p >> T.ZATV
return param
def naredba(p) -> 'grananje|petlja|blok|Vrati|Pridruživanje':
if p > T.AKO: return p.grananje()
elif p > T.DOK: return p.petlja()
elif p > T.OTV: return p.blok()
elif p >= T.VRATI: return Vrati(p.tipa(p.imef))
else:
ime = p.ime()
p >> T.JEDNAKO
return Pridruživanje(ime, p.tipa(ime))
def tipa(p, ime) -> 'aritm|log':
if ime ^ T.AIME: return p.aritm()
elif ime ^ T.LIME: return p.log()
else: assert False, f'Nepoznat tip od {ime}'
def grananje(p) -> 'Grananje':
p >> T.AKO
je = p > T.JE
atributi = p >> {T.JE, T.NIJE}, p.log(), p.naredba()
if je and p >= T.INAČE: inače = p.naredba()
else: inače = Blok([])
return Grananje(*atributi, inače)
def petlja(p) -> 'Petlja':
p >> T.DOK
return Petlja(p >> {T.JE, T.NIJE}, p.log(), p.naredba())
def blok(p) -> 'Blok|naredba':
p >> T.OTV
if p >= T.ZATV: return Blok([])
n = [p.naredba()]
while p >= T.ZAREZ and not p > T.ZATV: n.append(p.naredba())
p >> T.ZATV
return Blok.ili_samo(n)
def log(p) -> 'Disjunkcija|disjunkt':
disjunkti = [p.disjunkt()]
while p >= T.ILI: disjunkti.append(p.disjunkt())
return Disjunkcija.ili_samo(disjunkti)
def disjunkt(p) -> 'možda_poziv|Usporedba':
if log := p >= {T.ISTINA, T.LAŽ, T.LIME}: return p.možda_poziv(log)
return Usporedba(p.aritm(), p >> {T.JEDNAKO, T.MANJE}, p.aritm())
def možda_poziv(p, ime) -> 'Poziv|ime':
if ime in p.funkcije:
funkcija = p.funkcije[ime]
return Poziv(funkcija, p.argumenti(funkcija.parametri))
elif ime == p.imef:
return Poziv(nenavedeno, p.argumenti(p.parametrif))
else: return ime
def argumenti(p, parametri) -> 'tipa*':
arg = []
p >> T.OTV
for i, parametar in enumerate(parametri):
if i: p >> T.ZAREZ
arg.append(p.tipa(parametar))
p >> T.ZATV
return arg
def aritm(p) -> 'Zbroj|član':
članovi = [p.član()]
while ...:
if p >= T.PLUS: članovi.append(p.član())
elif p >= T.MINUS: članovi.append(Suprotan(p.član()))
else: return Zbroj.ili_samo(članovi)
def član(p) -> 'Umnožak|faktor':
faktori = [p.faktor()]
while p >= T.ZVJEZDICA: faktori.append(p.faktor())
return Umnožak.ili_samo(faktori)
def faktor(p) -> 'Suprotan|možda_poziv|aritm|BROJ':
if p >= T.MINUS: return Suprotan(p.faktor())
elif aritm := p >= T.AIME: return p.možda_poziv(aritm)
elif p >= T.OTV:
u_zagradi = p.aritm()
p >> T.ZATV
return u_zagradi
else: return p >> T.BROJ
def izvrši(funkcije, *argv):
print('Program je vratio:', funkcije['program'].pozovi(argv))
### AST
# Funkcija: ime:AIME|LIME parametri:[IME] tijelo:naredba
# naredba: Grananje: istinitost:JE|NIJE uvjet:log onda:naredba inače:naredba
# Petlja: istinitost:JE|NIJE uvjet:log tijelo:naredba
# Blok: naredbe:[naredba]
# Pridruživanje: ime:AIME|LIME pridruženo:izraz
# Vrati: što:izraz
# izraz: log: Disjunkcija: disjunkti:[log]
# Usporedba: lijevo:aritm relacija:MANJE|JEDNAKO desno:aritm
# aritm: Zbroj: pribrojnici:[aritm]
# Suprotan: od:aritm
# Umnožak: faktori:[aritm]
# Poziv: funkcija:Funkcija? argumenti:[izraz]
class Funkcija(AST):
ime: 'IME'
parametri: 'IME*'
tijelo: 'naredba'
def pozovi(funkcija, argumenti):
lokalni = Memorija(zip(funkcija.parametri, argumenti))
try: funkcija.tijelo.izvrši(mem=lokalni, unutar=funkcija)
except Povratak as exc: return exc.preneseno
else: raise GreškaIzvođenja(f'{funkcija.ime} nije ništa vratila')
class Poziv(AST):
funkcija: 'Funkcija?'
argumenti: 'izraz*'
def vrijednost(poziv, mem, unutar):
pozvana = poziv.funkcija
if pozvana is nenavedeno: pozvana = unutar # rekurzivni poziv
argumenti = [a.vrijednost(mem, unutar) for a in poziv.argumenti]
return pozvana.pozovi(argumenti)
def za_prikaz(poziv): # samo za ispis, da se ne ispiše čitava funkcija
r = {'argumenti': poziv.argumenti}
if poziv.funkcija is nenavedeno: r['*rekurzivni'] = True
else: r['*ime'] = poziv.funkcija.ime
return r
def ispunjen(ast, mem, unutar):
u = ast.uvjet.vrijednost(mem, unutar)
if ast.istinitost ^ T.JE: return u
elif ast.istinitost ^ T.NIJE: return not u
else: assert False, f'Tertium non datur! {ast.istinitost}'
class Grananje(AST):
istinitost: 'JE|NIJE'
uvjet: 'log'
onda: 'naredba'
inače: 'naredba'
def izvrši(grananje, mem, unutar):
if ispunjen(grananje, mem, unutar): grananje.onda.izvrši(mem, unutar)
else: grananje.inače.izvrši(mem, unutar)
class Petlja(AST):
istinitost: 'JE|NIJE'
uvjet: 'log'
tijelo: 'naredba'
def izvrši(petlja, mem, unutar):
while ispunjen(petlja, mem, unutar): petlja.tijelo.izvrši(mem, unutar)
class Blok(AST):
naredbe: 'naredba*'
def izvrši(blok, mem, unutar):
for naredba in blok.naredbe: naredba.izvrši(mem, unutar)
class Pridruživanje(AST):
ime: 'IME'
pridruženo: 'izraz'
def izvrši(self, mem, unutar):
mem[self.ime] = self.pridruženo.vrijednost(mem, unutar)
class Vrati(AST):
što: 'izraz'
def izvrši(self, mem, unutar):
raise Povratak(self.što.vrijednost(mem, unutar))
class Disjunkcija(AST):
disjunkti: 'log*'
def vrijednost(disjunkcija, mem, unutar):
return any(disjunkt.vrijednost(mem, unutar)
for disjunkt in disjunkcija.disjunkti)
class Usporedba(AST):
lijevo: 'aritm'
relacija: 'MANJE|JEDNAKO'
desno: 'aritm'
def vrijednost(usporedba, mem, unutar):
l = usporedba.lijevo.vrijednost(mem, unutar)
d = usporedba.desno.vrijednost(mem, unutar)
if usporedba.relacija ^ T.JEDNAKO: return l == d
elif usporedba.relacija ^ T.MANJE: return l < d
else: assert False, f'Nepoznata relacija {usporedba.relacija}'
class Zbroj(AST):
pribrojnici: 'aritm*'
def vrijednost(zbroj, mem, unutar):
return sum(p.vrijednost(mem, unutar) for p in zbroj.pribrojnici)
class Suprotan(AST):
od: 'aritm'
def vrijednost(self, mem, unutar): return -self.od.vrijednost(mem, unutar)
class Umnožak(AST):
faktori: 'aritm*'
def vrijednost(umnožak, mem, unutar):
return math.prod(f.vrijednost(mem, unutar) for f in umnožak.faktori)
class Povratak(NelokalnaKontrolaToka): """Signal koji šalje naredba vrati."""
proba = P('program() = ako je Istina vrati 1 inače vrati 2')
prikaz(proba, 5)
izvrši(proba)
with SemantičkaGreška: P('f(x)=() f(x)=()')
with SintaksnaGreška:
P('f(x) = vrati 7 program() = vrati f(Laž)')
with SintaksnaGreška: izvrši(P('program() = vrati2'))
with LeksičkaGreška: P('program() = vrati 007')
modul = '''
Negacija(V) = ako je V vrati Laž inače vrati Istina
Neparan(x) = (
N = Laž,
dok nije x = 0 (
x = x - 1,
N = Negacija(N),
),
vrati N
)
'''
suma_faktorijela = P(modul + '''
fakt(x) = (
f = 1,
dok nije x = 0 (
f = f*x,
x = x-1
),
vrati f
)
program() = (
s = 0,
t = 0,
dok je t < 9 (
ako je Neparan(t) s = s + fakt(t),
t = t + 1
),
vrati s
)
''')
prikaz(suma_faktorijela)
izvrši(suma_faktorijela)
tablice_istinitosti = P(modul + '''
Konjunkcija(P, Q) = ako je P vrati Q inače vrati P
Disjunkcija(P, Q) = ako je P vrati P inače vrati Q
Kondicional(P, Q) = vrati Disjunkcija(Negacija(P), Q)
Bikondicional(P, Q) = vrati Konjunkcija(Kondicional(P, Q), Kondicional(Q, P))
Multiplex(m, P, Q) = # rudimentarni switch/case
ako je m = 1 vrati Konjunkcija(P, Q) inače
ako je m = 2 vrati Disjunkcija(P, Q) inače
ako je m = 3 vrati Kondicional(P, Q) inače
ako je m = 4 vrati Bikondicional(P, Q) inače
ako je m = 5 vrati Negacija(P) inače
vrati Laž
broj(Bool) = ako je Bool vrati 1 inače vrati 0
dodaj(lista, Bool) = (
bit = broj(Bool),
lista = lista * 10 + bit,
lista = lista * 10 + 8,
vrati lista
)
program(m) = (
lista = 6,
b = 0,
dok je b < 4 (
Prvi = Negacija(b < 2),
Drugi = Neparan(b),
Rezultat = Multiplex(m, Prvi, Drugi),
lista = dodaj(lista, Rezultat),
b = b + 1
),
vrati lista + 1
)
''')
print()
prikaz(tablice_istinitosti)
izvrši(tablice_istinitosti, 3) # poziv iz komandne linije, prijenos m=3
print()
rekurzivna = P('''
fakt(n) = ako je n = 0 vrati 1 inače vrati n*fakt(n-1)
program() = vrati fakt(7)
''')
prikaz(rekurzivna)
izvrši(rekurzivna)
# DZ: dodajte određenu petlju: za ime = izraz .. izraz naredba
# DZ*: dodajte late binding, da se modul i program mogu zasebno kompajlirati
<file_sep># Interpretacija programa
Repozitorij za kod koji ćemo pisati.
Savjetujem da skinete lokalno čitav repozitorij, te dalje radite na lokalnoj
kopiji. Dobro je stvoriti posebnu datoteku za "šaranje".
Ovdje ću dodavati još koda kako kolegij bude napredovao.
<file_sep>Semantička analiza
==================
Već smo vidjeli kako deklarirati ASTove u poglavlju o sintaksnoj analizi. Ponovimo: pišemo ih kao potklase veprove klase ``AST``, navodeći odmah ispod toga deklaracije njihovih atributa. Primjer::
class Petlja(AST):
uvjet: 'logički_izraz'
tijelo: 'naredba|Blok'
Anotacije (ovo iza dvotočke u deklaracijama) mogu biti proizvoljne, vepar ih ne čita. Pristojno je napisati ili varijablu gramatike (metodu parsera) koja vraća nešto što može doći na to mjesto, ili tip (klasu) ASTa koji se direktno može tamo staviti. Anotacije treba pisati kao stringove, osim ako ćete jako paziti na poredak tako da ne koristite ništa što već nije definirano. (Možete i ``from __future__ import annotations`` na početku ako ne želite paziti na to.) Kao što rekoh, vepra nije briga što ćete tamo napisati: ``atribut: ...`` je sasvim u redu ako vam se ne da razmišljati, ali slično kao za BKG, pažljiv dizajn ASTova i njegova dokumentacija kroz tipove atributa vrlo je korisna stepenica u uspješnoj implementaciji semantičkog analizatora.
Krenuvši od korijena (to je AST kojeg stvara početna varijabla gramatike) i slijedeći atribute, prije ili kasnije doći ćemo do *listova*, što su najčešće tokeni. Dualno, možemo zamisliti ASTove kao nekakve obrasce u koje parser slaže tokene koje lexer generira, kako bi prikazao sintaksnu strukturu programa. Obilascima ASTova (koristeći najčešće rekurzivne metode) sada možemo učiniti sljedeći korak i našem programu "udahnuti dušu" odnosno dati mu nekakvu semantiku.
S ASTovima možemo raditi praktički što god želimo: pretvarati ih u jednostavnije ili po nekom drugom kriteriju bolje ASTove (optimizacija), preslikavati ih u nekakvu međureprezentaciju, bajtkod ili čak strojni kod (kompilacija), ili ih direktno preslikavati u stvarni svijet efekata i izlaznih vrijednosti (izvršavanje/evaluacija). Ovo je mjesto gdje vepar prestaje biti rigidni *framework* i postaje biblioteka raznih alata za koje se pokazuje da su često korisni u semantičkim analizama mnogih jezika. Događa se inverzija kontrole: dok je pri leksičkoj i sintaksnoj analizi vepar sam po potrebi pozivao lexer i metode parsera, i od njih slagao ASTove, sada ASTovi sami brinu za svoju kontrolu toka, eventualno koristeći veprove strukture i pozivajući njegove pomoćne funkcije tamo gdje je potrebno.
Tako ovdje samo navodimo dobre prakse za neke najčešće obrasce semantičke analize; prostor mogućnosti ovdje je daleko veći nego što se to u ovakvom tutorialu može opisati.
Evaluacija
----------
Metode pišemo na pojedinim ASTovima, pozivajući (iste ili različite) metode na drugim ASTovima koji su najčešće neposredni potomci početnog, sve dok ne dođemo do poziva metode na tokenu u listu ASTa, koja predstavlja bazu rekurzije. Recimo, u klasi ``Zbroj`` mogli bismo napisati metodu ::
def vrijednost(self):
return self.lijevo.vrijednost() + self.desno.vrijednost()
i sasvim analogno (napišite sami!) za ``Umnožak``, što bi zajedno s metodom ``vrijednost`` na ``BROJ``\ evima (koju smo napisali u poglavlju o leksičkoj analizi) dalo da napokon možemo dobiti ::
>>> P('5+8*12').vrijednost()
101
Prilično analogno, samo bez povratne vrijednosti, možemo *izvršavati* naredbe u programima. Recimo, ``Petlja`` definirana na početku ovog poglavlja mogla bi imati metodu ::
def izvrši(self):
while self.uvjet.vrijednost(): self.tijelo.izvrši()
(pod pretpostavkom da sve što metoda parsera ``logički_izraz`` može vratiti ima metodu ``vrijednost`` koja vraća ``bool``, te da svaka ``naredba``, kao i ``Blok``, imaju metodu ``izvrši``). Implementacija bloka naredbi bila bi u tom slučaju ::
class Blok(AST):
naredbe: 'naredba*'
def izvrši(self):
for naredba in self.naredbe(): naredba.izvrši()
Memorija
--------
Što ako u izrazu imamo varijable? Treba nam (a) neki način da im pridijelimo vrijednost (naredbom pridruživanja, ili prijenosom izvana), (b) način da te vrijednosti učinimo dostupnom svakoj metodi ``vrijednost`` na svim ASTovima i Tokenima, te (c) način da vepru kažemo da prijavi suvislu grešku u slučaju nepostojanja (ili, u nekim slučajevima, redefinicije) tražene varijable.
Za (a) možemo koristiti Pythonov rječnik, ali u tom slučaju je komplicirano riješiti (c) (opet, zbog inverzije kontrole; vepar ne zna ništa o tome što mi radimo s tim rječnikom). Također, nezgodno je uvijek misliti jesu li ključevi u rječniku tokeni ili njihovi sadržaji (ponekad je bolje jedno, ponekad drugo). Sve te (i druge) probleme rješava ``Memorija``. To je klasa čije instance su specijalno prilagođene za praćenje metapodataka (vrijednosti, tipova, ...) raznih tokena, bilo direktno bilo po sadržaju. Pri konstrukciji možemo (a i ne moramo) navesti inicijalne podatke u obliku rječnika, druge memorije, ili čak objekta poput ``zip(imena, vrijednosti)``. Također možemo navesti opciju ``redefinicija=False`` (podrazumijevano je ``True``), čime zabranjujemo *rebinding* (ponovo pridruživanje) tokenima koji već postoje u memoriji. Naravno, ako su metapodaci promjenjivi Pythonovi objekti, možemo ih mijenjati bez obzira što smo tu naveli.
Kako riješiti (b)? *Low-tech* rješenje je jednostavno memoriju, jednom kad je konstruiramo, poslati kao argument u svaki poziv. To je sasvim izvedivo, ali zahtijeva puno mijenjanja (posebno ako se kasnije sjetimo da još nešto trebamo prenijeti na isti način), a i djeluje pomalo šašavo pisati da ``T.BROJ.vrijednost`` prima argument koji uopće ne koristi. Za to možemo koristiti `rt` (od *runtime*), veprov globalni objekt koji u svojim atributima drži sve potrebno za izvršavanje, pa tako i memoriju ako nam je potrebna. Dakle, samo treba negdje pri početku izvršavanja inicijalizirati ``rt.mem = Memorija()``, realizirati nekakvu naredbu pridruživanja poput ::
class Pridruživanje(AST):
čemu: 'IME'
pridruženo: 'izraz'
def izvrši(self):
rt.mem[self.čemu] = self.pridruženo.vrijednost()
i klasi ``T.IME`` dodati metodu ::
def vrijednost(t): return rt.mem[t]
Optimizacija
------------
Jedna konceptualno jednostavna operacija na ASTovima je optimizacija: od jednog ASTa napravimo drugi, najčešće tako da uklonimo neke nepotrebne dijelove. Recimo, uz globalnu definiciju ``nula = Token(T.BROJ, '0')``, mogli bismo u klasi ``Zbroj`` napisati ::
def optim(self):
if self.lijevo == nula: return self.desno.optim()
elif self.desno == nula: return self.lijevo.optim()
else: return self
ali to **nije dobra** metoda za optimizaciju, jer gleda samo "plitko" izraze do dubine 1: recimo, neće optimizirati ``(0+0)+5``. Bolje je rekurzivno optimizirati prvo potomke, što može otkriti neke obrasce koje možemo iskoristiti na osnovnoj razini::
def optim(self):
ol, od = self.lijevo.optim(), self.desno.optim()
if ol == nula: return od
elif od == nula: return ol
else: return Zbroj(ol, od)
Alternativno, možemo i *mijenjati* ASTove direktno, što ima svoje prednosti poput čuvanja podataka o rasponu pojedinih ASTova, ali ima i mane jer je teže pisati rekurzivne funkcije koje mijenjaju svoje argumente. To se obično koristi u složenijim jezicima, gdje inkrementalna kompleksnost takvog postupka nije prevelika, a ogromnu većinu "gornjih slojeva" nećemo mijenjati optimizacijom, pa nema smisla da ih prepisujemo svaki put (tzv. lokalni ili *peephole* optimizatori).
<file_sep>from collections import ChainMap
from ASTs import *
class C0Parser(Parser):
def prog(self):
if self >> {Tokeni.INT, Tokeni.BOOL, Tokeni.STRING, Tokeni.CHAR, Tokeni.VOID}:
tip = self.zadnji
ime = self.pročitaj(Tokeni.IDENTIFIER)
self.pročitaj(Tokeni.OOTV)
varijable = []
while not self >> Tokeni.OZATV:
if (not self >> {Tokeni.INT, Tokeni.BOOL, Tokeni.STRING, Tokeni.CHAR}):
raise SintaksnaGreška("pogrešna inicijalizacija")
tipVar = self.zadnji
imeVar = self.pročitaj(Tokeni.IDENTIFIER)
if (not self.pogledaj() ** Tokeni.OZATV):
self.pročitaj(Tokeni.ZAREZ)
varijable.append(Varijabla(tipVar, imeVar))
if (self.pogledaj() ** Tokeni.SEP): #samo deklaracija funkcije
self.pročitaj(Tokeni.SEP)
return DeklaracijaFunkcije(tip, ime, varijable)
self.pročitaj(Tokeni.VOTV)
tijelo = []
while not self >> Tokeni.VZATV: tijelo.append(self.stmt())
return DefinicijaFunkcije(tip, ime, varijable, tijelo)
def stmt(self):
if self >> Tokeni.IF:
self.pročitaj(Tokeni.OOTV)
uvjet = self.expression()
self.pročitaj(Tokeni.OZATV)
tijeloIf = self.stmt()
idući = self.pogledaj()
if idući ** Tokeni.ELSE:
self.pročitaj(Tokeni.ELSE)
tijeloElse = self.stmt()
return IfElse(uvjet, tijeloIf, tijeloElse)
else:
return If(uvjet, tijeloIf)
if self >> Tokeni.WHILE:
self.pročitaj(Tokeni.OOTV)
uvjet = self.expression()
self.pročitaj(Tokeni.OZATV)
tijeloWhile = self.stmt()
return While(uvjet, tijeloWhile)
if self >> Tokeni.FOR:
self.pročitaj(Tokeni.OOTV)
deklaracija = ""
if (not self.pogledaj() ** Tokeni.SEP):
deklaracija = self.simple()
self.pročitaj(Tokeni.SEP)
uvjet = self.expression()
self.pročitaj(Tokeni.SEP)
inkrement = ""
if (not self.pogledaj() ** Tokeni.OZATV):
inkrement = self.simple()
self.pročitaj(Tokeni.OZATV)
tijeloFor = self.stmt()
return For(deklaracija, uvjet, inkrement, tijeloFor)
if self >> Tokeni.RETURN:
povratnaVrijednost = ""
if (not self.pogledaj() ** Tokeni.SEP):
povratnaVrijednost = self.expression()
self.pročitaj(Tokeni.SEP)
return Return(povratnaVrijednost)
if self >> Tokeni.BREAK:
br = self.zadnji
self.pročitaj(Tokeni.SEP)
return br
if self >> Tokeni.CONTINUE:
con = self.zadnji
self.pročitaj(Tokeni.SEP)
return con
if self >> Tokeni.ASSERT:
self.pročitaj(Tokeni.OOTV)
izraz = self.expression()
self.pročitaj(Tokeni.OZATV)
self.pročitaj(Tokeni.SEP)
return Assert(izraz)
if self >> Tokeni.ERROR:
self.pročitaj(Tokeni.OOTV)
izraz = self.expression()
self.pročitaj(Tokeni.OZATV)
self.pročitaj(Tokeni.SEP)
return Error(izraz)
if self >> Tokeni.VOTV:
blok = []
while not self >> Tokeni.VZATV: blok.append(self.stmt())
return Blok(blok)
else:
simple = self.simple()
self.pročitaj(Tokeni.SEP)
return simple
def simple(self):
if self >> primitivniTipovi:
tip = self.zadnji
varijabla = self.pročitaj(Tokeni.IDENTIFIER)
if self >> Tokeni.ASSIGN:
var = Varijabla(tip, varijabla)
desna = self.expression()
return Deklaracija(var, desna)
else:
return Varijabla(tip, varijabla)
else:
return self.expression()
def expression(self):
trenutni = self.logički()
while True:
if self >> Tokeni.CONDQ:
prviUvjet = self.expression()
self.pročitaj(Tokeni.CONDDOT)
drugiUvjet = self.expression()
trenutni = TernarniOperator(trenutni, prviUvjet, drugiUvjet)
else: return trenutni
else:
self.greška()
def logički(self):
trenutni = self.bitwise()
while True:
if self >> {Tokeni.LAND, Tokeni.LOR}:
operacija = self.zadnji
trenutni = LogičkaOperacija(trenutni, self.bitwise(), operacija)
else: return trenutni
def bitwise(self):
trenutni = self.equality()
while True:
if self >> {Tokeni.BITAND, Tokeni.BITEXCLOR, Tokeni.BITOR}:
operacija = self.zadnji
trenutni = BitwiseOperacija(trenutni, self.equality(), operacija)
else: return trenutni
def equality(self):
trenutni = self.comparison()
while True:
if self >> {Tokeni.EQ, Tokeni.DISEQ}:
operacija = self.zadnji
trenutni = Equality(trenutni, self.comparison(), operacija)
else: return trenutni
def comparison(self):
trenutni = self.shifts()
while True:
if self >> {Tokeni.LESS, Tokeni.LESSEQ, Tokeni.GRT, Tokeni.GRTEQ}:
operacija = self.zadnji
trenutni = Comparison(trenutni, self.shifts(), operacija)
else: return trenutni
def shifts(self):
trenutni = self.add()
while True:
if self >> {Tokeni.LSHIFT, Tokeni.RSHIFT}:
operacija = self.zadnji
trenutni = BinarnaOperacija(trenutni, self.add(), operacija)
else: return trenutni
def add(self):
trenutni = self.factor()
while True:
if self >> {Tokeni.PLUS, Tokeni.MINUS}:
operacija = self.zadnji
trenutni = BinarnaOperacija(trenutni, self.factor(), operacija)
else: return trenutni
def factor(self):
trenutni = self.assign()
while True:
if self >> {Tokeni.ZVJ, Tokeni.SLASH, Tokeni.MOD}:
operacija = self.zadnji
trenutni = BinarnaOperacija(trenutni, self.assign(), operacija)
else: return trenutni
def assign(self):
trenutni = self.allocate()
while True:
if self >> assignOperators:
operacija = self.zadnji
trenutni = Assignment(trenutni, self.expression(), operacija)
else: break
return trenutni
def allocate(self):
trenutni = self.allocarray()
if self >> Tokeni.ALLOC:
self.pročitaj(Tokeni.OOTV)
if self >> primitivniTipovi:
tip = self.zadnji
self.pročitaj(Tokeni.OZATV)
trenutni = Alociraj(tip)
else:
self.zadnji.neočekivan()
return trenutni
def allocarray(self):
trenutni = self.unaries()
if self >> Tokeni.ALLOCA:
self.pročitaj(Tokeni.OOTV)
if self >> primitivniTipovi:
tip = self.zadnji
self.pročitaj(Tokeni.ZAREZ)
koliko = self.expression()
self.pročitaj(Tokeni.OZATV)
trenutni = AlocirajArray(tip, koliko)
else:
self.zadnji.neočekivan()
return trenutni
def unaries(self):
if self >> Tokeni.USKL:
iza = self.expression()
return Negacija(iza)
if self >> Tokeni.TILDA:
iza = self.expression()
return Tilda(iza)
if self >> Tokeni.MINUS:
iza = self.expression()
return Minus(iza)
if self >> Tokeni.ZVJ:
iza = self.base()
trenutni = Dereferenciraj(iza)
return trenutni
baza = self.base()
return baza
def base(self):
if self >> Tokeni.OOTV:
u_zagradi = self.expression()
self.pročitaj(Tokeni.OZATV)
return u_zagradi
if self >> Tokeni.IDENTIFIER:
#može biti identifier, može biti poziv funkcije ako slijedi otvorena zagrada iza
ime = self.zadnji
if (self.pogledaj() ** Tokeni.OOTV):
self.pročitaj(Tokeni.OOTV)
varijable = []
while not self >> Tokeni.OZATV:
imeVar = self.expression()
if (not self.pogledaj() ** Tokeni.OZATV):
self.pročitaj(Tokeni.ZAREZ)
varijable.append(imeVar)
return IzvrijedniFunkciju(ime, varijable)
if (self.pogledaj() ** Tokeni.INCR or self.pogledaj() ** Tokeni.DECR):
trenutni = self.zadnji
while True:
if self >> Tokeni.INCR:
trenutni = Inkrement(ime)
elif self >> Tokeni.DECR:
trenutni = Dekrement(ime)
else:
break
return trenutni
if self >> Tokeni.UOTV:
trenutni = self.expression()
self.pročitaj(Tokeni.UZATV)
trenutni = Dohvati(ime, trenutni)
return trenutni
else:
return ime
if self >> Tokeni.PRINT:
#print funkcija
self.pročitaj(Tokeni.OOTV)
varijable = []
while not self >> Tokeni.OZATV:
imeVar = self.expression()
if (not self.pogledaj() ** Tokeni.OZATV):
self.pročitaj(Tokeni.ZAREZ)
varijable.append(imeVar)
return PrintFunkcija(varijable)
if self >> osnovniIzrazi:
trenutni = self.zadnji
return trenutni
def start(self):
naredbe = [self.prog()]
while not self >> E.KRAJ:
naredbe.append(self.prog())
return Program(naredbe)<file_sep>from util import *
class PotisniAutomat(types.SimpleNamespace):
"""Automat koji prepoznaje beskontekstni jezik."""
@classmethod
def iz_komponenti(klasa,
stanja, abeceda, abeceda_stoga, prijelaz, početno, završna):
"""Relacijska definicija: Δ⊆Q×(Σ∪{ε})×(Γ∪{ε})×Q×(Γ∪{ε})"""
assert abeceda
assert početno in stanja
assert završna <= stanja
assert relacija(prijelaz, stanja, ε_proširenje(abeceda),
ε_proširenje(abeceda_stoga), stanja, ε_proširenje(abeceda_stoga))
return klasa(**vars())
@classmethod
def iz_funkcije(klasa,
stanja, abeceda, abeceda_stoga, f_prijelaza, početno, završna):
"""Funkcijska definicija: δ:Q×(Σ∪{ε})×(Γ∪{ε})→℘(Q×(Γ∪{ε}))
Sipser page 113 definition 2.13"""
prijelaz = relacija_iz_funkcije(f_prijelaza)
return klasa.iz_komponenti(
stanja, abeceda, abeceda_stoga, prijelaz, početno, završna)
@classmethod
def iz_tablice(klasa, tablica):
"""Parsiranje tabličnog zapisa potisnog automata.
Pogledati funkciju util.parsiraj_tablicu_PA za detalje."""
return klasa.iz_komponenti(*parsiraj_tablicu_PA(tablica))
@classmethod
def iz_nedeterminističnog_konačnog_automata(klasa, nka):
"""Pretvorba iz nedeterminističnog konačnog automata u potisni."""
Q, Σ, Δ, q0, F = nka.komponente
ΔP = {(q, α, ε, p, ε) for (q, α, p) in Δ}
return klasa.iz_komponenti(Q, Σ, set(), ΔP, q0, F)
@property
def funkcija_prijelaza(automat):
"""Relacija prijelaza pretvorena u funkciju."""
return funkcija_iz_relacije(automat.prijelaz, automat.stanja,
ε_proširenje(automat.abeceda), ε_proširenje(automat.abeceda_stoga))
@property
def komponente(automat):
"""Relacijska definicija - rastav u šestorku."""
return (automat.stanja, automat.abeceda, automat.abeceda_stoga,
automat.prijelaz, automat.početno, automat.završna)
def prihvaća(automat, riječ):
"""Prihvaća li automat zadanu riječ?
Poluodlučivo: može zapeti u beskonačnoj petlji ako ne prihvaća."""
red = collections.deque([(riječ, automat.početno, None)])
while red:
riječ, stanje, stog = red.popleft()
if not riječ and stanje in automat.završna:
return True
for polazno, znak, uzmi, dolazno, stavi in automat.prijelaz:
if stanje != polazno: continue
if znak == ε: nova_riječ = riječ
elif riječ and riječ[0] == znak: nova_riječ = riječ[1:]
else: continue
if uzmi == ε: novi_stog = stog
elif stog and stog[~0] == uzmi: novi_stog = stog[0]
else: continue
if stavi != ε: novi_stog = novi_stog, stavi
red.append((nova_riječ, dolazno, novi_stog))
return False
def crtaj(automat):
"""Ispisuje na ekran dijagram automata u DOT formatu.
Dobiveni string može se kopirati u sandbox.kidstrythisathome.com/erdos
ili u www.webgraphviz.com."""
print(DOT_PA(automat))
# TODO: pretvorba PA -> JPA -> BKG, BKG -> (J)PA
<file_sep>"""Aritmetika na N, s razlikom što su + i * lijevo asocirani višemjesni.
Uz implicitno množenje ako desni faktor počinje zagradom (npr. 2(3+1)=8).
Implementiran je i optimizator, baš kao u originalnom aritmetika_N.py."""
from vepar import *
from backend import Python_eval
class T(TipoviTokena):
PLUS, PUTA, OTVORENA, ZATVORENA = '+*()'
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
def optim(t): return t
@lexer
def an(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
### Beskontekstna gramatika
# izraz -> član | izraz PLUS član
# član -> faktor | član PUTA faktor | član zagrade
# faktor -> BROJ | zagrade
# zagrade -> OTVORENA izraz ZATVORENA
class P(Parser):
def izraz(p) -> 'Zbroj|član':
trenutni = [p.član()]
while p >= T.PLUS: trenutni.append(p.član())
return Zbroj.ili_samo(trenutni)
def član(p) -> 'Umnožak|faktor':
trenutni = [p.faktor()]
while p >= T.PUTA or p > T.OTVORENA:
trenutni.append(p.faktor())
return Umnožak.ili_samo(trenutni)
def faktor(p) -> 'BROJ|izraz':
if broj := p >= T.BROJ: return broj
elif p >> T.OTVORENA:
u_zagradi = p.izraz()
p >> T.ZATVORENA
return u_zagradi
nula, jedan = Token(T.BROJ, '0'), Token(T.BROJ, '1')
class Zbroj(AST):
pribrojnici: 'izraz*'
def vrijednost(zbroj):
return sum(pribrojnik.vrijednost() for pribrojnik in zbroj.pribrojnici)
def optim(zbroj):
opt_pribr = [pribrojnik.optim() for pribrojnik in zbroj.pribrojnici]
opt_pribr = [x for x in opt_pribr if x != nula]
if not opt_pribr: return nula
return Zbroj.ili_samo(opt_pribr)
class Umnožak(AST):
faktori: 'izraz*'
def vrijednost(umnožak):
return math.prod(faktor.vrijednost() for faktor in umnožak.faktori)
def optim(umnožak):
opt_fakt = [faktor.optim() for faktor in umnožak.faktori]
if nula in opt_fakt: return nula
opt_fakt = [x for x in opt_fakt if x != jedan]
if not opt_fakt: return jedan
else: return Umnožak.ili_samo(opt_fakt)
def testiraj(izraz):
print('-' * 60)
prikaz(stablo := P(izraz), 3)
prikaz(opt := stablo.optim(), 3)
mi = opt.vrijednost()
try: Python = Python_eval(izraz)
except SyntaxError: return print('Python ovo ne zna!', izraz, '==', mi)
if mi == Python: return print(izraz, '==', mi, 'OK')
print(izraz, 'mi:', mi, 'Python:', Python, 'krivo')
raise ArithmeticError
an('(2+3)*4')
testiraj('(2+3)*4')
testiraj('2 + (0+1*1*2)')
testiraj('2(3+5)')
testiraj('(1+1) (0+2+0) (0+1) (3+4)')
with SintaksnaGreška: testiraj('(2+3)4')
with SintaksnaGreška: testiraj('2\t37')
with LeksičkaGreška: testiraj('2^3')
with LeksičkaGreška: testiraj('3+00')
with SintaksnaGreška: testiraj('+1')
with LeksičkaGreška: testiraj('-1')
<file_sep>"""RAM-stroj i LOOP-jezik.
RAM-stroj je virtualni stroj (VM) s prebrojivo mnogo registara R0, R1, R2, ....
U svakom registru može se nalaziti proizvoljni prirodni broj (uključujući 0).
Na početku rada RAM-stroja (reset) su svi registri inicijalizirani na 0.
RAM-stroj se može koristiti za izračunavanje brojevnih funkcija
(kao što se Turingov stroj može koristiti za izračunavanje jezičnih funkcija).
U tu svrhu, k ulaznih podataka se zapiše u registre R1--Rk (ostali su 0)
na početku rada, a na kraju rada se izlazni podatak pročita iz registra R0.
LOOP je strojni jezik (machine code) za RAM-stroj.
LOOP-program je slijed (jedne ili više) instrukcija sljedećeg oblika:
* INC Rj; (inkrement), čije izvršavanje povećava broj u Rj za 1
* DEC Rj; (dekrement), čije izvršavanje smanjuje broj u Rj za 1,
osim ako je taj broj 0 (tada ne radi ništa).
* Rj{program} (ograničena petlja), čije izvršavanje izvršava program onoliko
puta koliki je broj bio u registru Rj na početku izvršavanja petlje
(program može mijenjati Rj, ali to ne mijenja broj izvršavanja petlje).
Npr. LOOP-program "R2{DECR2;} R3{INCR2;DECR3;}" premješta broj iz R3 u R2."""
from vepar import *
from backend import RAMStroj
class T(TipoviTokena):
TOČKAZ, VOTV, VZATV, INC, DEC = *';{}', 'inc', 'dec'
class REG(Token):
def broj(t): return int(t.sadržaj[1:])
@lexer
def loop(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.casefold() in {'i', 'd'}:
next(lex) # 'N' ili 'E', case insensitive
next(lex) # 'C' , case insensitive
yield lex.literal(T, case=False)
elif znak == 'R':
lex.prirodni_broj('')
yield lex.token(T.REG)
else: yield lex.literal(T)
### Beskontekstna gramatika:
# program -> naredba | program naredba
# naredba -> INC REG TOČKAZ | DEC REG TOČKAZ | REG VOTV program VZATV
class P(Parser):
def program(p) -> 'Program':
naredbe = [p.naredba()]
while not p > {KRAJ, T.VZATV}: naredbe.append(p.naredba())
return Program(naredbe)
def naredba(p) -> 'Promjena|Petlja':
if smjer := p >= {T.INC, T.DEC}:
instrukcija = Promjena(smjer, p >> T.REG)
p >> T.TOČKAZ
return instrukcija
elif reg := p >> T.REG:
p >> T.VOTV
tijelo = p.program()
p >> T.VZATV
return Petlja(reg, tijelo)
### Apstraktna sintaksna stabla:
# naredba: Petlja: registar:REG tijelo:Program
# Promjena: op:INC|DEC registar:REG
# Program: naredbe:[naredba]
class Program(AST):
naredbe: 'naredba*'
def izvrši(program):
for naredba in program.naredbe: naredba.izvrši()
class Promjena(AST):
op: 'INC|DEC'
registar: 'REG'
def izvrši(promjena):
j = promjena.registar.broj()
if promjena.op ^ T.INC: rt.stroj.inc(j)
elif promjena.op ^ T.DEC: rt.stroj.dec(j)
else: assert False, f'Nepoznata operacija {promjena.op}'
class Petlja(AST):
registar: 'REG'
tijelo: 'Program'
def izvrši(petlja):
n = rt.stroj.registri[petlja.registar.broj()]
for ponavljanje in range(n): petlja.tijelo.izvrši()
def računaj(program, *ulazi):
rt.stroj = RAMStroj(*ulazi)
program.izvrši()
return rt.stroj.rezultat
with LeksičkaGreška: loop('inc R00')
prikaz(power := P('''
INC R0;
R2{
R0{
R1 {INC R3;}
DEC R0;
}
R3{DECR3;INCR0;}
}
'''), 9)
print(baza:=3, '^', eksponent:=7, '=', računaj(power, baza, eksponent))
# DZ: napišite multiply i add (mnogo su jednostavniji od power)
# DZ: Primitivno rekurzivne funkcije predstavljaju funkcijski programski jezik
# ~~ u kojem postoje inicijalne funkcije [nul Z(x)=0, sljedbenik Sc(x)=x+1, te
# rj koordinatne projekcije Ink(x1,...,xk)=xn za sve prirodne 1 <= n <= k].
# 13 Također postoje operatori kompozicije [f(xs)=h(g1(xs),...,gl(xs))]
# i primitivne rekurzije [f(xs,0)=g(xs); f(xs,y+1)=h(xs,y,f(xs,y))].
# ** Napišite kompajler jezika primitivno rekurzivnih funkcija u LOOP.
# (Uputa: prvo položite, ili barem odslušajte, kolegij Izračunljivost!)
<file_sep>from util import *
class TuringovStroj(types.SimpleNamespace):
@classmethod
def iz_komponenti(klasa, stanja, abeceda, radna_abeceda, praznina,
prijelaz, početno, prihvat):
assert abeceda
assert abeceda <= radna_abeceda
assert praznina in radna_abeceda - abeceda
assert {početno, prihvat} <= stanja
assert funkcija(prijelaz,
Kartezijev_produkt(stanja - {prihvat}, radna_abeceda),
Kartezijev_produkt(stanja, radna_abeceda, {-1, 1}))
return klasa(**vars())
@classmethod
def iz_tablice(klasa, tablica):
"""Parsiranje tabličnog zapisa Turingovog stroja.
Pogledati funkciju util.parsiraj_tablicu_TS za detalje."""
return klasa.iz_komponenti(*parsiraj_tablicu_TS(tablica))
@property
def komponente(stroj):
"""Relacijska definicija - rastav u sedmorku."""
return (stroj.stanja, stroj.abeceda, stroj.radna_abeceda,
stroj.praznina, stroj.prijelaz, stroj.početno, stroj.prihvat)
def prihvaća(T, riječ):
"""Prihvaća li Turingov stroj T zadanu riječ?
Poluodlučivo: može zapeti u beskonačnoj petlji ako ne prihvaća."""
return T.rezultat(riječ) is not None
def izračunavanje(T, riječ):
assert set(riječ) <= T.abeceda
stanje, pozicija, traka = T.početno, 0, list(riječ)
yield stanje, pozicija, traka
while stanje != T.prihvat:
if pozicija >= len(traka): traka.append(T.praznina)
stanje, traka[pozicija], pomak = T.prijelaz[stanje, traka[pozicija]]
pozicija = max(pozicija + pomak, 0)
yield stanje, pozicija, traka
def rezultat(T, riječ):
for stanje, pozicija, traka in T.izračunavanje(riječ):
if stanje == T.prihvat: break
if (T.prijelaz[stanje, T.praznina] == (stanje, T.praznina, 1) and
pozicija == len(traka)): return
while traka and traka[~0] == T.praznina: del traka[~0]
join_ok = all(type(znak) is str and len(znak) == 1 for znak in traka)
return ''.join(traka) if join_ok else traka
<file_sep>from util import *
class KonačniAutomat(types.SimpleNamespace):
"""Automat koji prepoznaje regularni jezik."""
@classmethod
def iz_komponenti(klasa, stanja, abeceda, prijelaz, početno, završna):
"""Sipser page 35 definition 1.5 - konstrukcija iz petorke."""
assert abeceda # nije prazna
assert početno in stanja
assert završna <= stanja
assert funkcija(prijelaz, Kartezijev_produkt(stanja, abeceda), stanja)
return klasa(**vars())
@classmethod
def iz_tablice(klasa, tablica):
"""Parsiranje tabličnog zapisa konačnog automata (Sipser page 36).
Pogledati funkciju util.parsiraj_tablicu_KA za detalje."""
return klasa.iz_komponenti(*parsiraj_tablicu_KA(tablica))
@property
def komponente(M):
"""Sipser page 35 definition 1.5 - rastav u petorku."""
return M.stanja, M.abeceda, M.prijelaz, M.početno, M.završna
def prihvaća(automat, ulaz):
"""Prihvaća li konačni automat zadani ulaz?"""
stanje = automat.početno
for znak in ulaz:
stanje = automat.prijelaz[stanje, znak]
return stanje in automat.završna
def izračunavanje(automat, ulaz):
"""Stanja kroz koja automat prolazi čitajući ulaz (Sipser page 40)."""
stanje = automat.početno
yield stanje
for znak in ulaz:
stanje = automat.prijelaz[stanje, znak]
yield stanje
def prirodni(automat):
"""Zamjenjuje stanja prirodnim brojevima, radi preglednosti."""
Q, Σ, δ, q0, F = automat.komponente
rječnik = {q: i for i, q in enumerate(Q, 1)}
QN = set(rječnik.values())
δN = {(rječnik[polazno], znak): rječnik[dolazno]
for (polazno, znak), dolazno in δ.items()}
q0N = rječnik[q0]
FN = {rječnik[završno] for završno in F}
return KonačniAutomat.iz_komponenti(QN, Σ, δN, q0N, FN)
def crtaj(automat):
"""Ispisuje na ekran dijagram automata u formatu DOT.
Dobiveni string može se kopirati u sandbox.kidstrythisathome.com/erdos
ili u www.webgraphviz.com."""
NedeterminističniKonačniAutomat.iz_konačnog_automata(automat).crtaj()
def unija(M1, M2):
"""Konačni automat za L(M1)∪L(M2)."""
assert M1.abeceda == M2.abeceda
Q1, Σ, δ1, q1, F1 = M1.komponente
Q2, Σ, δ2, q2, F2 = M2.komponente
Q = Kartezijev_produkt(Q1, Q2)
δ = {((r1,r2), α): (δ1[r1,α], δ2[r2,α]) for r1,r2 in Q for α in Σ}
F = Kartezijev_produkt(Q1, F2) | Kartezijev_produkt(F1, Q2)
return KonačniAutomat.iz_komponenti(Q, Σ, δ, (q1,q2), F)
def presjek(M1, M2):
"""Konačni automat za L(M1)∩L(M2)."""
M = M1.unija(M2)
M.završna = Kartezijev_produkt(M1.završna, M2.završna)
return M
def komplement(M):
r"""Konačni automat za (M.abeceda)*\L(M)."""
Q, Σ, δ, q0, F = M.komponente
return KonačniAutomat.iz_komponenti(Q, Σ, δ, q0, Q - F)
def razlika(M1, M2):
r"""Konačni automat za L(M1)\L(M2)."""
return M1.presjek(M2.komplement())
def simetrična_razlika(M1, M2):
"""Konačni automat za L(M1)△L(M2)."""
return M1.razlika(M2).unija(M2.razlika(M1))
def optimizirana_simetrična_razlika(M1, M2):
"""Konačni automat za L(M1)△L(M2), s |M1.stanja|·|M2.stanja| stanja."""
M = M1.razlika(M2)
M.završna |= Kartezijev_produkt(M1.stanja - M1.završna, M2.završna)
return M
def dohvatljiva(δ, S, α):
"""Stanja do kojih je moguće doći iz stanja iz S čitanjem znaka α."""
return unija_familije(δ[q, α] for q in S)
def ε_ljuska(δ, S):
"""Stanja do kojih je moguće doći iz stanja iz S bez čitanja znaka."""
while (noviS := dohvatljiva(δ, S, ε) | S) != S: S = noviS
return noviS # ne S, jer to ne mora biti fset
class NedeterminističniKonačniAutomat(types.SimpleNamespace):
"""Nedeterministični automat koji prepoznaje regularni jezik."""
@classmethod
def iz_komponenti(klasa, stanja, abeceda, prijelaz, početno, završna):
"""Relacijska definicija: Δ⊆Q×(Σ∪{ε})×Q"""
assert abeceda # nije prazna
assert početno in stanja
assert završna <= stanja
assert relacija(prijelaz, stanja, ε_proširenje(abeceda), stanja)
return klasa(**vars())
@classmethod
def iz_funkcije(klasa, stanja, abeceda, f_prijelaza, početno, završna):
"""Funkcijska definicija: δ:Q×(Σ∪{ε})→℘(Q) (Sipser page 53 def.1.37)"""
prijelaz = relacija_iz_funkcije(f_prijelaza)
return klasa.iz_komponenti(stanja, abeceda, prijelaz, početno, završna)
@classmethod
def iz_konačnog_automata(klasa, konačni_automat):
"""Pretvorba iz determinističnog KA u nedeterministični."""
Q, Σ, δ, q0, F = konačni_automat.komponente
Δ = {(q, α, δ[q, α]) for q in Q for α in Σ}
return klasa.iz_komponenti(Q, Σ, Δ, q0, F)
@classmethod
def iz_tablice(klasa, tablica):
"""Parsiranje tabličnog zapisa nedeterminističnog KA (Sipser page 54).
Pogledati funkciju util.parsiraj_tablicu_NKA za detalje."""
return klasa.iz_komponenti(*parsiraj_tablicu_NKA(tablica))
@property
def komponente(M):
"""Relacijska definicija - rastav u petorku."""
return M.stanja, M.abeceda, M.prijelaz, M.početno, M.završna
@property
def funkcija_prijelaza(automat):
"""Relacija prijelaza pretvorena u funkciju."""
return funkcija_iz_relacije(automat.prijelaz,
automat.stanja, ε_proširenje(automat.abeceda))
def prihvaća(automat, ulaz):
"""Prihvaća li automat zadani ulaz?"""
δ = automat.funkcija_prijelaza
moguća = ε_ljuska(δ, {automat.početno})
for znak in ulaz: moguća = ε_ljuska(δ, dohvatljiva(δ, moguća, znak))
return not moguća.isdisjoint(automat.završna)
def crtaj(automat):
"""Ispisuje na ekran dijagram automata u DOT formatu.
Dobiveni string može se kopirati u sandbox.kidstrythisathome.com/erdos
ili u www.webgraphviz.com."""
from PA import PotisniAutomat
print(DOT_PA(PotisniAutomat.
iz_nedeterminističnog_konačnog_automata(automat)))
def izračunavanje(nka, ulaz):
"""Generator niza skupova mogućih stanja kroz koja nedeterministični
konačni automat prolazi čitajući zadani ulaz."""
return nka.optimizirana_partitivna_konstrukcija().izračunavanje(ulaz)
def partitivna_konstrukcija(nka):
"""Ekvivalentni KA zadanom NKA, s 2^|nka.stanja| stanja."""
Q, Σ, Δ, q0, F = nka.komponente
δ = nka.funkcija_prijelaza
PQ = partitivni_skup(Q)
δ_KA = {(S,α): ε_ljuska(δ, dohvatljiva(δ,S,α)) for S in PQ for α in Σ}
F_KA = {S for S in PQ if S & F}
q0_KA = ε_ljuska(δ, {q0})
return KonačniAutomat.iz_komponenti(PQ, Σ, δ_KA, q0_KA, F_KA)
def optimizirana_partitivna_konstrukcija(nka):
"""Ekvivalentni KA zadanom NKA, samo s dostižnim stanjima."""
Q, Σ, Δ, q0, F = nka.komponente
δ = nka.funkcija_prijelaza
Q_KA = set()
δ_KA = {}
F_KA = set()
q0_KA = ε_ljuska(δ, {q0})
red = collections.deque([q0_KA])
while red:
stanje = red.popleft()
if stanje not in Q_KA:
for α in Σ:
novo_stanje = ε_ljuska(δ, dohvatljiva(δ, stanje, α))
δ_KA[stanje, α] = novo_stanje
red.append(novo_stanje)
Q_KA.add(stanje)
if not stanje.isdisjoint(F):
F_KA.add(stanje)
return KonačniAutomat.iz_komponenti(Q_KA, Σ, δ_KA, q0_KA, F_KA)
def označi(nka, l):
"""Označava stanja danog NKA dodatnom oznakom l, radi disjunktnosti."""
Q, Σ, Δ, q0, F = nka.komponente
Ql = {označi1(q, l) for q in Q}
Δl = {(označi1(p, l), α, označi1(q, l)) for p, α, q in Δ}
q0l = označi1(q0, l)
Fl = {označi1(q, l) for q in F}
return NedeterminističniKonačniAutomat.iz_komponenti(Ql, Σ, Δl, q0l, Fl)
def unija(N1, N2):
"""Nedeterministični konačni automat koji prepoznaje L(N1)∪L(N2)."""
assert N1.abeceda == N2.abeceda
if not N1.stanja.isdisjoint(N2.stanja):
N1 = N1.označi(1)
N2 = N2.označi(2)
Q1, Σ, Δ1, q1, F1 = N1.komponente
Q2, Σ, Δ2, q2, F2 = N2.komponente
q0 = novo('q0', Q1 | Q2)
Q = disjunktna_unija(Q1, Q2, {q0})
F = disjunktna_unija(F1, F2)
Δ = disjunktna_unija(Δ1, Δ2, {(q0, ε, q1), (q0, ε, q2)})
return NedeterminističniKonačniAutomat.iz_komponenti(Q, Σ, Δ, q0, F)
def konkatenacija(N1, N2):
"""Nedeterministični konačni automat koji prepoznaje L(N1)L(N2)."""
assert N1.abeceda == N2.abeceda
if not N1.stanja.isdisjoint(N2.stanja):
N1 = N1.označi(3)
N2 = N2.označi(4)
Q1, Σ, Δ1, q1, F1 = N1.komponente
Q2, Σ, Δ2, q2, F2 = N2.komponente
Q = disjunktna_unija(Q1, Q2)
Δ = disjunktna_unija(Δ1, Δ2, {(p1, ε, q2) for p1 in F1})
return NedeterminističniKonačniAutomat.iz_komponenti(Q, Σ, Δ, q1, F2)
def plus(N):
"""Nedeterministični konačni automat za Kleenejev plus od L(N)."""
Q, Σ, Δ, q0, F = N.komponente
Δp = Δ | {(p, ε, q0) for p in F}
return NedeterminističniKonačniAutomat.iz_komponenti(Q, Σ, Δp, q0, F)
def zvijezda(N):
"""Nedeterministični konačni automat za Kleenejevu zvijezdu od L(N)."""
Q, Σ, Δ, q0, F = N.plus().komponente
start = novo('start', Q)
return NedeterminističniKonačniAutomat.iz_komponenti(
Q | {start}, Σ, Δ | {(start, ε, q0)}, start, F | {start})
<file_sep>.. vepar documentation master file, created by
sphinx-quickstart on Thu May 20 07:26:27 2021.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Dokumentacija za vepar 2
========================
.. toctree::
:maxdepth: 2
:caption: Sadržaj:
tutorial/lexer
tutorial/parser
tutorial/semantic
refer/vepar
Vepar vam omogućuje da koristeći Python pišete vlastite programske
jezike, prolazeći kroz uobičajene faze kao što su leksiranje,
parsiranje, proizvodnja apstraktnih sintaksnih stabala (AST),
optimizacija, generiranje bajtkoda za virtualni stroj, te izvršavanje
(interpretaciju u užem smislu).
Ne trebate znati puno Pythona za to: vepar je framework (poput
npr. Djanga) koji ima svoje konvencije i prilično rigidan uobičajeni
stil pisanja, iz kojih ćete rijetko trebati izaći. Ipak, poznavanje
Pythona sigurno će pomoći, jer ćete manje toga morati naučiti i
mnogi detalji u dizajnu imat će vam više smisla.
Iako se vepar može koristiti u profesionalnom okruženju, prvenstveno
je zamišljen kao akademski alat: cilj je naučiti što više o uobičajenim
tehnikama interpretacije programa, a ne napisati najbrži parser, ni
semantički analizator s najboljim mogućim oporavkom od grešaka, niti
generator strašno optimiziranog koda.
To je ujedno i glavna prednost vepra pred uobičajenim alatima kao što
su flex, yacc i LLVM: ne morajući cijelo vrijeme razmišljati o performansama,
vepar može puno bolje izložiti osnovne koncepte koji stoje u pozadini raznih
faza interpretacije programa, razdvajajući ih i tretirajući svaki zasebno.
Spoj toga i uobičajene Pythonove filozofije "sve je interaktivno, dinamično
i istraživo" predstavlja dobru podlogu za učenje.
<file_sep>"""Interpreter za jednostavni fragment jezika C++: petlje, grananja, ispis.
Prema zadatku s kolokvija 16. veljače 2015. (Puljić).
* petlje: for(var = broj; var < broj; var ++ ili var += broj) naredba
* grananja: if(var == broj) naredba
* ispis: cout << var1 << var2 << ..., s opcionalnim << endl na kraju
Tijelo petlje može biti i blok u vitičastim zagradama.
Podržana je i naredba break za izlaz iz unutarnje petlje:
nelokalna kontrola toka realizirana je pomoću izuzetka Prekid."""
from vepar import *
class T(TipoviTokena):
FOR, COUT, ENDL, IF = 'for', 'cout', 'endl', 'if'
OOTV, OZATV, VOTV, VZATV, MANJE, JEDNAKO, TOČKAZ = '(){}<=;'
PLUSP, PLUSJ, MMANJE, JJEDNAKO = '++', '+=', '<<', '=='
class BREAK(Token):
literal = 'break'
def izvrši(self): raise Prekid
class BROJ(Token):
def vrijednost(self): return int(self.sadržaj)
class IME(Token):
def vrijednost(self): return rt.mem[self]
@lexer
def cpp(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak == '+':
if lex >= '+': yield lex.token(T.PLUSP)
elif lex >= '=': yield lex.token(T.PLUSJ)
else: raise lex.greška('u ovom jeziku nema samostalnog +')
elif znak == '<': yield lex.token(T.MMANJE if lex >= '<' else T.MANJE)
elif znak == '=':
yield lex.token(T.JJEDNAKO if lex >= '=' else T.JEDNAKO)
elif znak.isalpha() or znak == '_':
lex * {str.isalnum, '_'}
yield lex.literal_ili(T.IME)
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
## Beskontekstna gramatika
# start -> naredbe naredba
# naredbe -> '' | naredbe naredba
# naredba -> petlja | grananje | ispis TOČKAZ | BREAK TOČKAZ
# for -> FOR OOTV IME# JEDNAKO BROJ TOČKAZ IME# MANJE BROJ TOČKAZ
# IME# inkrement OZATV
# petlja -> for naredba | for VOTV naredbe VZATV
# inkrement -> PLUSP | PLUSJ BROJ
# ispis -> COUT varijable | COUT varijable MMANJE ENDL
# varijable -> '' | varijable MMANJE IME
# grananje -> IF OOTV IME JJEDNAKO BROJ OZATV naredba
class P(Parser):
def start(p) -> 'Program':
naredbe = [p.naredba()]
while not p > KRAJ: naredbe.append(p.naredba())
return Program(naredbe)
def naredba(p) -> 'petlja|ispis|grananje|BREAK':
if p > T.FOR: return p.petlja()
elif p > T.COUT: return p.ispis()
elif p > T.IF: return p.grananje()
elif br := p >> T.BREAK:
p >> T.TOČKAZ
return br
def petlja(p) -> 'Petlja':
kriva_varijabla = SemantičkaGreška(
'Sva tri dijela for-petlje moraju imati istu varijablu.')
p >> T.FOR, p >> T.OOTV
i = p >> T.IME
p >> T.JEDNAKO
početak = p >> T.BROJ
p >> T.TOČKAZ
if (p >> T.IME) != i: raise kriva_varijabla
p >> T.MANJE
granica = p >> T.BROJ
p >> T.TOČKAZ
if (p >> T.IME) != i: raise kriva_varijabla
if p >= T.PLUSP: inkrement = nenavedeno
elif p >> T.PLUSJ: inkrement = p >> T.BROJ
p >> T.OZATV
if p >= T.VOTV:
blok = []
while not p >= T.VZATV: blok.append(p.naredba())
else: blok = [p.naredba()]
return Petlja(i, početak, granica, inkrement, blok)
def ispis(p) -> 'Ispis':
p >> T.COUT
varijable, novired = [], nenavedeno
while p >= T.MMANJE:
if varijabla := p >= T.IME: varijable.append(varijabla)
else:
novired = p >> T.ENDL
break
p >> T.TOČKAZ
return Ispis(varijable, novired)
def grananje(p) -> 'Grananje':
p >> T.IF, p >> T.OOTV
lijevo = p >> T.IME
p >> T.JJEDNAKO
desno = p >> T.BROJ
p >> T.OZATV
return Grananje(lijevo, desno, p.naredba())
class Prekid(NelokalnaKontrolaToka): """Signal koji šalje naredba break."""
## Apstraktna sintaksna stabla:
# Program: naredbe:[naredba]
# naredba: BREAK: Token
# Petlja: varijabla:IME početak:BROJ granica:BROJ
# inkrement:BROJ? blok:[naredba]
# Ispis: varijable:[IME] novired:ENDL?
# Grananje: lijevo:IME desno:BROJ onda:naredba
class Program(AST):
naredbe: 'naredba*'
def izvrši(program):
rt.mem = Memorija()
try: # break izvan petlje je zapravo sintaksna greška - kompliciranije
for naredba in program.naredbe: naredba.izvrši()
except Prekid: raise SemantičkaGreška('nedozvoljen break izvan petlje')
class Petlja(AST):
varijabla: 'IME'
početak: 'BROJ'
granica: 'BROJ'
inkrement: 'BROJ?'
blok: 'naredba*'
def izvrši(petlja):
kv = petlja.varijabla # kontrolna varijabla petlje
rt.mem[kv] = petlja.početak.vrijednost()
while rt.mem[kv] < petlja.granica.vrijednost():
try:
for naredba in petlja.blok: naredba.izvrši()
except Prekid: break
inkr = petlja.inkrement
rt.mem[kv] += inkr.vrijednost() if inkr else 1
class Ispis(AST):
varijable: 'IME*'
novired: 'ENDL?'
def izvrši(ispis):
for varijabla in ispis.varijable:
print(varijabla.vrijednost(), end=' ')
if ispis.novired ^ T.ENDL: print()
class Grananje(AST):
lijevo: 'IME'
desno: 'BROJ'
onda: 'naredba'
def izvrši(grananje):
if grananje.lijevo.vrijednost() == grananje.desno.vrijednost():
grananje.onda.izvrši()
def očekuj(greška, kôd):
print('Testiram:', kôd)
with greška: P(kôd).izvrši()
prikaz(kôd := P('''
for ( i = 8 ; i < 13 ; i += 2 ) {
for(j=0; j<5; j++) {
cout<<i<<j;
if(i == 10) if (j == 1) break;
}
cout<<i<<endl;
}
'''), 8)
kôd.izvrši()
prikaz(P('cout;'))
očekuj(SintaksnaGreška, '')
očekuj(SintaksnaGreška, 'for(c=1; c<3; c++);')
očekuj(LeksičkaGreška, '+1')
očekuj(SemantičkaGreška, 'for(a=1; b<3; c++)break;')
očekuj(SemantičkaGreška, 'break;')
očekuj(LeksičkaGreška, 'if(i == 07) cout;')
# DZ: implementirajte naredbu continue
# DZ: implementirajte praznu naredbu (for/if(...);)
# DZ: omogućite i grananjima da imaju blokove -- uvedite novo AST Blok
# DZ: omogućite da parametri petlje budu varijable, ne samo brojevi
# DZ: omogućite grananja s obzirom na relaciju <, ne samo ==
# DZ: dodajte parseru kontekstnu varijablu 'jesmo li u petlji' za dozvolu BREAK
# DZ: uvedite deklaracije varijabli i pratite jesu li varijable deklarirane
<file_sep>"""Leksički i sintaksni analizator za JavaScriptove funkcije.
Po uzoru na kolokvij 19. siječnja 2012. (Puljić).
Lexer nije sasvim regularan jer broji slojeve vitičastih zagrada
kako bi znao predstavlja li niz znakova (koji može početi znakom $
u skladu s tradicijom JavaScripta) ime parametra funkcije ili naredba."""
from vepar import *
class T(TipoviTokena):
FUNCTION, VAR, KOMENTAR = 'function', 'var', '//'
O_OTV, O_ZATV, V_OTV, V_ZATV, KOSACRTA, ZAREZ, TOČKAZAREZ = '(){}/,;'
class IME(Token): pass
class NAREDBA(Token): pass
@lexer
def js(lex):
ugniježđenost = 0
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isalpha() or znak in {'$', '_'}:
lex * {str.isalnum, '$', '_'}
default = T.NAREDBA if ugniježđenost else T.IME
yield lex.literal_ili(default)
elif znak == '/':
if lex >= '/':
lex - '\n'
yield lex.token(T.KOMENTAR)
else: yield lex.token(T.KOSACRTA)
else:
token = lex.literal(T)
if token ^ T.V_OTV: ugniježđenost += 1
elif token ^ T.V_ZATV: ugniježđenost -= 1
yield token
### Beskontekstna gramatika
# start -> fun | start fun
# fun -> FUNCTION IME O_OTV argumenti? O_ZATV V_OTV KOMENTAR* nar V_ZATV
# argumenti -> VAR IME | argumenti ZAREZ VAR IME
# nar -> NAREDBA TOČKAZAREZ nar | NAREDBA KOMENTAR+ nar | NAREDBA | ''
class P(Parser):
def funkcija(p) -> 'Funkcija':
p >> T.FUNCTION
ime = p >> T.IME
p >> T.O_OTV
argumenti = []
if p > T.VAR:
argumenti = [p.argument()]
while p >= T.ZAREZ: argumenti.append(p.argument())
p >> T.O_ZATV
return Funkcija(ime, argumenti, p.tijelo())
def tijelo(p) -> 'naredba*':
p >> T.V_OTV
while p >= T.KOMENTAR: pass
naredbe = []
while not p >= T.V_ZATV:
naredbe.append(p >> T.NAREDBA)
if p >= T.TOČKAZAREZ: pass
elif p > T.KOMENTAR:
while p >= T.KOMENTAR: pass
elif p >> T.V_ZATV: break
return naredbe
def start(p) -> 'Program':
funkcije = [p.funkcija()]
while not p > KRAJ: funkcije.append(p.funkcija())
return Program(funkcije)
def argument(p) -> 'IME':
p >> T.VAR
return p >> T.IME
### AST
# Funkcija: ime:IME argumenti:[IME] tijelo:[NAREDBA]
# Program: funkcije:[Funkcija]
class Funkcija(AST):
ime: 'IME'
argumenti: 'IME*'
tijelo: 'NAREDBA*'
class Program(AST):
funkcije: 'Funkcija*'
prikaz(P('''
function ime (var x, var y, var z) {
//neke naredbe odvojene s ; ili komentarima
naredba; druga_naredba //kom
još_jedna_naredba
}
function ništa(){}
function $trivijalna(var hmmm){n// komm/
//
}
'''), 3)
with SintaksnaGreška: P('function n(){naredba naredba;}')
<file_sep>"""Izračunavanje aritmetičkih izraza nad skupom prirodnih brojeva.
Podržani operatori su + (zbrajanje), * (množenje) i ^ (potenciranje).
Svi operatori su binarni i desno asocirani, radi jednostavnosti parsera.
Zbrajanju i množenju je svejedno jer su to asocijativne operacije,
a potenciranje se obično po dogovoru shvaća desno asocirano (2^3^2=2^9=512).
Zagrade su dozvoljene, ali često nisu nužne. Prioritet je uobičajen (^, *, +).
Implementiran je i jednostavni optimizator, koji detektira sve nule i
jedinice u izrazima, te pojednostavljuje izraze koji ih sadrže
(x+0=0+x=x*1=1*x=x^1=x, x^0=1^x=1, x*0=0*x=0^x=0
- ovo zadnje pravilo se uvijek primjenjuje nakon x^0=1, jer 0^0=1)."""
from vepar import *
from backend import StrojSaStogom, Python_eval
class T(TipoviTokena):
PLUS, PUTA, NA, OTVORENA, ZATVORENA = '+*^()'
class BROJ(Token):
def vrijednost(t): return int(t.sadržaj)
def optim(t): return t
def prevedi(t): yield ['PUSH', t.vrijednost()]
@lexer
def an(lex):
for znak in lex:
if znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
else: yield lex.literal(T)
### Beskontekstna gramatika: (desno asocirani operatori)
# izraz -> član PLUS izraz | član
# član -> faktor PUTA član | faktor
# faktor -> baza NA faktor | baza
# baza -> BROJ | OTVORENA izraz ZATVORENA
### Apstraktna sintaksna stabla
# izraz: BROJ: Token
# Zbroj: pribrojnici:[izraz] (duljine 2)
# Umnožak: faktori:[izraz] (duljine 2)
# Potencija: baza:izraz eksponent:izraz
class P(Parser):
def izraz(p) -> 'Zbroj|član':
prvi = p.član()
if p >= T.PLUS:
drugi = p.izraz()
return Zbroj([prvi, drugi])
else:
return prvi
def član(p) -> 'Umnožak|faktor':
faktor = p.faktor()
if p >= T.PUTA: return Umnožak([faktor, p.član()])
else: return faktor
def faktor(p) -> 'Potencija|baza':
baza = p.baza()
if p >= T.NA: return Potencija(baza, p.faktor())
else: return baza
def baza(p) -> 'BROJ|izraz':
if broj := p >= T.BROJ: return broj
elif p >> T.OTVORENA:
u_zagradi = p.izraz()
p >> T.ZATVORENA
return u_zagradi
nula = Token(T.BROJ, '0')
jedan = Token(T.BROJ, '1')
class Zbroj(AST):
pribrojnici: 'izraz*'
def vrijednost(izraz):
a, b = izraz.pribrojnici
return a.vrijednost() + b.vrijednost()
def optim(izraz):
a, b = izraz.pribrojnici
a, b = a.optim(), b.optim()
if a == nula: return b
elif b == nula: return a
else: return Zbroj([a, b])
def prevedi(izraz):
for pribrojnik in izraz.pribrojnici: yield from pribrojnik.prevedi()
yield ['ADD']
class Umnožak(AST):
faktori: 'izraz*'
def vrijednost(izraz):
a, b = izraz.faktori
return a.vrijednost() * b.vrijednost()
def optim(izraz):
a, b = izraz.faktori
a, b = a.optim(), b.optim()
if a == jedan: return b
elif b == jedan: return a
elif nula in [a, b]: return nula
else: return Umnožak([a, b])
def prevedi(izraz):
for faktor in izraz.faktori: yield from faktor.prevedi()
yield ['MUL']
class Potencija(AST):
baza: 'izraz'
eksponent: 'izraz'
def vrijednost(izraz):
return izraz.baza.vrijednost() ** izraz.eksponent.vrijednost()
def optim(izraz):
b, e = izraz.baza.optim(), izraz.eksponent.optim()
if e == nula: return jedan
elif b == nula: return nula # 0^0 je gore, jer prepoznamo sve nule
elif jedan in {b, e}: return b
else: return Potencija(b, e)
def prevedi(izraz):
yield from izraz.baza.prevedi()
yield from izraz.eksponent.prevedi()
yield ['POW']
def testiraj(izraz):
print('-' * 60)
print(izraz)
prikaz(stablo := P(izraz))
prikaz(opt := stablo.optim())
vm = StrojSaStogom()
for instrukcija in opt.prevedi():
vm.izvrši(*instrukcija)
print(*instrukcija, '\t'*2, vm)
print('rezultat:', vm.rezultat)
mi = opt.vrijednost()
Python = Python_eval(izraz.replace('^', '**'))
if mi == Python: print(izraz, '==', mi, 'OK')
else:
print(izraz, 'mi:', mi, 'Python:', Python, 'krivo')
raise ArithmeticError('Python se ne slaže s nama')
an('(2+3)*4^1')
testiraj('(2+3)*4^1')
testiraj('2^0^0^0^0')
testiraj('2+(0+1*1*2)')
testiraj('1+2*3^4+0*5^6*7+8*9')
with LeksičkaGreška: testiraj('2 3')
with SintaksnaGreška: testiraj('2+')
with SintaksnaGreška: testiraj('(2+3)45')
with LeksičkaGreška: testiraj('3+02')
<file_sep>mg = '''\
S>a
S>PZ
PZ>aZ
aZ>aa
PZ>PAAZ
PA>PB
BAA>BBA
BAZ>BBZ
PB>PAB
ABB>AAAB
ABZ>AAAAZ
PA>aA
aAA>aaA
aAZ>aaZ
'''
import collections, contextlib
pravila = collections.defaultdict(set)
for linija in mg.splitlines():
lijevo, desne = linija.split('>')
pravila[lijevo].update(desne.split('|'))
# print(pravila)
def mjesta(riječ, podriječ):
i = -1
with contextlib.suppress(ValueError):
while ...:
i = riječ.index(podriječ, i+1)
yield i, i + len(podriječ)
def sljedeće(pravila, riječ):
for lijevo, desna in pravila.items():
for početak, kraj in mjesta(riječ, lijevo):
for desno in desna:
yield riječ[:početak] + desno + riječ[kraj:]
def jezik(pravila, do=16, početna='S'):
moguće = {'S'}
while ...:
novo = set()
for riječ in moguće:
if riječ.islower(): yield riječ
elif len(riječ) <= do:
novo.update(sljedeće(pravila, riječ))
if not novo: return
moguće = novo
for riječ in jezik(pravila, do=64):
print(riječ)
<file_sep>"""Istinitosna vrijednost, i jednostavna optimizacija, formula logike sudova.
Standardna definicija iz [Vuković, Matematička logika]:
* Propozicijska varijabla (P0, P1, P2, ..., P9, P10, P11, ....) je formula
* Ako je F formula, tada je i !F formula (negacija)
* Ako su F i G formule, tada su i (F&G), (F|G), (F->G) i (F<->G) formule
Sve zagrade (oko binarnih veznika) su obavezne!
Interpretaciju zadajemo imenovanim argumentima: vrijednost(F, P2=True, P7=False)
Optimizacija (formula.optim()) zamjenjuje potformule oblika !!F sa F."""
from vepar import *
class T(TipoviTokena):
NEG, KONJ, DISJ, OTV, ZATV = '!&|()'
KOND, BIKOND = '->', '<->'
class PVAR(Token):
def vrijednost(var, I): return I[var]
def optim(var): return var
@lexer
def ls(lex):
for znak in lex:
if znak == 'P':
prvo = next(lex)
if not prvo.isdecimal(): raise lex.greška('očekivana znamenka')
if prvo != '0': lex * str.isdigit
yield lex.token(T.PVAR)
elif znak == '-':
lex >> '>'
yield lex.token(T.KOND)
elif znak == '<':
lex >> '-'
lex >> '>'
yield lex.token(T.BIKOND)
else: yield lex.literal(T)
### Beskontekstna gramatika:
# formula -> NEG formula | PVAR | OTV formula binvez formula ZATV
# binvez -> KONJ | DISJ | KOND | BIKOND
### Apstraktna sintaksna stabla (i njihovi atributi):
# formula: PVAR: Token
# Negacija: ispod:formula
# Binarna: veznik:T lijevo:formula desno:formula
class P(Parser):
def formula(p) -> 'PVAR|Negacija|Binarna':
if varijabla := p >= T.PVAR: return varijabla
elif p >= T.NEG:
ispod = p.formula()
return Negacija(ispod)
elif p >> T.OTV:
lijevo = p.formula()
veznik = p >> {T.KONJ, T.DISJ, T.KOND, T.BIKOND}
desno = p.formula()
p >> T.ZATV
return Binarna(veznik, lijevo, desno)
class Negacija(AST):
ispod: 'formula'
def vrijednost(negacija, I): return not negacija.ispod.vrijednost(I)
def optim(negacija):
ispod_opt = negacija.ispod.optim()
if ispod_opt ^ Negacija: return ispod_opt.ispod
else: return Negacija(ispod_opt)
class Binarna(AST):
veznik: 'T'
lijevo: 'formula'
desno: 'formula'
def vrijednost(self, I):
v = self.veznik
l = self.lijevo.vrijednost(I)
d = self.desno.vrijednost(I)
if v ^ T.DISJ: return l or d
elif v ^ T.KONJ: return l and d
elif v ^ T.KOND: return l <= d
elif v ^ T.BIKOND: return l == d
else: assert False, 'nepokriveni slučaj'
def optim(self):
lijevo_opt = self.lijevo.optim()
desno_opt = self.desno.optim()
return Binarna(self.veznik, lijevo_opt, desno_opt)
def istinitost(formula, **interpretacija):
I = Memorija(interpretacija)
return formula.vrijednost(I)
ls(ulaz := '!(P5&!!(P3->P0))')
prikaz(F := P(ulaz))
prikaz(F := F.optim())
print(f'{istinitost(F, P0=False, P3=True, P5=False)=}') # True
for krivo in 'P', 'P00', 'P1\tP2', 'P34<>P56':
with LeksičkaGreška: ls(krivo)
# DZ: implementirajte još neke optimizacije: npr. F|!G u G->F.
# DZ: Napravite totalnu optimizaciju negacije: svaka formula s najviše jednim !
# ~~ *Za ovo bi vjerojatno bilo puno lakše imati po jedno AST za svaki veznik.
<file_sep>from collections import ChainMap
mem = ChainMap() # mem = {}
mem['x'] = 5
mem['y'] = 7
mem = mem.new_child()
mem['x'] = 2
print(mem['x'], mem['y'])
mem = mem.parents
print(mem['x'], mem['y'])
mem = mem.parents
print(mem)
<file_sep>from pj import *
class KF(enum.Enum):
OTV, ZATV = '()'
class ATOM(Token):
def Mr(self, **atomi):
return pogledaj(atomi,self)
class BROJ(Token):
def vrijednost(self,**_):
return int(self.sadržaj)
class N(Token):
literal='n'
def vrijednost(self, **atomi):
return atomi['n']
def kf_lex(formula):
lex=Tokenizer(formula)
for i, znak in enumerate(iter(lex.čitaj, '')):
print(znak)
if not i and znak=='n' or znak!=')' and lex.slijedi('n'):
raise lex.greška("nema ')' prije n!")
elif znak.isdigit() and znak!='0':
lex.zvijezda(str.isdigit)
yield lex.token(KF.BROJ)
elif znak.isupper():
idući=lex.čitaj()
print('"', idući)
if not idući.islower(): lex.vrati()
yield lex.literal(KF.ATOM)
else: yield lex.literal(KF)
### Beskontekstna gramatika
# formula -> formula skupina | skupina
# skupina -> ATOM BROJ? | OTV formula ZATV (N | BROJ)?
### Apstraktna sintaksna stabla
# Formula: skupine:[(Formula, broj|'n')]
jedan=Token(KF.BROJ,'1')
class KFParser(Parser):
def formula(self):
skupine=[self.skupina()]
while not self>={E.KRAJ,KF.ZATV}:
skupine.append(self.skupina())
return Formula(skupine)
def skupina(self):
if self >> KF.ATOM:
atom=self.zadnji
if self >> KF.BROJ:
broj=self.zadnji
else:
broj=jedan
return (atom,broj)
else:
self.pročitaj(KF.OTV)
f=self.formula()
self.pročitaj(KF.ZATV)
if self >> {KF.N, KF.BROJ}:
broj=self.zadnji
else:
broj=jedan
return (f,broj)
start = formula
class Formula(AST('skupine')):
def Mr(self, **atomi):
suma=0
for skupina, broj in self.skupine:
suma += skupina.Mr(**atomi)*broj.vrijednost(**atomi)
return suma
if __name__=='__main__':
formula='CabH3(CabH2)nCabH3'
formula = 'AbcdeF'
tokeni=list(kf_lex(formula))
p=KFParser.parsiraj(tokeni)
print(tokeni,p,p.Mr(Cab=12.01,H=1.008,n=2),sep='\n\n')
<file_sep>"""Jednostavni parser SQLa, samo za nizove naredbi CREATE i SELECT.
Ovaj fragment SQLa je zapravo regularan -- nigdje nema ugnježđivanja!
Napisan je semantički analizator u obliku name resolvera:
provjerava jesu li svi selektirani stupci prisutni, te broji pristupe."""
from vepar import *
from backend import PristupLog
class T(TipoviTokena):
SELECT, FROM, CREATE, TABLE = 'select', 'from', 'create', 'table'
OTVORENA, ZATVORENA, ZVJEZDICA, ZAREZ, TOČKAZAREZ = '()*,;'
class IME(Token): pass
class BROJ(Token): pass
@lexer
def sql(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isalnum():
lex * str.isalnum
if lex.sadržaj.isdecimal(): yield lex.token(T.BROJ)
else: yield lex.literal_ili(T.IME, case=False)
elif znak == '-':
lex >> '-'
lex - '\n'
lex.zanemari()
else: yield lex.literal(T)
### Beskontekstna gramatika:
# start -> naredba | start naredba
# naredba -> select TOČKAZAREZ | create TOČKAZAREZ
# select -> SELECT ZVJEZDICA FROM IME | SELECT stupci FROM IME
# stupci -> IME | stupci ZAREZ IME
# create -> CREATE TABLE IME OTVORENA spec_stupci ZATVORENA
# spec_stupci -> spec_stupac | spec_stupci ZAREZ spec_stupac
# spec_stupac -> IME IME | IME IME OTVORENA BROJ ZATVORENA
class P(Parser):
def start(p) -> 'Skripta':
naredbe = [p.naredba()]
while not p > KRAJ: naredbe.append(p.naredba())
return Skripta(naredbe)
def select(p) -> 'Select':
p >> T.SELECT
if p >= T.ZVJEZDICA: stupci = nenavedeno
elif stupac := p >> T.IME:
stupci = [stupac]
while p >= T.ZAREZ: stupci.append(p >> T.IME)
p >> T.FROM
return Select(p >> T.IME, stupci)
def spec_stupac(p) -> 'Stupac':
ime, tip = p >> T.IME, p >> T.IME
if p >= T.OTVORENA:
veličina = p >> T.BROJ
p >> T.ZATVORENA
else: veličina = nenavedeno
return Stupac(ime, tip, veličina)
def create(p) -> 'Create':
p >> T.CREATE, p >> T.TABLE
tablica = p >> T.IME
p >> T.OTVORENA
stupci = [p.spec_stupac()]
while p >= T.ZAREZ: stupci.append(p.spec_stupac())
p >> T.ZATVORENA
return Create(tablica, stupci)
def naredba(p) -> 'select|create':
if p > T.SELECT: rezultat = p.select()
elif p > T.CREATE: rezultat = p.create()
else: raise p.greška()
p >> T.TOČKAZAREZ
return rezultat
### Apstraktna sintaksna stabla:
# Skripta: naredbe:[naredba]
# naredba: Select: tablica:IME stupci:[IME]?
# Create: tablica:IME specifikacije:[Stupac]
# Stupac: ime:IME tip:IME veličina:BROJ?
class Skripta(AST):
"""Niz naredbi SQLa, svaka završava točkazarezom."""
naredbe: 'naredba*'
def razriješi(skripta):
rt.imena = Memorija(redefinicija=False)
for naredba in skripta.naredbe: naredba.razriješi()
return rt.imena
class Stupac(AST):
"""Specifikacija stupca u tablici."""
ime: 'IME'
tip: 'IME'
veličina: 'BROJ?'
class Create(AST):
"""Naredba CREATE TABLE."""
tablica: 'IME'
specifikacije: 'Stupac*'
def razriješi(naredba):
pristup = rt.imena[naredba.tablica] = Memorija(redefinicija=False)
for stupac in naredba.specifikacije:
pristup[stupac.ime] = PristupLog(stupac)
class Select(AST):
"""Naredba SELECT."""
tablica: 'IME'
stupci: 'IME*?'
def razriješi(naredba):
t = rt.imena[naredba.tablica]
dohvaćeni = naredba.stupci
if dohvaćeni is nenavedeno: dohvaćeni = dict(t)
for stupac in dohvaćeni: t[stupac].pristupi()
def za_indeks(skripta):
for tablica, logovi in skripta.razriješi():
ukupni = brojač = 0
for stupac, log in logovi:
ukupni += log.pristup
brojač += 1
if not brojač: continue
prosjek = ukupni / brojač
for stupac, log in logovi:
if log.pristup > prosjek: yield tablica, stupac
skripta = P('''
CREATE TABLE Persons
(
PersonID int,
Name varchar(255), -- neki stupci imaju zadanu veličinu
Birthday date, -- a neki nemaju...
Married bool,
City varchar(9) -- zadnji nema zarez!
); -- Sada krenimo nešto selektirati
SELECT Name, City FROM Persons;
SELECT * FROM Persons;
CREATE TABLE 2E3 (s t, s2 t);
SELECT*FROM 2E3; -- između simbola i riječi ne mora ići razmak
SELECT s FROM 2E3; -- ali između dvije riječi mora, naravno
SELECT Name, Married FROM Persons;
SELECT Name from Persons;
''')
prikaz(skripta, 4)
for tablica, log in skripta.razriješi():
print('Tablica', tablica, '- stupci:')
for stupac, pristup in log: print('\t', stupac, pristup)
for i, (tablica, stupac) in enumerate(za_indeks(skripta), start=1):
print(f'CREATE INDEX idx{i} ON {tablica.sadržaj} ({stupac.sadržaj});')
with SemantičkaGreška: P('SELECT * FROM nema;').razriješi()
with SemantičkaGreška:
P('CREATE TABLE mala (stupac int); SELECT drugi FROM mala;').razriješi()
with SintaksnaGreška: P('CREATE TABLE 2000 (s t);')
# ideje za dalji razvoj:
# * pristup stupcu umjesto samog broja može biti lista brojeva linija \
# skripte u kojima počinju SELECTovi koji pristupaju pojedinom stupcu
# * optimizacija: brisanje iz CREATE stupaca kojima nismo uopće pristupili
# * implementirati INSERT INTO, da možemo doista nešto i raditi s podacima
# * povratni tip za SELECT (npr. (varchar(255), bool) za predzadnji)
# * interaktivni način rada (online - analizirati naredbu po naredbu)
<file_sep>"""Aritmetika u Q, s deklaracijama varijabli, statičkim (sintaksnim) tipovima,
i provjerom tipova (typechecking). Podržana su tri tipa, totalno uređena s
obzirom na relaciju "biti podtip": nat (N), int (Z) i rat (Q)."""
from vepar import *
class T(TipoviTokena):
NAT, INT, RAT, DIV, MOD = 'nat', 'int', 'rat', 'div', 'mod'
PLUS, MINUS, PUTA, KROZ, NA, OTV, ZATV, JEDNAKO, UPIT = '+-*/^()=?'
NOVIRED = '\n'
class IME(Token):
def provjeri_tip(t): return rt.symtab[t]
class BROJ(Token):
def provjeri_tip(t): return Tip.N
@lexer
def aq(lex):
for znak in lex:
if znak == '\n': yield lex.literal(T) # prije provjere isspace!
elif znak.isspace(): lex.zanemari()
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak.isalpha():
lex * {str.isalpha, '_'}
yield lex.literal_ili(T.IME, case=False)
else: yield lex.literal(T)
class Tip(enum.Enum):
N = Token(T.NAT)
Z = Token(T.INT)
Q = Token(T.RAT)
def __le__(t1, t2): return t1 is Tip.N or t2 is Tip.Q or t1 is t2
def __lt__(t1, t2): return t1 <= t2 and t1 is not t2
### Beskontekstna gramatika
# start -> NOVIRED? niz_naredbi NOVIRED?
# niz_naredbi -> naredba | niz_naredbi NOVIRED naredba
# naredba -> UPIT izraz | (NAT|INT|RAT)? IME JEDNAKO izraz
# izraz -> član | izraz (PLUS|MINUS) član
# član -> faktor | član (PUTA|KROZ|DIV|MOD) faktor
# faktor -> baza | baza NA faktor | MINUS faktor
# baza -> BROJ | IME | OTV izraz ZATV
class P(Parser):
def start(self) -> 'Program':
self >= T.NOVIRED
rt.symtab, naredbe = Memorija(), []
while not self > KRAJ:
naredbe.append(self.naredba())
self >> {T.NOVIRED, KRAJ}
return Program(naredbe)
def naredba(self) -> 'izraz|Pridruživanje':
if self >= T.UPIT: return self.izraz()
token_za_tip = self >= {T.NAT, T.INT, T.RAT}
ažuriraj(varijabla := self >> T.IME, token_za_tip)
self >> T.JEDNAKO
return Pridruživanje(varijabla, token_za_tip, self.izraz())
def izraz(self) -> 'član|Op':
t = self.član()
while op := self >= {T.PLUS, T.MINUS}: t = Op(op, t, self.član())
return t
def član(self) -> 'faktor|Op':
trenutni = self.faktor()
while operator := self >= {T.PUTA, T.KROZ, T.DIV, T.MOD}:
trenutni = Op(operator, trenutni, self.faktor())
return trenutni
def faktor(self) -> 'baza|Op':
if op := self >= T.MINUS: return Op(op, nenavedeno, self.faktor())
baza = self.baza()
if op := self >= T.NA: return Op(op, baza, self.faktor())
else: return baza
def baza(self) -> 'BROJ|IME|izraz':
if broj := self >= T.BROJ: return broj
elif varijabla := self >= T.IME:
varijabla.provjeri_tip() # zapravo provjeri deklaraciju
return varijabla
elif self >> T.OTV:
u_zagradi = self.izraz()
self >> T.ZATV
return u_zagradi
### Apstraktna sintaksna stabla
# Program: naredbe:[naredba] # rt.symtab:Memorija
# Pridruživanje: varijabla:IME tip:T? vrijednost:izraz
# Op: operator:T lijevo:izraz desno:izraz
def ažuriraj(var, token_za_tip):
if token_za_tip:
tip = Tip(token_za_tip)
if var in rt.symtab:
pravi = var.provjeri_tip()
if tip is pravi: raise var.redeklaracija()
else: raise var.krivi_tip(tip, pravi)
rt.symtab[var] = tip
return var.provjeri_tip()
class Program(AST):
naredbe: 'naredba*'
def provjeri_tipove(self):
for naredba in self.naredbe:
tip = naredba.provjeri_tip()
if tip: print(tip)
class Pridruživanje(AST):
varijabla: 'IME'
tip: 'Tip?'
vrijednost: 'izraz'
def provjeri_tip(self):
lijevo = self.varijabla.provjeri_tip()
desno = self.vrijednost.provjeri_tip()
if not desno <= lijevo: raise self.varijabla.krivi_tip(lijevo, desno)
class Op(AST):
operator: 'T'
lijevo: 'izraz'
desno: 'izraz'
def provjeri_tip(self):
if self.lijevo is nenavedeno: prvi = Tip.N # -x = 0 - x
else: prvi = self.lijevo.provjeri_tip()
o, drugi = self.operator, self.desno.provjeri_tip()
if o ^ T.KROZ: return Tip.Q
elif o ^ {T.PLUS, T.PUTA}: return max(prvi, drugi)
elif o ^ T.MINUS: return max(prvi, drugi, Tip.Z)
# semantika: a div b := floor(a/b), a mod b := a - a div b * b
elif o ^ T.DIV: return Tip.N if prvi is drugi is Tip.N else Tip.Z
elif o ^ T.MOD: return Tip.Q if prvi is Tip.Q else drugi
elif o ^ T.NA:
if drugi is Tip.N: return prvi
elif drugi is Tip.Z: return Tip.Q
else: raise o.krivi_tip(prvi, drugi)
else: assert False, f'nepokriveni slučaj operatora {o}!'
ast = P('''
rat a = 6 / 2
a = a + 4
nat b = 8 + 1
int c = 6 ^ 2
rat d = 6
d = d ^ 5
? b mod 1
? c div b
? 6 ^ -3 - 3
''')
prikaz(ast, 3)
ast.provjeri_tipove()
# DZ: Dodajte tipove R i C (u statičku analizu; računanje je druga stvar:)
<file_sep>"""Zadaća 2020. https://youtu.be/1JELGXoKSiI"""
from vepar import *
import fractions
class T(TipoviTokena):
PLUS, MINUS, PUTA, KROZ = '+-×÷'
MANJE, VEĆE, JEDNAKO, OTV, ZATV = '<>=()'
UNOS, ISPIS, UBROJ, UTEKST = 'unos', 'ispis', 'broj', 'tekst$'
ZA, DO, SLJEDEĆI = 'za', 'do', 'sljedeći'
AKO, INAČE, NADALJE = 'ako', 'inače', 'nadalje'
class BROJ(Token):
def vrijednost(t): return fractions.Fraction(t.sadržaj)
class TEKST(Token):
def vrijednost(t): return t.sadržaj[1:-1]
class BVAR(Token):
def vrijednost(t): return rt.memorija[t]
class TVAR(Token):
def vrijednost(t): return rt.memorija[t]
@lexer
def basic(lex):
for znak in lex:
if znak.isspace(): lex.zanemari()
elif znak.isdecimal():
lex.prirodni_broj(znak)
yield lex.token(T.BROJ)
elif znak.isalpha():
lex * str.isalnum
yield lex.literal_ili(T.TVAR if lex >= '$' else T.BVAR, case=False)
elif znak == ',':
lex - "'"
yield lex.token(T.TEKST)
elif znak == "'":
lex - "'"
lex.zanemari()
else: yield lex.literal(T)
### BKG
# start = naredbe -> naredba | naredbe naredba
# naredba -> pridruživanje | petlja | unos | ispis | grananje
# pridruživanje -> BVAR JEDNAKO broj | TVAR JEDNAKO tekst
# broj -> račun usporedba+ račun | račun | tekst JEDNAKO tekst
# usporedba -> MANJE | VEĆE | JEDNAKO
# račun -> član | račun PLUS član | račun MINUS član
# član -> faktor | član PUTA faktor | član KROZ faktor
# faktor -> BROJ | BVAR | OTV broj ZATV | UBROJ OTV tekst ZATV
# tekst -> TEKST | TVAR | tekst PLUS tekst | UTEKST OTV broj ZATV
# petlja -> ZA BVAR# JEDNAKO broj DO broj naredbe SLJEDEĆI BVAR#
# unos -> UNOS BVAR | UNOS TVAR
# ispis -> ISPIS broj | ISPIS tekst | ISPIS SLJEDEĆI
# grananje -> AKO broj naredbe (INAČE naredbe)? NADALJE?
class P(Parser):
def start(p) -> 'Program': return Program(p.naredbe())
def naredbe(p) -> '(pridruživanje|petlja|unos|ispis|grananje)*':
lista = []
while ...:
if p > {T.BVAR, T.TVAR}: lista.append(p.pridruživanje())
elif p > T.ZA: lista.append(p.petlja())
elif p > T.UNOS: lista.append(p.unos())
elif p > T.ISPIS: lista.append(p.ispis())
elif p > T.AKO: lista.append(p.grananje())
else: return lista
def pridruživanje(p) -> 'Pridruživanje':
varijabla = p >> {T.BVAR, T.TVAR}
p >> T.JEDNAKO
if varijabla ^ T.BVAR: pridruženo = p.broj()
elif varijabla ^ T.TVAR: pridruženo = p.tekst()
return Pridruživanje(varijabla, pridruženo)
def petlja(p) -> 'Petlja':
p >> T.ZA
varijabla = p >> T.BVAR
p >> T.JEDNAKO
početak = p.broj()
p >> T.DO
kraj = p.broj()
tijelo = p.naredbe()
p >> T.SLJEDEĆI
if varijabla != (p >> T.BVAR):
raise SemantičkaGreška('Varijable u petlji se ne podudaraju')
return Petlja(varijabla, početak, kraj, tijelo)
def unos(p) -> 'Unos':
p >> T.UNOS
return Unos(p >> {T.BVAR, T.TVAR})
def ispis(p) -> 'Ispis':
p >> T.ISPIS
if p > {T.BROJ, T.BVAR, T.OTV, T.UBROJ}: što = p.broj()
elif p > {T.TEKST, T.TVAR, T.UTEKST}:
što = p.tekst()
if p >= T.JEDNAKO: što = JednakTekst(što, p.tekst())
else: što = p >> T.SLJEDEĆI
return Ispis(što)
def grananje(p) -> 'Grananje':
p >> T.AKO
uvjet = p.broj()
onda = p.naredbe()
inače = []
if p >= T.INAČE: inače = p.naredbe()
p >> {T.NADALJE, KRAJ}
return Grananje(uvjet, onda, inače)
def broj(p) -> 'Usporedba|račun|JednakTekst':
if p > {T.BROJ, T.BVAR, T.OTV, T.UBROJ}:
prvi = p.račun()
usporedba = {T.MANJE, T.VEĆE, T.JEDNAKO}
manje = veće = jednako = nenavedeno
if p > usporedba:
while u := p >= usporedba:
if u ^ T.MANJE: manje = u
elif u ^ T.VEĆE: veće = u
elif u ^ T.JEDNAKO: jednako = u
return Usporedba(prvi, p.račun(), manje, veće, jednako)
else: return prvi
else:
prvi = p.tekst()
p >> T.JEDNAKO
drugi = p.tekst()
return JednakTekst(prvi, drugi)
def račun(p) -> 'član|Osnovna':
t = p.član()
while op := p >= {T.PLUS, T.MINUS}: t = Osnovna(op, t, p.član())
return t
def član(p) -> 'faktor|Osnovna':
t = p.faktor()
while op := p >= {T.PUTA, T.KROZ}: t = Osnovna(op, t, p.faktor())
return t
def faktor(p) -> 'broj|TekstUBroj|BROJ|BVAR':
if p >= T.OTV:
u_zagradi = p.broj()
p >> T.ZATV
return u_zagradi
elif p >= T.UBROJ:
p >> T.OTV
argument = p.tekst()
p >> T.ZATV
return TekstUBroj(argument)
else: return p >> {T.BROJ, T.BVAR}
def tekst(p) -> 'BrojUTekst|TEKST|TVAR|Konkatenacija':
if p >= T.UTEKST:
p >> T.OTV
trenutni = BrojUTekst(p.broj())
p >> T.ZATV
else: trenutni = p >> {T.TEKST, T.TVAR}
if p >= T.PLUS: return Konkatenacija(trenutni, p.tekst())
else: return trenutni
### AST
# Program: naredbe:[naredba]
# naredba: Unos: varijabla:BVAR|TVAR
# Ispis: što:broj|tekst|SLJEDEĆI
# Pridruživanje: varijabla:BVAR|!TVAR što:broj|!tekst
# Petlja: varijabla:BVAR početak:broj kraj:broj tijelo:[naredba]
# Grananje: uvjet:broj onda:[naredba] inače:[naredba]
# broj: JednakTekst: lijevo:tekst desno:tekst
# Usporedba: lijevo:broj desno:broj
# manje:MANJE? veće:VEĆE? jednako:JEDNAKO?
# Osnovna: operacija:PLUS|MINUS|PUTA|KROZ lijevo:broj desno:broj
# TekstUBroj: tekst:tekst
# BROJ: Token
# BVAR: Token
# tekst: BrojUTekst: broj:broj
# Konkatenacija: lijevo:tekst desno:tekst
# TEKST: Token
# TVAR: Token
class Program(AST):
naredbe: 'naredba*'
def izvrši(program):
rt.memorija = Memorija()
for naredba in program.naredbe: naredba.izvrši()
class Unos(AST):
varijabla: 'BVAR|TVAR'
def izvrši(unos):
v = unos.varijabla
prompt = f'\t{v.sadržaj}? '
if v ^ T.TVAR: rt.memorija[v] = input(prompt)
elif v ^ T.BVAR:
while ...:
t = input(prompt)
try: rt.memorija[v] = fractions.Fraction(t.replace('÷', '/'))
except ValueError: print(end='To nije racionalni broj! ')
else: break
else: assert False, f'Nepoznat tip varijable {v}'
class Ispis(AST):
što: 'broj|tekst|SLJEDEĆI'
def izvrši(ispis):
if ispis.što ^ T.SLJEDEĆI: print()
else:
t = ispis.što.vrijednost()
if isinstance(t, fractions.Fraction): t = str(t).replace('/', '÷')
print(t, end=' ')
class Pridruživanje(AST):
varijabla: 'BVAR|!TVAR'
što: 'broj|!tekst'
def izvrši(self): rt.memorija[self.varijabla] = self.što.vrijednost()
class Petlja(AST):
varijabla: 'BVAR'
početak: 'broj'
kraj: 'broj'
tijelo: 'naredba*'
def izvrši(petlja):
kv = petlja.varijabla
p, k = petlja.početak.vrijednost(), petlja.kraj.vrijednost()
korak = 1 if p <= k else -1
rt.memorija[kv] = p
while (rt.memorija[kv] - k) * korak <= 0:
for naredba in petlja.tijelo: naredba.izvrši()
rt.memorija[kv] += korak
class Grananje(AST):
uvjet: 'broj'
onda: 'naredba*'
inače: 'naredba*'
def izvrši(grananje):
b = grananje.uvjet.vrijednost()
if b == ~0: sljedeći = grananje.onda
elif b == 0: sljedeći = grananje.inače
else: raise GreškaIzvođenja(f'Tertium ({b}) non datur!')
for naredba in sljedeći: naredba.izvrši()
class JednakTekst(AST):
lijevo: 'tekst'
desno: 'tekst'
def vrijednost(self):
return -(self.lijevo.vrijednost() == self.desno.vrijednost())
class Usporedba(AST):
lijevo: 'broj'
desno: 'broj'
manje: 'MANJE?'
veće: 'VEĆE?'
jednako: 'JEDNAKO?'
def vrijednost(self):
l, d = self.lijevo.vrijednost(), self.desno.vrijednost()
return -((self.manje and l < d) or (self.jednako and l == d)
or (self.veće and l > d) or 0)
class Osnovna(AST):
operacija: 'T'
lijevo: 'broj'
desno: 'broj'
def vrijednost(self):
l, d = self.lijevo.vrijednost(), self.desno.vrijednost()
o = self.operacija
if o ^ T.PLUS: return l + d
elif o ^ T.MINUS: return l - d
elif o ^ T.PUTA: return l * d
elif o ^ T.KROZ:
if d: return fractions.Fraction(l, d)
else: raise o.iznimka('Nazivnik ne smije biti nula!')
else: assert False, f'Nepokrivena binarna operacija {o}'
class TekstUBroj(AST):
tekst: 'tekst'
def vrijednost(self):
arg = self.tekst.vrijednost()
try: return fractions.Fraction(arg.replace('÷', '/'))
except ValueError: raise GreškaIzvođenja(f'{arg!r} nije broj')
class BrojUTekst(AST):
broj: 'broj'
def vrijednost(self):
return str(self.broj.vrijednost()).replace('/', '÷')
class Konkatenacija(AST):
lijevo: 'tekst'
desno: 'tekst'
def vrijednost(self):
return self.lijevo.vrijednost() + self.desno.vrijednost()
ast = P('''
ispis sljedeći ispis ,Gaußova dosjetka' ispis sljedeći
crtice$ = ,'
za i=1 do 16
crtice$ = crtice$ + ,-'
sljedeći i
ispis crtice$ ispis sljedeći
ispis ,Prirodni broj'
unos n
ako n = < 0
ispis ,To nije prirodni broj! Više sreće drugi put.'
ispis sljedeći inače 'ovaj "inače" se odnosi na čitav ostatak programa'
rješenje =
n×(n+1) ÷ 2
ispis ,Zbroj prvih' ispis n ispis ,prirodnih brojeva'
ispis ,iznosi' ispis tekst$(rješenje) + ,,' ispis sljedeći
ispis ,što se može provjeriti i ručno:' ispis sljedeći
zbroj = 0
za pribrojnik=1 do n
ako pribrojnik > 1 ispis ,+'
nadalje
ispis pribrojnik
zbroj = zbroj + pribrojnik
sljedeći pribrojnik
ispis ,=' ispis zbroj ispis sljedeći
ako zbroj = rješenje
ispis ,Kao što vidimo, Gaußova dosjetka funkcionira.' ispis sljedeći
inače ispis ,Hm, nešto nije u redu. Obratite se administratoru Svemira.'
ispis sljedeći
''')
prikaz(ast)
ast.izvrši()
<file_sep>import collections
from util import *
class BeskontekstnaGramatika(types.SimpleNamespace):
"""Gramatika koja generira beskontekstni jezik."""
@classmethod
def iz_komponenti(klasa, varijable, abeceda, pravila, početna):
"""Sipser page 104 definition 2.2 - definicija iz četvorke."""
assert abeceda
simboli = disjunktna_unija(varijable, abeceda)
assert all(set(pravilo) <= simboli for pravilo in pravila)
assert početna in varijable
pozitivna = None
del simboli
return klasa(**vars())
@property
def komponente(G):
"""Sipser page 104 definition 2.2 - rastav u četvorku."""
return G.varijable, G.abeceda, G.pravila, G.početna
@property
def simboli(G):
"""Skup simbola (varijabli i znakova zajedno) Y."""
return disjunktna_unija(G.varijable, G.abeceda)
@classmethod
def iz_strelica(klasa, strelice):
"""Parsiranje streličnog zapisa beskontekstne gramatike.
Pogledati funkciju util.parsiraj_strelice_BKG za detalje."""
return klasa.iz_komponenti(*parsiraj_strelice_BKG(strelice))
@classmethod
def iz_konačnog_automata(klasa, ka):
"""Pretvorba konačnog automata u desnolinearnu gramatiku."""
nka = NedeterminističniKonačniAutomat.iz_konačnog_automata(ka)
rezultat = klasa.iz_nedeterminističnog_konačnog_automata(nka)
assert rezultat.desnolinearna()
return rezultat
@classmethod
def iz_nedeterminističnog_konačnog_automata(klasa, nka):
"""Pretvorba NKA u desnolinearnu gramatiku."""
Q, Σ, Δ, q0, F = nka.komponente
P = {(p,α,q) if α != ε else (p,q) for p,α,q in Δ} | {(q,) for q in F}
return BeskontekstnaGramatika.iz_komponenti(Q, Σ, P, q0)
def daje(gramatika, prije, poslije):
"""Daje li riječ prije riječ poslije po pravilima gramatike?
Vraća None, ili pravilo i mjesto na kojem ga treba primijeniti."""
assert set(prije) | set(poslije) <= gramatika.simboli
for mjesto, simbol in enumerate(prije):
if simbol in gramatika.varijable:
for pravilo in gramatika.pravila:
if simbol == pravilo[0]:
if primijeni(pravilo, prije, mjesto) == poslije:
return pravilo, mjesto
def validan(gramatika, izvod):
"""Je li izvod u skladu s pravilima gramatike?"""
početak, *ostatak = izvod
if list(početak) != [gramatika.početna]:
return False
for prije, poslije in zip(izvod, ostatak):
if not gramatika.daje(prije, poslije):
print(prije, poslije)
return False
return set(izvod[~0]) <= gramatika.abeceda
def desnolinearna(gramatika):
"""Je li gramatika desnolinearna?"""
for A, *zamjene in gramatika.pravila:
if not zamjene:
continue
elif len(zamjene) == 2:
b, C = zamjene
if b in gramatika.abeceda and C in gramatika.varijable:
continue
return False
return True
def Chomskyjeva(gramatika):
"""Je li gramatika u Chomskyjevoj normalnoj formi?
Ako jest, postavlja i oznaku da je gramatika sigurno pozitivna."""
for A, *zamjene in gramatika.pravila:
if len(zamjene) == 1:
a, = zamjene
if a in gramatika.abeceda:
continue
elif len(zamjene) == 2:
if set(zamjene) <= gramatika.varijable:
continue
return False
if gramatika.pozitivna is None:
gramatika.pozitivna = True
return True
def faza_START(G):
stara_S = G.početna
for A, *zamjene in G.pravila:
if stara_S in zamjene:
nova_S = novo('S', G.varijable)
G.varijable.add(nova_S)
G.pravila.add((nova_S, stara_S))
G.početna = nova_S
break
def faza_TERM(G):
N = {}
for α in G.abeceda:
for pravilo in G.pravila.copy():
if α in pravilo and len(pravilo) > 2:
if α not in N:
N[α] = novo('N' + str(α), G.simboli)
G.varijable.add(N[α])
G.pravila.add((N[α], α))
G.pravila.remove(pravilo)
G.pravila.add(tuple(N[α] if s == α else s for s in pravilo))
def faza_BIN(G):
for pravilo in G.pravila.copy():
if len(pravilo) >= 4:
G.pravila.remove(pravilo)
početna = trenutna = pravilo[0]
for simbol in pravilo[1:-2]:
vezna = novo(početna, G.varijable)
G.varijable.add(vezna)
G.pravila.add((trenutna, simbol, vezna))
trenutna = vezna
G.pravila.add((trenutna, pravilo[~1], pravilo[~0]))
def faza_DEL(G):
nep = set()
while ...:
for A, *zamjene in G.pravila:
if A not in nep and set(zamjene) <= nep:
nep.add(A)
break
else: break
G.pozitivna = G.početna not in nep
for A, *zamjene in G.pravila.copy():
pojave = {i for i, simbol in enumerate(zamjene) if simbol in nep}
if pojave:
for podskup in partitivni_skup(pojave):
novo_pravilo = [A]
for i, simbol in enumerate(zamjene):
if i not in podskup:
novo_pravilo.append(simbol)
G.pravila.add(tuple(novo_pravilo))
G.pravila -= {(A,) for A in G.varijable}
def faza_UNIT(G):
maknuta = set()
while ...:
for pravilo in G.pravila.copy():
if len(pravilo) == 2 and pravilo[1] in G.varijable:
A, B = pravilo
G.pravila.remove(pravilo)
maknuta.add(pravilo)
for zamjensko in G.pravila.copy():
if zamjensko[0] == B:
B, *u = zamjensko
novo = tuple([A] + u)
if novo not in maknuta:
G.pravila.add(novo)
break
else: break
def ChNF(gramatika):
"""Ekvivalentna (do na ε) gramatika u Chomskyjevoj normalnoj formi."""
if gramatika.Chomskyjeva(): return gramatika
G = copy.deepcopy(gramatika)
for f in 'START TERM BIN DEL UNIT'.split(): getattr(G, 'faza_' + f)()
return G
def označi(gramatika, l):
"""Označava stanja gramatike dodatnom oznakom l, radi disjunktnosti."""
def označi_pravilo(p, l):
for simbol in p:
if simbol in gramatika.varijable: yield označi1(simbol, l)
else: yield simbol
V, Σ, P, S = gramatika.komponente
Vl = {označi1(A, l) for A in V}
Pl = {tuple(označi_pravilo(p, l)) for p in P}
Sl = označi1(S, l)
return BeskontekstnaGramatika.iz_komponenti(Vl, Σ, Pl, Sl)
def unija(G1, G2):
"""Beskontekstna gramatika koja generira L(G1)∪L(G2)."""
assert G1.abeceda == G2.abeceda
if not G1.varijable.isdisjoint(G2.varijable):
G1 = G1.označi(1)
G2 = G2.označi(2)
V1, Σ, P1, S1 = G1.komponente
V2, Σ, P2, S2 = G2.komponente
S = novo('S', V1 | V2 | Σ)
V = disjunktna_unija(V1, V2, {S})
P = disjunktna_unija(P1, P2, {(S, S1), (S, S2)})
return BeskontekstnaGramatika.iz_komponenti(V, Σ, P, S)
def konkatenacija(G1, G2):
"""Beskontekstna gramatika koja generira L(G1)L(G2)."""
assert G1.abeceda == G2.abeceda
if not G1.varijable.isdisjoint(G2.varijable):
G1 = G1.označi(3)
G2 = G2.označi(4)
V1, Σ, P1, S1 = G1.komponente
V2, Σ, P2, S2 = G2.komponente
S = novo('S', V1 | V2 | Σ)
V = disjunktna_unija(V1, V2, {S})
P = disjunktna_unija(P1, P2, {(S, S1, S2)})
return BeskontekstnaGramatika.iz_komponenti(V, Σ, P, S)
def plus(G):
"""Beskontekstna gramatika koja generira Kleenejev plus od L(G)."""
V0, Σ, P0, S0 = G.komponente
S = novo('S', V0)
V = disjunktna_unija(V0, {S})
P = disjunktna_unija(P0, {(S, S0, S), (S, S0)})
return BeskontekstnaGramatika.iz_komponenti(V, Σ, P, S)
def zvijezda(G):
"""Beskontekstna gramatika koja generira Kleenejevu zvijezdu od L(G)."""
V0, Σ, P0, S0 = G.komponente
S = novo('S', V0)
V = disjunktna_unija(V0, {S})
P = disjunktna_unija(P0, {(S, S0, S), (S,)})
return BeskontekstnaGramatika.iz_komponenti(V, Σ, P, S)
def CYK(gramatika, riječ):
"""Cocke-Younger-Kasami algoritam za problem prihvaćanja za BKG."""
G = gramatika.ChNF()
if not riječ: return not G.pozitivna
širenja = {V: set() for V in G.varijable}
for pravilo in G.pravila:
if len(pravilo) == 3:
A, B, C = pravilo
širenja[A].add((B, C))
@memoiziraj
def izvodi(A, i, j):
assert j > i
if j - i == 1: return (A, riječ[i]) in G.pravila
for k in range(i + 1, j):
for B, C in širenja[A]:
if izvodi(B, i, k) and izvodi(C, k, j): return True
return False
return izvodi(G.početna, 0, len(riječ))
def ispiši_strelice(G):
sažeta = collections.defaultdict(set, {G.početna: set()})
for v, *desno in G.pravila: sažeta[v].add(' '.join(desno) or 'ε')
for v, desne in sažeta.items(): print(v, '->', ' | '.join(desne))
<file_sep>"""Regularni izrazi kao beskontekstni jezik. (Po kolokviju 10. veljače 2017.)
Izgrađeni su od osnovnih (inicijalnih) regularnih izraza:
/0 prazan jezik
/1 jezik koji se sastoji samo od prazne riječi
x jezik koji se sastoji od jednoslovne riječi x
- specijalni znakovi zahtijevaju escaping pomoću /
pomoću operatora:
| (infiksni) unija
(ne piše se) konkatenacija
*,+,? (postfiksni) Kleenejevi operatori"""
from vepar import *
import RI # kao backend
specijalni = '()|*+?'
class T(TipoviTokena):
OTV, ZATV, ILI, ZVIJEZDA, PLUS, UPITNIK = specijalni
PRAZAN, EPSILON = '/0', '/1'
class ZNAK(Token): pass
@lexer
def ri(lex):
for znak in lex:
if znak in specijalni: yield lex.literal(T)
elif znak == '/':
sljedeći = next(lex)
if not sljedeći: raise lex.greška('/ na kraju stringa')
elif sljedeći in {'/', *specijalni}: yield lex.token(T.ZNAK)
elif sljedeći in {'0', '1'}: yield lex.literal(T)
else: raise lex.greška('nedefinirana /-sekvenca')
else: yield lex.token(T.ZNAK)
### Beskontekstna gramatika
# rx -> disjunkt | disjunkt ILI rx
# disjunkt -> faktor | faktor disjunkt
# faktor -> element | faktor ZVIJEZDA | faktor PLUS | faktor UPITNIK
# element -> PRAZAN | EPSILON | ZNAK | OTV rx ZATV
class P(Parser):
def rx(self) -> 'disjunkt|Unija':
disjunkt = self.disjunkt()
if self >= T.ILI: return RI.Unija(disjunkt, self.rx())
else: return disjunkt
def disjunkt(self) -> 'faktor|Konkatenacija':
faktor = self.faktor()
if self > {T.PRAZAN, T.EPSILON, T.ZNAK, T.OTV}:
return RI.Konkatenacija(faktor, self.disjunkt())
else: return faktor
def faktor(self) -> 'element|Zvijezda|Plus|Upitnik':
trenutni = self.element()
while ...:
if self >= T.ZVIJEZDA: trenutni = RI.Zvijezda(trenutni)
elif self >= T.PLUS: trenutni = RI.Plus(trenutni)
elif self >= T.UPITNIK: trenutni = RI.Upitnik(trenutni)
else: return trenutni
def element(self) -> 'Prazan|Epsilon|Elementarni|rx':
if self >= T.PRAZAN: return RI.prazan
elif self >= T.EPSILON: return RI.epsilon
elif znak := self >= T.ZNAK:
t = znak.sadržaj
if t.startswith('/'): kosa_crta, t = t
return RI.Elementarni(t)
elif self >> T.OTV:
u_zagradi = self.rx()
self >> T.ZATV
return u_zagradi
### Kao ASTove koristimo klase iz modula RI
# rx: prazan
# epsilon
# Elementarni: znak:str (duljine 1)
# Unija: r1:rx r2:rx
# Konkatenacija: r1:rx r2:rx
# Zvijezda: r:rx
# Plus: r:rx
# Upitnik: r:rx
ri(r := '(a(/*c?)+)?')
prikaz(P(r))
print(*P(r).početak(20))
<file_sep>"""Leksička, sintaksna, semantička analiza te izvođenje programa."""
__version__ = '2.5'
import enum, types, collections, contextlib, itertools, functools, \
dataclasses, textwrap, inspect, math
the_lexer = None
def lexer(gen):
global the_lexer
assert the_lexer is None, 'Lexer je već postavljen!'
assert inspect.isgeneratorfunction(gen), 'Lexer mora biti generator!'
the_lexer = gen
@functools.wraps(gen)
def tokeniziraj(ulaz):
"""Pregledno ispisuje pronađene tokene, za debugiranje tokenizacije."""
if '\n' not in ulaz: print('Tokenizacija:', ulaz)
for token in the_lexer(Tokenizer(ulaz)):
r = raspon(token)
if r.startswith('Znak'): print(f'\t\t{r:15}: {token}')
else: print(f'\t{r:23}: {token}')
return tokeniziraj
def paše(znak, uvjet):
"""Zadovoljava li znak zadani uvjet (funkcija, znak ili skup)."""
if isinstance(uvjet, str):
assert len(uvjet) <= 1, 'Znakovi moraju biti duljine 1!'
return znak == uvjet
elif callable(uvjet):
rezultat = uvjet(znak)
assert isinstance(rezultat, bool), 'Uvjet nije predikat!'
return rezultat
elif isinstance(uvjet, (set, frozenset)):
return any(paše(znak, disjunkt) for disjunkt in uvjet)
else: assert False, f'Nepoznata vrsta uvjeta {uvjet}!'
def raspis(uvjet):
if isinstance(uvjet, str): yield repr(uvjet)
elif callable(uvjet): yield uvjet.__name__
elif isinstance(uvjet, (set, frozenset)):
yield from itertools.chain.from_iterable(map(raspis, uvjet))
else: assert False, f'Nepoznata vrsta uvjeta {uvjet}!'
def omotaj(metoda):
"""Jednostavni wrapper za metode parsera."""
@functools.wraps(metoda)
def omotano(self, *args, **kw):
početak = self.pogledaj()._početak
pvr = metoda(self, *args, **kw)
kraj = self.zadnji._kraj
if pvr is None: raise NoneInAST(textwrap.dedent(f'''
Sve metode parsera moraju vratiti vrijednost!
Provjerite metodu {metoda.__name__}.
Umjesto None vratite nenavedeno.'''))
if isinstance(pvr, AST): pvr._početak, pvr._kraj = početak, kraj
return pvr
return omotano
class EnumItem:
def __init__(self, name, value): self.name, self.value = name, value
if False:
class TokenEnumDict(dict):
def __init__(self):
super().__init__(_back_ = {})
def __setitem__(self, key, value):
if key.startswith('_'): return super().__setitem__(key, value)
item = EnumItem(key, value)
super().__setitem__(key, item)
self._back_[value] = item
def __getitem__(self, key): return self.forward[key]
def __call__(self, value): return self.backward[value]
class TipoviTokenaMeta(type):
if False:
@classmethod
def __prepare__(cls, name, bases): return TokenEnumDict()
def __new__(metaclass, classname, bases, classdict):
cls = super().__new__(metaclass, classname, bases, classdict)
cls._back_ = {}
for name, value in vars(cls).copy().items():
if not name.startswith('_'):
item = cls()
item.name, item.value = name, value
setattr(cls, name, item)
cls._back_[value] = item
return cls
def __iter__(self):
for name, item in vars(self).items():
if not name.startswith('_'): yield item
class TipoviTokena(metaclass=TipoviTokenaMeta): pass
class Kontekst(type):
"""Metaklasa: upravitelj konteksta (with) za očekivanu grešku."""
def __enter__(self): pass
def __exit__(self, e_type, e_val, e_tb):
if e_type is None: raise Greška(f'{self.__name__} nije dignuta')
elif issubclass(e_type, self):
print(e_type.__name__, e_val, sep=': ')
return True
class Runtime(types.SimpleNamespace):
"""Globalni objekt za pamćenje runtime konteksta (npr. memorije)."""
def __delattr__(self, atribut):
with contextlib.suppress(AttributeError): super().__delattr__(atribut)
rt = Runtime()
# TODO: bolji API: Greška(poruka, pozicija ili token ili AST...)
# ali ostaviti i lex.greška() i parser.greška() for convenience
class Greška(Exception, metaclass=Kontekst): """Greška vezana uz poziciju."""
class LeksičkaGreška(Greška): """Greška nastala u leksičkoj analizi."""
class SintaksnaGreška(Greška): """Greška nastala u sintaksnoj analizi."""
class SemantičkaGreška(Greška): """Greška nastala u semantičkoj analizi."""
class GreškaIzvođenja(Greška): """Greška nastala u izvođenju."""
class E(TipoviTokena): KRAJ = None
KRAJ = E.KRAJ
class NoneInAST(Exception): """U apstraktnom sintaksnom stablu se našao None."""
cache = functools.lru_cache(maxsize=None)
def Registri(prefiks='_t', start=0):
for i in itertools.count(start): yield prefiks + str(i)
class NelokalnaKontrolaToka(Exception):
"""Bazna klasa koja služi za implementaciju nelokalne kontrole toka."""
@property
def preneseno(self):
"""Vrijednost koja je prenesena "unatrag" prema korijenu."""
return self.args[0] if self.args else nenavedeno
class Tokenizer:
"""Klasa za rastavljanje niza znakova na tokene."""
def __init__(self, string):
"""Inicijalizira tokenizer tako da čita string (od početka)."""
self.pročitani, self.buffer, self.stream = [], None, iter(string)
self.i = int('\n' in string and not string.startswith('\n'))
self.j = 0
self.početak = 0, 1
@property
def sadržaj(self):
"""Što je tokenizer do sada pročitao, od zadnjeg prepoznatog tokena."""
return ''.join(self.pročitani)
def čitaj(self):
"""Čita sljedeći znak iz buffera ili stringa."""
znak = next(self.stream, '') if self.buffer is None else self.buffer
self.pročitani.append(znak)
self.buffer = None
if znak == '\n':
self.gornji_j = self.j
self.i += 1
self.j = 0
else: self.j += 1
return znak
def vrati(self):
"""Poništava čitanje zadnjeg pročitanog znaka."""
assert self.buffer is None, 'Buffer je pun'
self.buffer = self.pročitani.pop()
if self.j: self.j -= 1
else:
self.j = self.gornji_j
self.i -= 1
del self.gornji_j
def pogledaj(self):
"""'Viri' u sljedeći element, 'bez' čitanja."""
znak = self.čitaj()
self.vrati()
return znak
def slijedi(self, uvjet):
"""Čita sljedeći znak ako i samo ako zadovoljava uvjet."""
return paše(self.čitaj(), uvjet) or self.vrati()
def vidi(self, uvjet):
"""Ispituje sljedeći znak ('bez' čitanja)."""
return paše(self.pogledaj(), uvjet)
def zvijezda(self, uvjet):
"""Čita Kleene* (nula ili više) znakova koji zadovoljavaju uvjet."""
while paše(self.čitaj(), uvjet): pass
self.vrati()
def plus(self, uvjet):
"""Čita Kleene+ (jedan ili više) znakova koji zadovoljavaju uvjet."""
self.nužno(uvjet)
self.zvijezda(uvjet)
def nužno(self, uvjet):
"""Čita zadani znak, ili prijavljuje leksičku grešku."""
if not paše(self.čitaj(), uvjet):
raise self.greška(f"očekivano {' ili '.join(raspis(uvjet))}")
def pročitaj_do(self, uvjet, *, uključivo=True, više_redova=False):
"""Čita sve znakove do ispunjenja uvjeta."""
poruka = ' ni '.join(raspis(uvjet)) + ' nije pronađen '
while ...:
znak = self.čitaj()
if paše(znak, uvjet):
if not uključivo: self.vrati()
break
elif znak == '\n' and not više_redova:
raise self.greška(poruka + 'u retku')
elif not znak:
raise self.greška(poruka + 'do kraja ulaza')
def __lt__(self, uvjet):
return self.pročitaj_do(uvjet, uključivo=False)
def greška(self, info=''):
"""Konstruira leksičku grešku."""
if self.buffer is not None: self.čitaj()
if self.j: i, j = self.i, self.j
else: i, j = self.i - 1, self.gornji_j + 1
poruka = f'Redak {i}, stupac {j}: ' if i else f'Znak #{j}: '
zadnji = self.pročitani.pop()
opis = f'znak {zadnji!r}' if zadnji else 'kraj ulaza'
poruka += f'neočekivani {opis}'
if info: poruka += f'\n\t({info})'
return LeksičkaGreška(poruka)
def token(self, tip):
"""Konstruira token zadanog tipa i pročitanog sadržaja."""
t = Token(tip, self.sadržaj)
t._početak = self.početak
t._kraj = self.i, self.j
self.zanemari()
return t
def literal(self, odakle, *, case=True):
"""Doslovni token s pročitanim sadržajem, ili leksička greška."""
t = self.sadržaj if case else self.sadržaj.casefold()
for e in odakle:
if e.value == t or getattr(e.value, 'literal', None) == t:
return self.token(e)
else: raise self.greška()
def literal_ili(self, inače, *, case=True):
"""Doslovni token ako je nađen po sadržaju, ili token tipa inače."""
t = self.sadržaj if case else self.sadržaj.casefold()
for e in type(inače):
if e.value == t or getattr(e.value, 'literal', None) == t:
return self.token(e)
else: return self.token(inače)
def zanemari(self):
"""Resetira pročitano (pretvara se da nije ništa pročitano)."""
self.pročitani.clear()
self.početak = self.i, self.j + 1
def __iter__(self):
"""Omogućuje prolazak `for znak in lex:`."""
return iter(self.čitaj, '')
def prirodni_broj(self, početak, *, nula=True):
"""Čita prirodni broj bez vodećih nula, ili nulu ako je dozvoljena."""
if not početak: početak = self.čitaj()
if početak.isdecimal():
if int(početak):
pročitano = [početak]
while (z := self.čitaj()).isdecimal(): pročitano.append(z)
self.vrati()
return int(''.join(pročitano))
elif nula:
if not self.pogledaj().isdecimal(): return 0
else: raise self.greška('vodeće nule nisu dozvoljene')
else: raise self.greška('nula nije dozvoljena ovdje')
else: raise self.greška('očekivan prirodni broj')
__next__ = čitaj
__ge__ = slijedi
__gt__ = vidi
__mul__ = zvijezda
__add__ = plus
__rshift__ = nužno
__sub__ = __le__ = pročitaj_do
class Token(collections.namedtuple('TokenTuple', 'tip sadržaj')):
"""Leksičke jedinice ulaza čiji tipovi upravljaju sintaksnom analizom."""
def __new__(cls, tip, sadržaj=None):
"""Konstruira novi token zadanog tipa i (podrazumijevanog) sadržaja."""
if sadržaj is None:
sadržaj = tip.value
if isinstance(sadržaj, type): sadržaj = sadržaj.literal
if isinstance(tip.value, type): cls = tip.value
return super().__new__(cls, tip, sadržaj)
def __init__(self, *args):
"""Inicijalizacija tokena za potrebe parsiranja."""
self.uspoređeni = set()
self.razriješen = False
def __repr__(self):
"""Za ispis tokena u obliku TIP'sadržaj'."""
return self.tip.name + repr(self.sadržaj)
def __xor__(self, tip):
"""Vraća sebe (istina) ako je zadanog tipa, inače nenavedeno (laž)."""
if not isinstance(tip, set): tip = {tip}
self.uspoređeni |= tip
if self.tip in tip:
self.razriješen = True
return self
else: return nenavedeno
def neočekivan(self, info=''):
"""Konstruira sintaksnu grešku: neočekivani tip tokena."""
if self.tip is KRAJ: poruka = 'Neočekivani kraj ulaza'
else: poruka = raspon(self) + f': neočekivani token {self!r}'
if info: poruka += f' ({info})'
uspoređeni = sorted(t.name for t in self.uspoređeni if t != self.tip)
if uspoređeni: poruka += f"\n\tOčekivano: {' ili '.join(uspoređeni)}"
return SintaksnaGreška(poruka)
def redeklaracija(self, prvi=None):
"""Konstruira semantičku grešku redeklariranog simbola."""
poruka = raspon(self) + f': redeklaracija {self!r}'
if prvi: poruka += '\n\tPrva deklaracija: ' + raspon(prvi).lower()
return SemantičkaGreška(poruka)
def nedeklaracija(self, info=''):
"""Konstruira semantičku grešku nedeklariranog simbola."""
poruka = raspon(self) + f': nedeklarirano {self!r}'
if info: poruka += f' ({info})'
return SemantičkaGreška(poruka)
def krivi_sadržaj(self, info):
"""Konstruira leksičku grešku: token nema dobar sadržaj."""
poruka = raspon(self) + f': {self!r}: {info}'
return LeksičkaGreška(poruka)
def iznimka(self, info):
"""Konstruira grešku izvođenja iz poruke ili Pythonove iznimke."""
if isinstance(info, BaseException):
info = type(info).__name__ + ': ' + info.args[0]
poruka = raspon(self) + f':\n\t{self!r}: {info}'
return GreškaIzvođenja(poruka)
def krivi_tip(self, *tipovi):
"""Konstruira semantičku grešku nepodudarajućih (statičkih) tipova."""
poruka = raspon(self) + f': {self!r}: tipovi ne odgovaraju: '
poruka += ' vs. '.join(map(str, tipovi))
return SemantičkaGreška(poruka)
@classmethod
def kraj(cls):
"""Oznaka kraja niza tokena."""
t = cls(KRAJ, '')
t._početak = t._kraj = 'zadnji', 'nepoznat'
t.razriješen = False
return t
class Parser:
def __new__(cls, ulaz):
"""(Tokenizira i) parsira ulaz u apstraktno sintaksno stablo."""
if the_lexer is None:
raise LookupError('Dekorirajte generator tokena s @lexer!')
self = super().__new__(cls)
self.buffer = self.zadnji = None
self.KRAJ = Token.kraj()
self.stream = the_lexer(Tokenizer(ulaz))
rezultat = self.start()
self >> KRAJ
return rezultat
def __init_subclass__(cls):
prva = None
for ime, metoda in vars(cls).items():
if ime.startswith('_'): continue
if prva is None: prva = metoda
if isinstance(metoda, types.FunctionType):
setattr(cls, ime, omotaj(metoda))
if not hasattr(cls, 'start'): cls.start = omotaj(prva)
def čitaj(self):
"""Čitanje sljedećeg tokena iz buffera ili inicijalnog niza."""
token = self.buffer
if token is None:
if self.zadnji is not None and not self.zadnji.razriješen:
raise self.greška()
token = next(self.stream, self.KRAJ)
self.buffer = None
self.zadnji = token
return token
def vrati(self):
"""Poništavanje čitanja zadnjeg pročitanog tokena."""
assert self.buffer is None, 'Buffer je pun'
self.buffer = self.zadnji
return nenavedeno
pogledaj = Tokenizer.pogledaj
def nužno(self, tip):
"""Čita token odgovarajućeg tipa, ili javlja sintaksnu grešku."""
token = self.čitaj()
if token ^ tip: return token
self.vrati()
raise self.greška()
def slijedi(self, tip):
"""Čita sljedeći token samo ako je odgovarajućeg tipa."""
return self.zadnji if self.čitaj() ^ tip else self.vrati()
def vidi(self, tip):
"""Je li sljedeći token ('bez' čitanja) navedenog tipa ili tipova?"""
return self.pogledaj() ^ tip
__rshift__ = nužno
__ge__ = slijedi
__gt__ = vidi
def greška(self):
"""Konstruira sintaksnu grešku: zadnji pročitani token je pogrešan."""
return self.zadnji.neočekivan()
def prikaz(objekt, dubina:int=math.inf, uvlaka='', ime:str=None, rasponi=2):
"""Vertikalni prikaz AST-a, do zadane dubine."""
intro = uvlaka
if ime is not None: intro += ime + ' = '
if isinstance(objekt, (str, int, Nenavedeno, enum.Enum)) \
or not dubina:
return print(intro, repr(objekt), sep='')
elif isinstance(objekt, Token):
r, tail = raspon(objekt), ''
if r != 'Nepoznata pozicija' and rasponi > 1: tail = ' @[' + r + ']'
return print(intro, repr(objekt), tail, sep='')
elif isinstance(objekt, list):
print(intro, end='[...]:\n' if objekt else '[]\n')
for vrijednost in objekt:
prikaz(vrijednost, dubina-1, uvlaka+'. ')
elif isinstance(objekt, Memorija):
print(intro + type(objekt).__name__ + ':')
for ime, vrijednost in objekt:
prikaz(vrijednost, dubina-1, uvlaka+': ', repr(ime))
elif isinstance(objekt, dict):
print(intro, end='{:::}:\n' if objekt else '{}\n')
for ključ, vrijednost in dict(objekt).items():
prikaz(vrijednost, dubina-1, uvlaka+': ', repr(ključ))
elif isinstance(objekt, tuple):
print(intro, end='(...):\n' if objekt else '()\n')
for vrijednost in objekt:
prikaz(vrijednost, dubina-1, uvlaka+', ')
elif isinstance(objekt, (types.SimpleNamespace, AST)):
header = intro + type(objekt).__name__ + ':'*bool(vars(objekt))
r = raspon(objekt)
if r != 'Nepoznata pozicija' and rasponi: header += ' @[' + r + ']'
print(header)
try: d, t = objekt.za_prikaz(), '~ '
except AttributeError: d, t = vars(objekt), ' '
for ime, vrijednost in d.items():
if not ime.startswith('_'):
prikaz(vrijednost, dubina - 1, uvlaka + t, ime)
else: raise TypeError(f'Ne znam lijepo prikazati {objekt}')
def raspon(ast):
"""String koji kazuje odakle dokle se prostire token ili AST."""
if hasattr(ast, '_početak'):
ip, jp = ast._početak
ik, jk = ast._kraj
if ip == ik:
if ip == 0:
if jp == jk: return f'Znak #{jp}'
else: return f'Znakovi #{jp}–#{jk}'
elif jp == jk: return f'Redak {ip}, stupac {jp}'
else: return f'Redak {ip}, stupci {jp}–{jk}'
elif ik == 'zadnji':
if ip == 0: return f'Znakovi #{jp}–kraj'
else: return f'Redak {ip}, stupac {jp} – kraj'
else: return f'Redak {ip}, stupac {jp} – redak {ik}, stupac {jk}'
else: return 'Nepoznata pozicija'
class AST:
"""Bazna klasa za sva apstraktna sintaksna stabla."""
def __init_subclass__(cls): dataclasses.dataclass(cls, frozen=False)
def __xor__(self, tip):
"""Vraća sebe (istina) ako je zadanog tipa, inače nenavedeno (laž)."""
if isinstance(tip, type) and isinstance(self, tip): return self
else: return nenavedeno
iznimka = Token.iznimka
@classmethod
def ili_samo(cls, lista):
"""Konstruktor koji umjesto cls([x]) vraća samo x."""
if not lista or len(dataclasses.fields(cls)) != 1:
raise SemantičkaGreška('Ispuštanje korijena nije dozvoljeno!')
return lista[0] if len(lista) == 1 else cls(lista)
class Nenavedeno(AST):
"""Atribut koji nije naveden."""
def __bool__(self): return False
def __repr__(self): return type(self).__name__.lower().join('<>')
nenavedeno = Nenavedeno()
class Memorija:
"""Memorija računala, indeksirana tokenima ili njihovim sadržajima."""
def __init__(self, podaci={}, *, redefinicija=True):
self.redefinicija = redefinicija
self.podaci, self.token_sadržaja = {}, {}
if isinstance(podaci, dict): podaci = podaci.items()
elif not isinstance(podaci, (zip, Memorija)):
raise TypeError(f'Memorija ne razumije podatke: {podaci}')
for ključ, vrijednost in podaci: self[ključ] = vrijednost
def provjeri(self, lokacija, sadržaj):
if sadržaj in self.podaci: return
if isinstance(lokacija, Token): raise lokacija.nedeklaracija()
raise LookupError(f'{lokacija!r} nije pronađeno u memoriji')
def razriješi(self, l):
"""Vraća sadržaj i čitav token (ili None ako ga ne zna) za l."""
if isinstance(l, Token):
d = self.token_sadržaja.setdefault(l.sadržaj, l)
if l == d: return l.sadržaj, d
else: raise d.krivi_tip(l.tip, d.tip)
elif isinstance(l, str): return l, self.token_sadržaja.get(l)
else: raise TypeError(f'Memorija nije indeksirana s {type(l)}!')
def __delitem__(self, lokacija):
if not self.redefinicija: # razmisliti o ovome, možda promijeniti
raise TypeError(f'Brisanje iz memorije zahtijeva redefiniciju')
sadržaj, token = self.razriješi(lokacija)
self.provjeri(lokacija, sadržaj)
del self.podaci[sadržaj]
def __getitem__(self, lokacija):
sadržaj, token = self.razriješi(lokacija)
self.provjeri(lokacija, sadržaj)
return self.podaci[sadržaj]
def __setitem__(self, lokacija, vrijednost):
sadržaj, token = self.razriješi(lokacija)
if self.redefinicija or sadržaj not in self.podaci:
self.podaci[sadržaj] = vrijednost
elif isinstance(lokacija, Token): raise lokacija.redeklaracija(token)
elif token: raise token.redeklaracija()
else: raise SemantičkaGreška(f'Nedozvoljena redefinicija {lokacija!r}')
def __contains__(self, lokacija):
with contextlib.suppress(SemantičkaGreška, LookupError):
sadržaj, token = self.razriješi(lokacija)
return sadržaj in self.podaci
def __iter__(self):
for ključ, vrijednost in self.podaci.items():
yield self.token_sadržaja.get(ključ, ključ), vrijednost
def __len__(self): return len(self.podaci)
#TODO: dodati Memorija.imena kao dict(Memorija).keys(), koristiti u 04_...
| 451be764e1830a587108a66ccfe1fd40b7505407 | [
"Markdown",
"Python",
"reStructuredText"
] | 55 | Python | vedgar/ip | 42627725e1f86f649fff534fc7b026fbf0c90765 | 8308f234c6d9c62b876b74d89339e43318d67564 |
refs/heads/master | <file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.service;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.ViewRepository;
import io.gravitee.repository.management.model.View;
import io.gravitee.rest.api.model.UpdateViewEntity;
import io.gravitee.rest.api.model.ViewEntity;
import io.gravitee.rest.api.service.AuditService;
import io.gravitee.rest.api.service.exceptions.ViewNotFoundException;
import io.gravitee.rest.api.service.impl.ViewServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import static io.gravitee.repository.management.model.View.AuditEvent.VIEW_UPDATED;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
/**
* @author <NAME> (nicolas.geraud at graviteesource.com)
* @author <NAME> (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
@RunWith(MockitoJUnitRunner.class)
public class ViewService_UpdateTest {
@InjectMocks
private ViewServiceImpl viewService = new ViewServiceImpl();
@Mock
private ViewRepository mockViewRepository;
@Mock
private AuditService mockAuditService;
@Test
public void shouldNotUpdateUnknownView_multi_mode() throws TechnicalException {
UpdateViewEntity mockView = mock(UpdateViewEntity.class);
when(mockView.getId()).thenReturn("unknown");
when(mockViewRepository.findById("unknown")).thenReturn(Optional.empty());
List<ViewEntity> list = viewService.update(singletonList(mockView));
assertTrue(list.isEmpty());
verify(mockViewRepository, times(1)).findById(any());
verify(mockViewRepository, never()).update(any());
verify(mockAuditService, never()).createPortalAuditLog(any(), eq(VIEW_UPDATED), any(), any(), any());
}
@Test(expected = ViewNotFoundException.class)
public void shouldNotUpdateUnknownView_single_mode() throws TechnicalException {
UpdateViewEntity mockView = mock(UpdateViewEntity.class);
when(mockViewRepository.findById("unknown")).thenReturn(Optional.empty());
viewService.update("unknown", mockView);
verify(mockViewRepository, times(1)).findById(any());
verify(mockViewRepository, never()).update(any());
verify(mockAuditService, never()).createPortalAuditLog(any(), eq(VIEW_UPDATED), any(), any(), any());
}
@Test
public void shouldUpdateView_multi_mode() throws TechnicalException {
UpdateViewEntity mockView = mock(UpdateViewEntity.class);
when(mockView.getId()).thenReturn("known");
when(mockView.getName()).thenReturn("Known");
when(mockViewRepository.findById("known")).thenReturn(Optional.of(new View()));
View updatedView = mock(View.class);
when(updatedView.getId()).thenReturn("view-id");
when(updatedView.getName()).thenReturn("view-name");
when(updatedView.getDescription()).thenReturn("view-description");
when(updatedView.getOrder()).thenReturn(1);
when(updatedView.isHidden()).thenReturn(true);
when(updatedView.getUpdatedAt()).thenReturn(new Date(1234567890L));
when(updatedView.getCreatedAt()).thenReturn(new Date(9876543210L));
when(mockViewRepository.update(any())).thenReturn(updatedView);
List<ViewEntity> list = viewService.update(singletonList(mockView));
assertFalse(list.isEmpty());
assertEquals("one element", 1, list.size());
assertEquals("Id", "view-id", list.get(0).getId());
assertEquals("Name", "view-name", list.get(0).getName());
assertEquals("Description", "view-description", list.get(0).getDescription());
assertEquals("Total APIs", 0, list.get(0).getTotalApis());
assertEquals("Order", 1, list.get(0).getOrder());
assertEquals("Hidden", true, list.get(0).isHidden());
assertEquals("UpdatedAt", new Date(1234567890L), list.get(0).getUpdatedAt());
assertEquals("CreatedAt", new Date(9876543210L), list.get(0).getCreatedAt());
verify(mockViewRepository, times(1)).findById(any());
verify(mockViewRepository, times(1)).update(any());
verify(mockAuditService, times(1)).createPortalAuditLog(any(), eq(VIEW_UPDATED), any(), any(), any());
}
@Test
public void shouldUpdateView_single_mode() throws TechnicalException {
UpdateViewEntity mockView = mock(UpdateViewEntity.class);
when(mockView.getId()).thenReturn("view-id");
when(mockView.getName()).thenReturn("View ID");
when(mockViewRepository.findById("view-id")).thenReturn(Optional.of(new View()));
View updatedView = mock(View.class);
when(updatedView.getId()).thenReturn("view-id");
when(updatedView.getName()).thenReturn("view-name");
when(updatedView.getDescription()).thenReturn("view-description");
when(updatedView.getOrder()).thenReturn(1);
when(updatedView.isHidden()).thenReturn(true);
when(updatedView.getUpdatedAt()).thenReturn(new Date(1234567890L));
when(updatedView.getCreatedAt()).thenReturn(new Date(9876543210L));
when(mockViewRepository.update(any())).thenReturn(updatedView);
ViewEntity view = viewService.update("view-id", mockView);
assertNotNull(view);
assertEquals("Id", "view-id", view.getId());
assertEquals("Name", "view-name", view.getName());
assertEquals("Description", "view-description", view.getDescription());
assertEquals("Total APIs", 0, view.getTotalApis());
assertEquals("Order", 1, view.getOrder());
assertEquals("Hidden", true, view.isHidden());
assertEquals("UpdatedAt", new Date(1234567890L), view.getUpdatedAt());
assertEquals("CreatedAt", new Date(9876543210L), view.getCreatedAt());
verify(mockViewRepository, times(1)).findById(any());
verify(mockViewRepository, times(1)).update(any());
verify(mockAuditService, times(1)).createPortalAuditLog(any(), eq(VIEW_UPDATED), any(), any(), any());
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.portal.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.rest.api.model.ApplicationEntity;
import io.gravitee.rest.api.model.NewApplicationEntity;
import io.gravitee.rest.api.model.SubscriptionEntity;
import io.gravitee.rest.api.model.SubscriptionStatus;
import io.gravitee.rest.api.model.application.ApplicationSettings;
import io.gravitee.rest.api.model.application.OAuthClientSettings;
import io.gravitee.rest.api.model.application.SimpleApplicationSettings;
import io.gravitee.rest.api.model.permissions.RolePermission;
import io.gravitee.rest.api.model.permissions.RolePermissionAction;
import io.gravitee.rest.api.model.subscription.SubscriptionQuery;
import io.gravitee.rest.api.portal.rest.mapper.ApplicationMapper;
import io.gravitee.rest.api.portal.rest.model.Application;
import io.gravitee.rest.api.portal.rest.model.ApplicationInput;
import io.gravitee.rest.api.portal.rest.resource.param.PaginationParam;
import io.gravitee.rest.api.portal.rest.security.Permission;
import io.gravitee.rest.api.portal.rest.security.Permissions;
import io.gravitee.rest.api.service.ApplicationService;
import io.gravitee.rest.api.service.SubscriptionService;
import io.gravitee.rest.api.service.notification.ApplicationHook;
import io.gravitee.rest.api.service.notification.Hook;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author <NAME> (florent.chamfroy at graviteesource.com)
* @author GraviteeSource Team
*/
public class ApplicationsResource extends AbstractResource {
@Context
private ResourceContext resourceContext;
@Inject
private ApplicationService applicationService;
@Inject
private SubscriptionService subscriptionService;
@Inject
private ApplicationMapper applicationMapper;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
@Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.CREATE),
})
public Response createApplication(@Valid @NotNull(message = "Input must not be null.") ApplicationInput applicationInput) {
NewApplicationEntity newApplicationEntity = new NewApplicationEntity();
newApplicationEntity.setDescription(applicationInput.getDescription());
newApplicationEntity.setGroups(applicationInput.getGroups() != null ? new HashSet<>(applicationInput.getGroups()) : new HashSet<>());
newApplicationEntity.setName(applicationInput.getName());
newApplicationEntity.setPicture(applicationInput.getPicture());
final io.gravitee.rest.api.portal.rest.model.ApplicationSettings settings = applicationInput.getSettings();
ApplicationSettings newApplicationEntitySettings = new ApplicationSettings();
if (settings == null || (settings.getApp() == null && settings.getOauth() == null)) {
newApplicationEntity.setSettings(newApplicationEntitySettings);
} else {
final io.gravitee.rest.api.portal.rest.model.SimpleApplicationSettings simpleAppInput = settings.getApp();
if (simpleAppInput != null) {
SimpleApplicationSettings sas = new SimpleApplicationSettings();
sas.setClientId(simpleAppInput.getClientId());
sas.setType(simpleAppInput.getType());
newApplicationEntitySettings.setApp(sas);
}
final io.gravitee.rest.api.portal.rest.model.OAuthClientSettings oauthAppInput = settings.getOauth();
if (oauthAppInput != null) {
OAuthClientSettings ocs = new OAuthClientSettings();
ocs.setApplicationType(oauthAppInput.getApplicationType());
ocs.setGrantTypes(oauthAppInput.getGrantTypes());
ocs.setRedirectUris(oauthAppInput.getRedirectUris());
newApplicationEntitySettings.setoAuthClient(ocs);
}
}
newApplicationEntity.setSettings(newApplicationEntitySettings);
ApplicationEntity createdApplicationEntity = applicationService.create(newApplicationEntity, getAuthenticatedUser());
return Response
.status(Response.Status.CREATED)
.entity(applicationMapper.convert(createdApplicationEntity, uriInfo))
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
@Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.READ),
@Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.READ)
})
public Response getApplications(@BeanParam PaginationParam paginationParam,
@QueryParam("forSubscription") final boolean forSubscription,
@QueryParam("order") @DefaultValue("name") final String order) {
Stream<Application> applicationStream = applicationService.findByUser(getAuthenticatedUser())
.stream()
.map(application -> applicationMapper.convert(application, uriInfo))
.map(this::addApplicationLinks);
if (forSubscription) {
applicationStream = applicationStream.filter(app -> this.hasPermission(RolePermission.APPLICATION_SUBSCRIPTION, app.getId(), RolePermissionAction.CREATE));
}
boolean isAsc = !order.startsWith("-");
if (order.contains("nbSubscriptions")) {
FilteredApplication filteredApplications = orderByNumberOfSubscriptions(applicationStream.collect(Collectors.toList()), isAsc);
return createListResponse(filteredApplications.getFilteredApplications(), paginationParam, filteredApplications.getMetadata());
}
Comparator<Application> applicationNameComparator = Comparator.comparing(Application::getName, String.CASE_INSENSITIVE_ORDER);
if (!isAsc) {
applicationNameComparator.reversed();
}
List<Application> applicationsList = applicationStream
.sorted(applicationNameComparator)
.collect(Collectors.toList());
return createListResponse(applicationsList, paginationParam);
}
private Application addApplicationLinks(Application application) {
String basePath = uriInfo.getAbsolutePathBuilder().path(application.getId()).build().toString();
return application.links(applicationMapper.computeApplicationLinks(basePath, application.getUpdatedAt()));
}
private FilteredApplication orderByNumberOfSubscriptions(Collection<Application> applications, boolean isAsc) {
//find all subscriptions for applications
SubscriptionQuery subscriptionQuery = new SubscriptionQuery();
subscriptionQuery.setApplications(applications.stream().map(Application::getId).collect(Collectors.toList()));
subscriptionQuery.setStatuses(Arrays.asList(SubscriptionStatus.ACCEPTED, SubscriptionStatus.PAUSED));
// group by applications
Map<String, Long> subscribedApplicationsWithCount = subscriptionService.search(subscriptionQuery).stream()
.collect(Collectors.groupingBy(SubscriptionEntity::getApplication, Collectors.counting()));
// link an application with its nb of subscriptions
Map<Application, Long> applicationsWithCount = new HashMap<>();
Map<String, Map<String, Object>> applicationsMetadata = new HashMap<>();
Map<String, Object> subscriptionsMetadata = new HashMap<>();
applicationsMetadata.put("subscriptions", subscriptionsMetadata);
applications.forEach(application -> {
Long applicationSubscriptionsCount = subscribedApplicationsWithCount.get(application.getId());
//creation of a map which will be sorted to retrieve applications in the right order
applicationsWithCount.put(application, applicationSubscriptionsCount == null ? 0L : applicationSubscriptionsCount);
//creation of a metadata map
subscriptionsMetadata.put(application.getId(), applicationSubscriptionsCount == null ? 0L : applicationSubscriptionsCount);
});
// order the list
Comparator<Entry<Application, Long>> comparingByValue = Map.Entry.<Application, Long>comparingByValue();
if (!isAsc) {
comparingByValue = comparingByValue.reversed();
}
return new FilteredApplication(applicationsWithCount.entrySet().stream()
.sorted(comparingByValue.thenComparing(
Map.Entry.<Application, Long>comparingByKey(Comparator.comparing(Application::getName, String.CASE_INSENSITIVE_ORDER))))
.map(Map.Entry::getKey).collect(Collectors.toList()), applicationsMetadata);
}
@GET
@Path("/hooks")
@Produces(MediaType.APPLICATION_JSON)
public Response getHooks() {
return Response.ok(Arrays.stream(ApplicationHook.values()).toArray(Hook[]::new)).build();
}
@Path("{applicationId}")
public ApplicationResource getApplicationResource() {
return resourceContext.getResource(ApplicationResource.class);
}
private class FilteredApplication {
List<Application> filteredApplications;
Map<String, Map<String, Object>> metadata;
public FilteredApplication(List<Application> filteredApplications, Map<String, Map<String, Object>> metadata) {
super();
this.filteredApplications = filteredApplications;
this.metadata = metadata;
}
public List<Application> getFilteredApplications() {
return filteredApplications;
}
public Map<String, Map<String, Object>> getMetadata() {
return metadata;
}
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.service.impl.upgrade;
import io.gravitee.common.utils.IdGenerator;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.ApiRepository;
import io.gravitee.repository.management.api.ViewRepository;
import io.gravitee.repository.management.model.View;
import io.gravitee.rest.api.service.Upgrader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.Set;
/**
* @author <NAME> (david.brassely at graviteesource.com)
* @author <NAME> (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class DefaultViewUpgrader implements Upgrader, Ordered {
/**
* Logger.
*/
private final Logger logger = LoggerFactory.getLogger(DefaultViewUpgrader.class);
@Autowired
private ViewRepository viewRepository;
@Autowired
private ApiRepository apiRepository;
@Override
public boolean upgrade() {
// Initialize default view
final Set<View> views;
try {
views = viewRepository.findAll();
Optional<View> optionalKeyLessView = views.
stream().
filter(v -> v.getKey() == null || v.getKey().isEmpty()).
findFirst();
if (optionalKeyLessView.isPresent()) {
logger.info("Update views to add field key");
for (final View view : views) {
view.setKey(IdGenerator.generate(view.getName()));
viewRepository.update(view);
}
}
} catch (TechnicalException e) {
logger.error("Error while upgrading views : {}", e);
}
return true;
}
@Override
public int getOrder() {
return 200;
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.management.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.rest.api.model.*;
import io.gravitee.rest.api.model.api.ApiEntity;
import io.gravitee.rest.api.model.permissions.RolePermission;
import io.gravitee.rest.api.model.permissions.RolePermissionAction;
import io.gravitee.rest.api.management.rest.security.Permission;
import io.gravitee.rest.api.management.rest.security.Permissions;
import io.gravitee.rest.api.service.ViewService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author <NAME> (azize.elamrani at graviteesource.com)
* @author <NAME> (nicolas.geraud at graviteesource.com)
* @author <NAME> (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
@Api(tags = {"Views"})
public class ViewsResource extends AbstractViewResource {
@Context
private ResourceContext resourceContext;
@Autowired
private ViewService viewService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ViewEntity> list() {
Set<ApiEntity> apis;
if (isAdmin()) {
apis = apiService.findAll();
} else if (isAuthenticated()) {
apis = apiService.findByUser(getAuthenticatedUser(), null);
} else {
apis = apiService.findByVisibility(Visibility.PUBLIC);
}
boolean viewAll = hasPermission(RolePermission.ENVIRONMENT_VIEW, RolePermissionAction.UPDATE, RolePermissionAction.CREATE, RolePermissionAction.DELETE);
return viewService.findAll()
.stream()
.filter(v -> viewAll || !v.isHidden())
.sorted(Comparator.comparingInt(ViewEntity::getOrder))
// set picture
.map(v -> setPicture(v, true))
.map(v -> {
v.setTotalApis(viewService.getTotalApisByView(apis, v));
return v;
})
.collect(Collectors.toList());
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
@Permission(value = RolePermission.ENVIRONMENT_VIEW, acls = RolePermissionAction.CREATE)
})
public ViewEntity create(@Valid @NotNull final NewViewEntity view) {
return viewService.create(view);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
@Permission(value = RolePermission.ENVIRONMENT_VIEW, acls = RolePermissionAction.UPDATE)
})
public List<ViewEntity> update(@Valid @NotNull final List<UpdateViewEntity> views) {
return viewService.update(views);
}
@Path("{id}")
public ViewResource getViewResource() {
return resourceContext.getResource(ViewResource.class);
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.portal.rest.mapper;
import javax.ws.rs.core.UriBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.gravitee.rest.api.model.ViewEntity;
import io.gravitee.rest.api.portal.rest.model.View;
import io.gravitee.rest.api.portal.rest.model.ViewLinks;
import io.gravitee.rest.api.portal.rest.utils.PortalApiLinkHelper;
/**
* @author <NAME> (florent.chamfroy at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class ViewMapper {
@Autowired
UserMapper userMapper;
public View convert(ViewEntity viewEntity, UriBuilder baseUriBuilder) {
final View view = new View();
view.setDescription(viewEntity.getDescription());
view.setId(viewEntity.getKey());
view.setName(viewEntity.getName());
view.setOrder(viewEntity.getOrder());
view.setTotalApis(viewEntity.getTotalApis());
ViewLinks viewLinks = new ViewLinks();
String basePath = PortalApiLinkHelper.viewsURL(baseUriBuilder.clone(), viewEntity.getId());
String highlightApi = viewEntity.getHighlightApi();
if(highlightApi != null) {
viewLinks.setHighlightedApi(PortalApiLinkHelper.apisURL(baseUriBuilder.clone(), highlightApi));
}
viewLinks.setPicture(basePath+"/picture");
viewLinks.setSelf(basePath);
view.setLinks(viewLinks);
return view;
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.service;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.ViewRepository;
import io.gravitee.repository.management.model.View;
import io.gravitee.rest.api.model.ViewEntity;
import io.gravitee.rest.api.service.impl.ViewServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Date;
import java.util.List;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* @author <NAME> (nicolas.geraud at graviteesource.com)
* @author GraviteeSource Team
*/
@RunWith(MockitoJUnitRunner.class)
public class ViewService_FindTest {
@InjectMocks
private ViewServiceImpl viewService = new ViewServiceImpl();
@Mock
private ViewRepository mockViewRepository;
@Test
public void shouldDoNothingWithEmptyResult() throws TechnicalException {
when(mockViewRepository.findAllByEnvironment(any())).thenReturn(emptySet());
List<ViewEntity> list = viewService.findAll();
assertTrue(list.isEmpty());
verify(mockViewRepository, times(1)).findAllByEnvironment(any());
}
@Test
public void shouldFindView() throws TechnicalException {
View view = mock(View.class);
when(view.getId()).thenReturn("view-id");
when(view.getName()).thenReturn("view-name");
when(view.getDescription()).thenReturn("view-description");
when(view.getOrder()).thenReturn(1);
when(view.isHidden()).thenReturn(true);
when(view.getUpdatedAt()).thenReturn(new Date(1234567890L));
when(view.getCreatedAt()).thenReturn(new Date(9876543210L));
when(mockViewRepository.findAllByEnvironment(any())).thenReturn(singleton(view));
List<ViewEntity> list = viewService.findAll();
assertFalse(list.isEmpty());
assertEquals("one element", 1, list.size());
assertEquals("Id", "view-id", list.get(0).getId());
assertEquals("Name", "view-name", list.get(0).getName());
assertEquals("Description", "view-description", list.get(0).getDescription());
assertEquals("Total APIs", 0, list.get(0).getTotalApis());
assertEquals("Order", 1, list.get(0).getOrder());
assertEquals("Hidden", true, list.get(0).isHidden());
assertEquals("UpdatedAt", new Date(1234567890L), list.get(0).getUpdatedAt());
assertEquals("CreatedAt", new Date(9876543210L), list.get(0).getCreatedAt());
verify(mockViewRepository, times(1)).findAllByEnvironment(any());
}
}
<file_sep>/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.service.impl;
import static io.gravitee.repository.management.model.Audit.AuditProperties.VIEW;
import static io.gravitee.repository.management.model.View.AuditEvent.VIEW_CREATED;
import static io.gravitee.repository.management.model.View.AuditEvent.VIEW_DELETED;
import static io.gravitee.repository.management.model.View.AuditEvent.VIEW_UPDATED;
import java.util.*;
import java.util.stream.Collectors;
import javax.xml.bind.DatatypeConverter;
import io.gravitee.common.utils.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.ViewRepository;
import io.gravitee.repository.management.model.View;
import io.gravitee.rest.api.model.InlinePictureEntity;
import io.gravitee.rest.api.model.NewViewEntity;
import io.gravitee.rest.api.model.UpdateViewEntity;
import io.gravitee.rest.api.model.ViewEntity;
import io.gravitee.rest.api.model.api.ApiEntity;
import io.gravitee.rest.api.service.ApiService;
import io.gravitee.rest.api.service.AuditService;
import io.gravitee.rest.api.service.EnvironmentService;
import io.gravitee.rest.api.service.ViewService;
import io.gravitee.rest.api.service.common.GraviteeContext;
import io.gravitee.rest.api.service.common.RandomString;
import io.gravitee.rest.api.service.exceptions.DuplicateViewNameException;
import io.gravitee.rest.api.service.exceptions.TechnicalManagementException;
import io.gravitee.rest.api.service.exceptions.ViewNotFoundException;
/**
* @author <NAME> (azize at graviteesource.com)
* @author <NAME> (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class ViewServiceImpl extends TransactionalService implements ViewService {
private final Logger LOGGER = LoggerFactory.getLogger(ViewServiceImpl.class);
@Autowired
private ViewRepository viewRepository;
@Autowired
private ApiService apiService;
@Autowired
private AuditService auditService;
@Autowired
private EnvironmentService environmentService;
@Override
public List<ViewEntity> findAll() {
try {
LOGGER.debug("Find all views");
return viewRepository.findAllByEnvironment(GraviteeContext.getCurrentEnvironment())
.stream()
.map(this::convert).collect(Collectors.toList());
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to find all views", ex);
throw new TechnicalManagementException("An error occurs while trying to find all views", ex);
}
}
@Override
public ViewEntity findById(final String id) {
try {
LOGGER.debug("Find view by id : {}", id);
Optional<View> view = viewRepository.findById(id);
if (!view.isPresent()) {
view = viewRepository.findByKey(id, GraviteeContext.getCurrentEnvironment());
}
if (view.isPresent()) {
return convert(view.get());
}
throw new ViewNotFoundException(id);
} catch (TechnicalException ex) {
final String error = "An error occurs while trying to find a view using its id: " + id;
LOGGER.error(error, ex);
throw new TechnicalManagementException(error, ex);
}
}
@Override
public ViewEntity findNotHiddenById(String id) {
ViewEntity view = this.findById(id);
if (!view.isHidden()) {
return view;
}
throw new ViewNotFoundException(id);
}
@Override
public ViewEntity create(NewViewEntity viewEntity) {
// First we prevent the duplicate view name
final Optional<ViewEntity> optionalView = findAll().stream()
.filter(v -> v.getName().equals((viewEntity.getName())))
.findAny();
if (optionalView.isPresent()) {
throw new DuplicateViewNameException(optionalView.get().getName());
}
try {
// check if environment exists
String environment = GraviteeContext.getCurrentEnvironment();
this.environmentService.findById(environment);
View view = convert(viewEntity);
view.setEnvironmentId(environment);
ViewEntity createdView = convert(viewRepository.create(view));
auditService.createPortalAuditLog(
Collections.singletonMap(VIEW, view.getId()),
VIEW_CREATED,
new Date(),
null,
view);
return createdView;
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to create view {}", viewEntity.getName(), ex);
throw new TechnicalManagementException("An error occurs while trying to create view " + viewEntity.getName(), ex);
}
}
@Override
public ViewEntity update(String viewId, UpdateViewEntity viewEntity) {
try {
LOGGER.debug("Update View {}", viewId);
Optional<View> optViewToUpdate = viewRepository.findById(viewId);
if (!optViewToUpdate.isPresent()) {
throw new ViewNotFoundException(viewId);
}
View view = convert(viewEntity, optViewToUpdate.get().getEnvironmentId());
// check if picture has been set
if (viewEntity.getPicture() == null) {
view.setPicture(optViewToUpdate.get().getPicture());
}
ViewEntity updatedView = convert(viewRepository.update(view));
auditService.createPortalAuditLog(
Collections.singletonMap(VIEW, view.getId()),
VIEW_UPDATED,
new Date(),
optViewToUpdate.get(),
view);
return updatedView;
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to update view {}", viewEntity.getName(), ex);
throw new TechnicalManagementException("An error occurs while trying to update view " + viewEntity.getName(), ex);
}
}
@Override
public List<ViewEntity> update(final List<UpdateViewEntity> viewEntities) {
final List<ViewEntity> savedViews = new ArrayList<>(viewEntities.size());
viewEntities.forEach(viewEntity -> {
try {
Optional<View> viewOptional = viewRepository.findById(viewEntity.getId());
if (viewOptional.isPresent()) {
View view = convert(viewEntity, viewOptional.get().getEnvironmentId());
// check if picture has been set
if (view.getPicture() == null) {
// Picture can not be updated when re-ordering views
view.setPicture(viewOptional.get().getPicture());
}
savedViews.add(convert(viewRepository.update(view)));
auditService.createPortalAuditLog(
Collections.singletonMap(VIEW, view.getId()),
VIEW_UPDATED,
new Date(),
viewOptional.get(),
view);
}
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to update view {}", viewEntity.getName(), ex);
throw new TechnicalManagementException("An error occurs while trying to update view " + viewEntity.getName(), ex);
}
});
return savedViews;
}
@Override
public void delete(final String viewId) {
try {
Optional<View> viewOptional = viewRepository.findById(viewId);
if (viewOptional.isPresent()) {
viewRepository.delete(viewId);
auditService.createPortalAuditLog(
Collections.singletonMap(VIEW, viewId),
VIEW_DELETED,
new Date(),
null,
viewOptional.get());
// delete all reference on APIs
apiService.deleteViewFromAPIs(viewId);
}
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to delete view {}", viewId, ex);
throw new TechnicalManagementException("An error occurs while trying to delete view " + viewId, ex);
}
}
@Override
public InlinePictureEntity getPicture(String viewId) {
ViewEntity viewEntity = findById(viewId);
InlinePictureEntity imageEntity = new InlinePictureEntity();
if (viewEntity.getPicture() != null) {
String[] parts = viewEntity.getPicture().split(";", 2);
imageEntity.setType(parts[0].split(":")[1]);
String base64Content = viewEntity.getPicture().split(",", 2)[1];
imageEntity.setContent(DatatypeConverter.parseBase64Binary(base64Content));
}
return imageEntity;
}
private View convert(final NewViewEntity viewEntity) {
final View view = new View();
view.setId(RandomString.generate());
view.setKey(IdGenerator.generate(viewEntity.getName()));
view.setName(viewEntity.getName());
view.setDescription(viewEntity.getDescription());
view.setOrder(viewEntity.getOrder());
view.setHidden(viewEntity.isHidden());
view.setHighlightApi(viewEntity.getHighlightApi());
view.setPicture(viewEntity.getPicture());
return view;
}
private View convert(final UpdateViewEntity viewEntity, final String environment) {
final View view = new View();
view.setId(viewEntity.getId());
view.setKey(IdGenerator.generate(viewEntity.getName()));
view.setEnvironmentId(environment);
view.setName(viewEntity.getName());
view.setDescription(viewEntity.getDescription());
view.setOrder(viewEntity.getOrder());
view.setHidden(viewEntity.isHidden());
view.setHighlightApi(viewEntity.getHighlightApi());
view.setPicture(viewEntity.getPicture());
return view;
}
private ViewEntity convert(final View view) {
final ViewEntity viewEntity = new ViewEntity();
viewEntity.setId(view.getId());
viewEntity.setKey(view.getKey());
viewEntity.setName(view.getName());
viewEntity.setDescription(view.getDescription());
viewEntity.setOrder(view.getOrder());
viewEntity.setHidden(view.isHidden());
viewEntity.setHighlightApi(view.getHighlightApi());
viewEntity.setPicture(view.getPicture());
viewEntity.setUpdatedAt(view.getUpdatedAt());
viewEntity.setCreatedAt(view.getCreatedAt());
return viewEntity;
}
@Override
public long getTotalApisByView(Set<ApiEntity> apis, ViewEntity view) {
return apis.stream()
.filter(api -> api.getViews() != null && api.getViews().contains(view.getKey()))
.count();
}
}
| cd83938fa66e0dc8618fb3f5dd872be76cb033d7 | [
"Java"
] | 7 | Java | krptodr/gravitee-management-rest-api | 9b30776427bef7c0a35ad97cca686c615c9d7736 | 7ff11545c2c94b5915ffcb55211841123a8f5e27 |
refs/heads/master | <file_sep>package com.nbcd.GenericLib;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class Extent_Reports{
public static ExtentReports extentReport;
public static ExtentTest logger;
static String reportFolder;
static WebDriver driver;
static
{
SimpleDateFormat sdfDateReport = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Date now = new Date();
extentReport=new ExtentReports(System.getProperty("user.dir") +"/ReportGenerator/NBCAutomation_"+ sdfDateReport.format(now) +".html",false);
extentReport.addSystemInfo("Selenium Version", "3.0.1");
extentReport.addSystemInfo("Environment", "Production");
extentReport.assignProject("NBC");
}
public void getResult(ITestResult result)
{
if(result.getStatus() == ITestResult.FAILURE)
{
logger.log(LogStatus.FAIL, "Test Case Failed :"+result.getName());
logger.log(LogStatus.FAIL, "Failed Reason is :"+result.getThrowable());
}
else if(result.getStatus() == ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, "Test Case Skipped is :"+result.getName());
logger.log(LogStatus.FAIL, "Skipped Reason is :"+result.getThrowable());
}
else if(result.getStatus() == ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, "Test Case Pass :"+result.getName());
}
else if(result.getStatus() == ITestResult.STARTED)
{
logger.log(LogStatus.SKIP, "Test Case Started :"+result.getName());
}
}
@BeforeMethod
public void beforeMethod(Method result)
{
logger=extentReport.startTest(result.getName());
logger.log(LogStatus.INFO, result.getName()+ " test Started");
}
@AfterMethod
public void afterMethod(ITestResult result)
{
getResult(result);
}
@AfterTest
public void endReport(){
extentReport.endTest(logger);
extentReport.flush();
}
}<file_sep>username = nbcd1
accessKey = <KEY>
browser = Chrome
browser_version = 54.0
os=windows
os_version = 7.0<file_sep>package com.nbcd.Pages;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import com.codoid.products.exception.FilloException;
import com.nbcd.GenericLib.DatabaseFunction;
import com.nbcd.GenericLib.Synchronization;
import com.nbcd.GenericLib.Utilities;
public class PGLaunchNBC
{
public WebDriver driver;
String sql;
DatabaseFunction db = new DatabaseFunction();
public List<String> lstObject;
String sqlQry,Status;
WebElement objNBCLogo;
//Constructor to initialize all the Page Objects
public PGLaunchNBC(WebDriver driver)
{
this.driver = driver;
}
//=========================================================================================================================
@Test
public boolean LaunchNBC( ) throws InterruptedException, FilloException
{
lstObject=db.getTestDataObject("Select * from LaunchNBC","ObjectRepository");
driver.get("http://www.nbc.com");
Synchronization.implicitWait(driver, 5);
WebElement objNBCLogo= (WebElement) Utilities.returnElement(driver,lstObject.get(2),lstObject.get(1));
if (objNBCLogo.isDisplayed())
{
return true;
}
else
{
return false;
}
}
}<file_sep>package com.nbcd.Test;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.codoid.products.exception.FilloException;
import com.nbcd.GenericLib.Extent_Reports;
import com.nbcd.Pages.PGShowHomePage_043VerifyTwitterTags;
public class TCShowHomePage_043VerifyTwitterTags extends Extent_Reports
{
public WebDriver driver;
@Test(groups="TCShowHomePage")
@Parameters({ "Browser"})
public void TwitterTags(String Browser) throws InterruptedException, FilloException, IOException
{
PGShowHomePage_043VerifyTwitterTags objSP = new PGShowHomePage_043VerifyTwitterTags(Browser);
objSP.VerifyTwitterTags();
}
}
<file_sep>package com.nbcd.Test;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.codoid.products.exception.FilloException;
import com.nbcd.GenericLib.Extent_Reports;
import com.nbcd.GenericLib.GetWebDriverInstance;
import com.nbcd.Pages.PGHomePage;
public class TCHomePage extends Extent_Reports
{
public WebDriver driver;
@Test(groups="TCHomePage")
@Parameters({ "Browser"})
public void MenuDetails(String Browser) throws InterruptedException, FilloException, IOException
{
PGHomePage objHP = new PGHomePage(Browser);
objHP.MenuDetails();
}
}
<file_sep>package com.nbcd.Pages;
import com.relevantcodes.extentreports.LogStatus;
import java.net.MalformedURLException;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import com.codoid.products.exception.FilloException;
import com.nbcd.GenericLib.DatabaseFunction;
import com.nbcd.GenericLib.Extent_Reports;
import com.nbcd.GenericLib.GetWebDriverInstance;
import com.nbcd.GenericLib.Utilities;
public class PGShowHomePage_043VerifyTwitterTags extends GetWebDriverInstance
{
private static WebDriver driver;
String sql;
protected static String showDetails;
DatabaseFunction db = new DatabaseFunction();
public List<String> lstObject,lstTestData;
String sqlQry,Status;
WebElement objTwitterCard,objTwitterSite,objTwitterSiteId,objTwitterTitle,objTwitterDescription,objTwitterImage;
//=================================================================================================================================================================================
//Constructor to initialize all the Page Objects
public PGShowHomePage_043VerifyTwitterTags(String Browser)
{
try
{
this.driver = GetWebDriverInstance.getBrowser(Browser);
lstTestData=db.getTestDataObject("Select * from VerifyTwitterTags","Input");
lstObject=db.getTestDataObject("Select * from VerifyTwitterTags","ObjectRepository");
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//=========================================================================================================================
@Test
public PGShowHomePage_043VerifyTwitterTags VerifyTwitterTags( ) throws InterruptedException, FilloException
{
//Launching Browser with valid URL.
driver.get(lstTestData.get(0));
try
{
objTwitterCard =Utilities.returnElement(driver,lstObject.get(2),lstObject.get(1));
objTwitterSite=Utilities.returnElement(driver,lstObject.get(5),lstObject.get(4));
objTwitterSiteId=Utilities.returnElement(driver,lstObject.get(8),lstObject.get(7));
objTwitterTitle=Utilities.returnElement(driver,lstObject.get(11),lstObject.get(10));
objTwitterDescription=Utilities.returnElement(driver,lstObject.get(14),lstObject.get(13));
objTwitterImage=Utilities.returnElement(driver,lstObject.get(17),lstObject.get(16));
/**twitter:card*/
if (lstTestData.get(1).equalsIgnoreCase(objTwitterCard.getAttribute("content")))
{
Extent_Reports.logger.log(LogStatus.PASS,"Expected Result for '"+lstObject.get(0) +"':"+lstTestData.get(1) +"\n"+"Actual Result for '"+lstObject.get(0) +"':"+objTwitterCard.getAttribute("content"));
}
else
{
Extent_Reports.logger.log(LogStatus.FAIL,"Expected Result for '"+lstObject.get(0) +"':"+lstTestData.get(1) +"\n"+"Actual Result for '"+lstObject.get(0) +"':"+objTwitterCard.getAttribute("content"));
}
/**twitter:site*/
if (lstTestData.get(2).equalsIgnoreCase(objTwitterSite.getAttribute("content")))
{
Extent_Reports.logger.log(LogStatus.PASS,"Expected Result for '"+lstObject.get(3) +"':"+lstTestData.get(2) +"\n"+"Actual Result for '"+lstObject.get(3) +"':"+objTwitterSite.getAttribute("content"));
}
else
{
Extent_Reports.logger.log(LogStatus.FAIL,"Expected Result for '"+lstObject.get(3) +"':"+lstTestData.get(2) +"\n"+"Actual Result for '"+lstObject.get(3) +"':"+objTwitterSite.getAttribute("content"));
}
/**twitter:site:id*/
if (lstTestData.get(3).equalsIgnoreCase(objTwitterSiteId.getAttribute("content")))
{
Extent_Reports.logger.log(LogStatus.PASS,"Expected Result for '"+lstObject.get(6) +"':"+lstTestData.get(3) +"\t"+"Actual Result for '"+lstObject.get(6) +"':"+objTwitterSiteId.getAttribute("content"));
}
else
{
Extent_Reports.logger.log(LogStatus.FAIL,"Expected Result for '"+lstObject.get(6) +"':"+lstTestData.get(3) +"\t"+"Actual Result for '"+lstObject.get(6) +"':"+objTwitterSiteId.getAttribute("content"));
}
/** twitter:title */
if (lstTestData.get(4).equalsIgnoreCase(objTwitterTitle.getAttribute("content")))
{
Extent_Reports.logger.log(LogStatus.PASS,"Expected Result for '"+lstObject.get(9) +"':"+lstTestData.get(4) +"\t"+"Actual Result for '"+lstObject.get(9) +"':"+objTwitterTitle.getAttribute("content"));
}
else
{
Extent_Reports.logger.log(LogStatus.FAIL,"Expected Result for '"+lstObject.get(9) +"':"+lstTestData.get(4) +"\t"+"Actual Result for '"+lstObject.get(9) +"':"+objTwitterTitle.getAttribute("content"));
}
/**twitter:description*/
if (lstTestData.get(5).equalsIgnoreCase(objTwitterDescription.getAttribute("content")))
{
Extent_Reports.logger.log(LogStatus.FAIL,"Expected Result for '"+lstObject.get(12) +"':Not Null"+lstTestData.get(5) +"\t"+"Actual Result for '"+lstObject.get(12) +"':"+objTwitterDescription.getAttribute("content"));
}
else
{
Extent_Reports.logger.log(LogStatus.PASS,"Expected Result for '"+lstObject.get(12) +"':Not Null"+lstTestData.get(5) +"\t"+"Actual Result for '"+lstObject.get(12) +"':"+objTwitterDescription.getAttribute("content"));
}
}
catch(Exception exc)
{
System.out.println(exc.getMessage());
}
driver.close();
return null;
}
}
| 05da3ece7ae2002a4bf090db63c3b6ec11a17124 | [
"Java",
"INI"
] | 6 | Java | qaautomationcts/NBCDWeb | b0c49c340d1cc4b6e37d9aa3607eb9a5e1e07fdf | a69e1a46aec810d473238364b8e0a183328d3b60 |
refs/heads/master | <repo_name>adi-horowitz/final-project<file_sep>/Trainer.py
import abc
import os
import sys
import tqdm
import torch
from torch.utils.data import DataLoader
from typing import Callable, Any
from pathlib import Path
from train_results import BatchResult, EpochResult, FitResult
class Trainer(abc.ABC):
"""
A class abstracting the various tasks of training models.
Provides methods at multiple levels of granularity:
- Multiple epochs (fit)
- Single epoch (train_epoch/test_epoch)
- Single batch (train_batch/test_batch)
"""
def __init__(self, model, loss_fn, optimizer, scheduler, device='cpu'):
"""
Initialize the trainer.
:param model: Instance of the model to train.
:param loss_fn: The loss function to evaluate with.
:param optimizer: The optimizer to train with.
:param device: torch.device to run training on (CPU or GPU).
"""
self.model = model
self.loss_fn = loss_fn
self.optimizer = optimizer
self.scheduler = scheduler
self.device = device
model.to(self.device)
def fit(self, dl_train: DataLoader, dl_test: DataLoader,
num_epochs, checkpoints: str = None,
early_stopping: int = None,
print_every=1, post_epoch_fn=None, **kw) -> FitResult:
"""
Trains the model for multiple epochs with a given training set,
and calculates validation loss over a given validation set.
:param dl_train: Dataloader for the training set.
:param dl_test: Dataloader for the test set.
:param num_epochs: Number of epochs to train for.
:param checkpoints: Whether to save model to file every time the
test set accuracy improves. Should be a string containing a
filename without extension.
:param early_stopping: Whether to stop training early if there is no
test loss improvement for this number of epochs.
:param print_every: Print progress every this number of epochs.
:param post_epoch_fn: A function to call after each epoch completes.
:return: A FitResult object containing train and test losses per epoch.
"""
actual_num_epochs = 0
train_loss, train_acc, test_loss, test_acc = [], [], [], []
best_acc = None
epochs_without_improvement = 0
epochs_so_far = 0
checkpoint_filename=None
if checkpoints is not None:
checkpoint_filename = f'{checkpoints}.pt'
Path(os.path.dirname(checkpoint_filename)).mkdir(exist_ok=True)
if os.path.isfile(checkpoint_filename):
print(f'*** Loading checkpoint file {checkpoint_filename}')
saved_state = torch.load(checkpoint_filename,
map_location=self.device)
best_acc = saved_state.get('best_acc', best_acc)
epochs_without_improvement =\
saved_state.get('ewi', epochs_without_improvement)
epochs_so_far = saved_state.get('esf', epochs_so_far)
actual_num_epochs += epochs_so_far
self.model.load_state_dict(saved_state['model_state'])
fit_res = saved_state['fit_result']
train_loss, train_acc, test_loss, test_acc = \
fit_res[1], fit_res[2], fit_res[3], fit_res[4]
if epochs_so_far == num_epochs:
batches = kw.get("max_batches") if "max_batches" in kw else None
test_res = self.test_epoch(dl_test, max_batches=batches)
test_loss.append(sum(test_res.losses) / len(test_res.losses))
test_acc.append(test_res.accuracy)
for epoch in range(epochs_so_far, num_epochs):
save_checkpoint = True
verbose = False # pass this to train/test_epoch.
if epoch % print_every == 0 or epoch == num_epochs - 1:
verbose = True
self._print(f'--- EPOCH {epoch+1}/{num_epochs} ---', verbose)
# Train & evaluate for one epoch:
# - Use the train/test_epoch methods.
# - Save losses and accuracies in the lists above.
# - Implement early stopping. This is a very useful and
# simple regularization technique that is highly recommended.
batches = None
if "max_batches" in kw:
batches = kw.get("max_batches")
actual_num_epochs += 1
train_res = self.train_epoch(dl_train, verbose=verbose, max_batches=batches)
test_res = self.test_epoch(dl_test, verbose=verbose, max_batches=batches)
train_loss.append(sum(train_res.losses) / len(train_res.losses))
train_acc.append(train_res.accuracy)
test_loss.append(sum(test_res.losses) / len(test_res.losses))
test_acc.append(test_res.accuracy)
if early_stopping is not None and len(test_loss) >= 2:
if test_loss[-1] >= test_loss[-2]:
epochs_without_improvement += 1
if epochs_without_improvement == early_stopping:
break
else:
epochs_without_improvement = 0
best_acc = max(best_acc if best_acc is not None else 0, test_res.accuracy)
# Save model checkpoint if requested
if save_checkpoint and checkpoint_filename is not None:
saved_state = dict(best_acc=best_acc,
ewi=epochs_without_improvement,
model_state=self.model.state_dict(),
esf=epoch+1,
fit_result=FitResult(actual_num_epochs, train_loss, train_acc, test_loss, test_acc))
torch.save(saved_state, checkpoint_filename)
print(f'*** Saved checkpoint {checkpoint_filename} '
f'at epoch {epoch+1}')
if post_epoch_fn:
post_epoch_fn(epoch, train_res, test_res, verbose)
return FitResult(actual_num_epochs,
train_loss, train_acc, test_loss, test_acc)
def train_epoch(self, dl_train: DataLoader, **kw) -> EpochResult:
"""
Train once over a training set (single epoch).
:param dl_train: DataLoader for the training set.
:param kw: Keyword args supported by _foreach_batch.
:return: An EpochResult for the epoch.
"""
self.model.train(True) # set train mode
return self._foreach_batch(dl_train, self.train_batch, **kw)
def test_epoch(self, dl_test: DataLoader, **kw) -> EpochResult:
"""
Evaluate model once over a test set (single epoch).
:param dl_test: DataLoader for the test set.
:param kw: Keyword args supported by _foreach_batch.
:return: An EpochResult for the epoch.
"""
self.model.train(False) # set evaluation (test) mode
return self._foreach_batch(dl_test, self.test_batch, **kw)
@abc.abstractmethod
def train_batch(self, batch) -> BatchResult:
"""
Runs a single batch forward through the model, calculates loss,
preforms back-propagation and uses the optimizer to update weights.
:param batch: A single batch of data from a data loader (might
be a tuple of data and labels or anything else depending on
the underlying dataset.
:return: A BatchResult containing the value of the loss function and
the number of correctly classified samples in the batch.
"""
raise NotImplementedError()
@abc.abstractmethod
def test_batch(self, batch) -> BatchResult:
"""
Runs a single batch forward through the model and calculates loss.
:param batch: A single batch of data from a data loader (might
be a tuple of data and labels or anything else depending on
the underlying dataset.
:return: A BatchResult containing the value of the loss function and
the number of correctly classified samples in the batch.
"""
raise NotImplementedError()
@staticmethod
def _print(message, verbose=True):
""" Simple wrapper around print to make it conditional """
if verbose:
print(message)
@staticmethod
def _foreach_batch(dl: DataLoader,
forward_fn: Callable[[Any], BatchResult],
verbose=True, max_batches=None) -> EpochResult:
"""
Evaluates the given forward-function on batches from the given
dataloader, and prints progress along the way.
"""
losses = []
num_correct = 0
num_samples = len(dl.sampler)
num_batches = len(dl.batch_sampler)
if max_batches is not None:
if max_batches < num_batches:
num_batches = max_batches
num_samples = num_batches * dl.batch_size
if verbose:
pbar_file = sys.stdout
else:
pbar_file = open(os.devnull, 'w')
pbar_name = forward_fn.__name__
with tqdm.tqdm(desc=pbar_name, total=num_batches,
file=pbar_file) as pbar:
dl_iter = iter(dl)
for batch_idx in range(num_batches):
data = next(dl_iter)
batch_res = forward_fn(data)
pbar.set_description(f'{pbar_name} ({batch_res.loss:.3f})')
pbar.update()
losses.append(batch_res.loss)
num_correct += batch_res.num_correct
avg_loss = sum(losses) / num_batches
accuracy = 100. * num_correct / num_samples
pbar.set_description(f'{pbar_name} '
f'(Avg. Loss {avg_loss:.3f}, '
f'Accuracy {accuracy:.1f})')
return EpochResult(losses=losses, accuracy=accuracy)
class SRMTrainer(Trainer):
def __init__(self, model, loss_fn, optimizer, scheduler, device=None):
super().__init__(model, loss_fn, optimizer, scheduler, device)
def train_epoch(self, dl_train: DataLoader, **kw):
self.h=None
return super().train_epoch(dl_train, **kw)
def test_epoch(self, dl_test: DataLoader, **kw):
self.h = None
return super().test_epoch(dl_test, **kw)
def train_batch(self, batch) -> BatchResult:
X, y = batch
X = X.to(self.device, dtype=torch.float) # (B,S,V)
y = y.to(self.device, dtype=torch.long) # (B,S)
# Train the SRM model on one batch of data.
# - Forward pass
# - Calculate total loss over sequence
# - Backward pass (BPTT)
# - Update params
# - Calculate number of correct char predictions
self.optimizer.zero_grad()
scores= self.model.forward(X)
loss = self.loss_fn.forward(scores, y)
loss.backward()
self.optimizer.step()
self.scheduler.step()
y_hat = torch.argmax(scores, dim=1)
num_correct = torch.sum(y_hat == y)
return BatchResult(loss.item(), num_correct.item())
def test_batch(self, batch) -> BatchResult:
x, y = batch
x = x.to(self.device, dtype=torch.float) # (B,S,V)
y = y.to(self.device, dtype=torch.long) # (B,S)
with torch.no_grad():
# Evaluate the SRM model on one batch of data.
# - Forward pass
# - Loss calculation
# - Calculate number of correct predictions
scores = self.model.forward(x)
loss = self.loss_fn.forward(scores, y)
y_hat = torch.argmax(scores, dim=1)
num_correct = torch.sum(y_hat == y)
return BatchResult(loss.item(), num_correct.item())<file_sep>/imagenet_train.py
import argparse
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from back import Bone, utils
from resnet_with_block import resnet50, se_resnet50, srm_resnet50
import imagenet
data_dir = 'imagenet'
model_names = ['resnet', 'senet', 'srmnet']
num_classes = 1000
batch_size = 64
epochs_count = 100
num_workers = 16
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', required=True, choices=model_names)
args = parser.parse_args()
datasets = imagenet.get_datasets(data_dir)
if args.model_name == 'resnet':
model = resnet50(num_classes=num_classes)
elif args.model_name == 'senet':
model = se_resnet50(num_classes=num_classes)
elif args.model_name == 'srmnet':
model = srm_resnet50(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = StepLR(optimizer, 30, 0.1)
criterion = nn.CrossEntropyLoss()
backbone = Bone(model,
datasets,
criterion,
optimizer,
scheduler=scheduler,
scheduler_after_ep=False,
metric_fn=utils.accuracy_metric,
metric_increase=True,
batch_size=batch_size,
num_workers=num_workers,
weights_path=f'weights/imagenet_best_{args.model_name}.pth',
log_dir=f'logs/imagenet/{args.model_name}')
backbone.fit(epochs_count)
<file_sep>/run.sh
#!/bin/sh
module load python
python experiments.py<file_sep>/experiments.py
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR, StepLR
from resnet_with_block import cifar_resnet32, cifar_se_resnet32,\
cifar_srm_resnet32, cifar_srm_with_corr_matrix_resnet32, srm_resnet50, se_resnet50, resnet50, oursrm_resnet50, cifar_srm_with_median_resnet32
import cifar10
import resnet_with_block
from plot import plot_fit
from Trainer import SRMTrainer
import torch
from torch.utils.data import DataLoader
from train_results import FitResult
import imagenet
import argparse
def print_with_plot(fit_result: FitResult):
print(fit_result)
plot_fit(fit_result)
def run_model(data_name, model_name):
if data_name == "cifar":
# parameters:
num_classes = 10
batch_size = 128
epochs_count = 100
num_workers = 8
# load data cifar:
data_dir = 'cifar10'
dl_train = DataLoader(dataset=cifar10.get_datasets(data_dir)['train'], batch_size=batch_size,
num_workers=num_workers)
dl_test = DataLoader(dataset=cifar10.get_datasets(data_dir)['val'], batch_size=batch_size,
num_workers=num_workers)
if model_name == "srm_with_corr":
model = cifar_srm_with_corr_matrix_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
fit_result = srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count,
checkpoints=model_name)
print_with_plot(fit_result)
elif model_name == "srm_median_and_corr":
model = resnet_with_block.cifar_srm_with_median_and_corr_matrix_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print_with_plot(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count, checkpoints=model_name))
elif model_name == "srm_with_median":
model = cifar_srm_with_median_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print_with_plot(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count, checkpoints=model_name))
elif model_name == "srmnet":
model = cifar_srm_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print_with_plot(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count, checkpoints=model_name))
elif model_name == "senet":
model = cifar_se_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print_with_plot(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count, checkpoints=model_name))
elif model_name == "resnet":
model = cifar_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [70, 80], 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count, checkpoints=model_name))
else:
# parametes:
num_classes = 1000
batch_size = 64
epochs_count = 100
num_workers = 16
# load data imagenet:
data_dir = 'imagenet'
dl_train = DataLoader(dataset=imagenet.get_datasets(data_dir)['train'], batch_size=batch_size,
num_workers=num_workers)
dl_test = DataLoader(dataset=imagenet.get_datasets(data_dir)['val'], batch_size=batch_size,
num_workers=num_workers)
if model_name == "oursrm":
model = oursrm_resnet50(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = StepLR(optimizer, 30, 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count))
elif model_name == "srm":
model = srm_resnet50(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = StepLR(optimizer, 30, 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count))
elif model_name == "senet":
model = se_resnet50(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = StepLR(optimizer, 30, 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count))
elif model_name == "resnet":
model = resnet50(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = StepLR(optimizer, 30, 0.1)
loss_fn = nn.CrossEntropyLoss()
srm = SRMTrainer(model, loss_fn, optimizer, scheduler)
print(srm.fit(dl_train=dl_train, dl_test=dl_test, num_epochs=epochs_count))
if __name__ == '__main__':
model_name = input('insert model name')
run_model('cifar', model_name)
<file_sep>/print_fit_result.py
import torch
from plot import plot_fit
def print_fit_res(model_name: str):
checkpoint_filename = f'{model_name}.pt'
saved_state = torch.load(checkpoint_filename,
'cpu')
fit_res = saved_state['fit_result']
plot_fit(fit_res)
if __name__ == '__main__':
model_name = input('insert model name')
print_fit_res(model_name)
<file_sep>/layer_blocks.py
"""
SE block from https://github.com/moskomule/senet.pytorch
"""
import torch
from torch import nn
class GramMatrix(nn.Module):
def forward(self, input):
a, b, c, d = input.size()
# a = batch size
# b = num channels
# (c,d) = dimensions of a f. map (N=c*d)
features = input.view(a, b, c*d) # resise F_XL into \hat F_XL
# G = [torch.mm(features[i,:,:], features[i,:,:].t()) for i in range(a)] # compute the gram product
# G = torch.stack(G, dim=0)
G = torch.matmul(features, torch.transpose(features,1,2))
# we 'normalize' the values of the gram matrix
# by dividing by the number of element in each feature maps.
return G.div(a * b * c * d)
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, channel, bias=False),
nn.Sigmoid()
)
def forward(self, x):
b, c, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1)
return x * y.expand_as(x)
class SRMLayer(nn.Module):
def __init__(self, channel, reduction=None):
# Reduction for compatibility with layer_block interface
super(SRMLayer, self).__init__()
# CFC: channel-wise fully connected layer
self.cfc = nn.Conv1d(channel, channel, kernel_size=2, bias=False,
groups=channel)
self.bn = nn.BatchNorm1d(channel)
def forward(self, x):
b, c, _, _ = x.size()
# Style pooling
mean = x.view(b, c, -1).mean(-1).unsqueeze(-1)
std = x.view(b, c, -1).std(-1).unsqueeze(-1)
u = torch.cat((mean, std), -1) # (b, c, 2)
# Style integration
z = self.cfc(u) # (b, c, 1)
z = self.bn(z)
g = torch.sigmoid(z)
g = g.view(b, c, 1, 1)
return x * g.expand_as(x)
class SRMWithMedian(nn.Module):
def __init__(self, channel, reduction=None):
# Reduction for compatibility with layer_block interface
super(SRMWithMedian, self).__init__()
# CFC: channel-wise fully connected layer
self.cfc = nn.Conv1d(channel, channel, kernel_size=3, bias=False,
groups=channel)
self.bn = nn.BatchNorm1d(channel)
self.gram = GramMatrix()
def forward(self, x):
b, c, _, _ = x.size()
# Style pooling
mean = x.view(b, c, -1).mean(-1).unsqueeze(-1)
std = x.view(b, c, -1).std(-1).unsqueeze(-1)
median = x.view(b, c, -1).median(-1)[0].unsqueeze(-1)
u = torch.cat((mean, std, median), -1) # (b, c, 3)
# Style integration
z = self.cfc(u) # (b, c, 1)
z = self.bn(z)
g = torch.sigmoid(z)
g = g.view(b, c, 1, 1)
return x * g.expand_as(x)
class SRMWithCorrMatrix(nn.Module):
def __init__(self, channel, reduction=None):
# Reduction for compatibility with layer_block interface
super(SRMWithCorrMatrix, self).__init__()
# CFC: channel-wise fully connected layer
self.cfc = nn.Conv1d(channel, channel, kernel_size=2 + channel, bias=False,
groups=channel)
self.bn = nn.BatchNorm1d(channel)
self.gram = GramMatrix()
def forward(self, x):
b, c, _, _ = x.size()
# Style pooling
mean = x.view(b, c, -1).mean(-1).unsqueeze(-1)
std = x.view(b, c, -1).std(-1).unsqueeze(-1)
gram = self.gram(x)
u = torch.cat((mean, std, gram), -1) # (b, c, 2+c)
# Style integration
z = self.cfc(u) # (b, c, 1)
z = self.bn(z)
g = torch.sigmoid(z)
g = g.view(b, c, 1, 1)
return x * g.expand_as(x)
class SRMWithMedianAndCorrMatrix(nn.Module):
def __init__(self, channel, reduction=None):
# Reduction for compatibility with layer_block interface
super(SRMWithMedianAndCorrMatrix, self).__init__()
# CFC: channel-wise fully connected layer
self.cfc = nn.Conv1d(channel, channel, kernel_size=3+channel, bias=False,
groups=channel)
self.bn = nn.BatchNorm1d(channel)
self.gram = GramMatrix()
def forward(self, x):
b, c, _, _ = x.size()
# Style pooling
mean = x.view(b, c, -1).mean(-1).unsqueeze(-1)
std = x.view(b, c, -1).std(-1).unsqueeze(-1)
median = x.view(b, c, -1).median(-1)[0].unsqueeze(-1)
gram = self.gram(x)
u = torch.cat((mean, std, median, gram), -1) # (b, c, 2+c)
# Style integration
z = self.cfc(u) # (b, c, 1)
z = self.bn(z)
g = torch.sigmoid(z)
g = g.view(b, c, 1, 1)
return x * g.expand_as(x)
<file_sep>/resnet_with_block.py
import torch.nn as nn
from torchvision.models import ResNet
from layer_blocks import SELayer, SRMWithCorrMatrix, SRMLayer, SRMWithMedian
import layer_blocks
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
bias=False)
def basic_block_factory(layer_block=None):
# Factory for using torchvision ResNet class
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
reduction=16):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
if layer_block is not None:
self.layer_block = layer_block(planes, reduction)
else:
self.layer_block = None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.layer_block is not None:
out = self.layer_block(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
return BasicBlock
def bottleneck_factory_with_layer_at_end(layer_block=SRMWithCorrMatrix):
# Factory for using torchvision ResNet class
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None,
reduction=16):
super(Bottleneck, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes, stride=stride)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = conv1x1(planes, planes * self.expansion)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
if layer_block is not None:
self.layer_block = layer_block(planes * self.expansion,
reduction)
else:
self.layer_block = None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.layer_block is not None:
out = self.layer_block(out)
if self.downsample:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
return Bottleneck
def bottleneck_factory(layer_block=None):
# Factory for using torchvision ResNet class
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None,
reduction=16):
super(Bottleneck, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes, stride=stride)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = conv1x1(planes, planes * self.expansion)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
if layer_block is not None:
self.layer_block = layer_block(planes * self.expansion,
reduction)
else:
self.layer_block = None
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.layer_block is not None:
out = self.layer_block(out)
if self.downsample:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
return Bottleneck
class CifarResNetWithBlock(nn.Module):
def __init__(self, n_size, num_classes=10, layer_block=None,
reduction=None):
super(CifarResNetWithBlock, self).__init__()
self.inplanes = 16
self.conv1 = conv3x3(3, self.inplanes, stride=1)
self.bn1 = nn.BatchNorm2d(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.block = basic_block_factory(layer_block=layer_block)
self.layer1 = self._make_layer(16, blocks=n_size, stride=1,
reduction=reduction)
self.layer2 = self._make_layer(32, blocks=n_size, stride=2,
reduction=reduction)
self.layer3 = self._make_layer(64, blocks=n_size, stride=2,
reduction=reduction)
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(64, num_classes)
self.initialize()
def initialize(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, planes, blocks, stride, reduction):
downsample = None
layers = []
if stride != 1 or self.inplanes != planes:
downsample = nn.Sequential(conv1x1(self.inplanes, planes,
stride=stride),
nn.BatchNorm2d(planes))
layers.append(self.block(self.inplanes, planes, stride, downsample,
reduction))
self.inplanes = planes
for i in range(1, blocks):
layers.append(self.block(self.inplanes, planes,
reduction=reduction))
self.inplanes = planes
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# ImageNet ResNets34
def resnet34(num_classes=1000):
model = ResNet(basic_block_factory(), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def se_resnet34(num_classes=1000):
model = ResNet(basic_block_factory(layer_block=SELayer), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def srm_resnet34(num_classes=1000):
model = ResNet(basic_block_factory(layer_block=SRMWithCorrMatrix), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
# ImageNet ResNets50
def resnet50(num_classes=1000):
model = ResNet(bottleneck_factory(), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def se_resnet50(num_classes=1000):
model = ResNet(bottleneck_factory(layer_block=SELayer), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def srm_resnet50(num_classes=1000):
model = ResNet(bottleneck_factory(layer_block=SRMWithCorrMatrix), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def oursrm_resnet50(num_classes=1000):
model = ResNet(bottleneck_factory(layer_block=SRMWithCorrMatrix), [3, 4, 6, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
# ImageNet ResNets101
def resnet101(num_classes=1000):
model = ResNet(bottleneck_factory(), [3, 4, 23, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def se_resnet101(num_classes=1000):
model = ResNet(bottleneck_factory(layer_block=SELayer), [3, 4, 23, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
def srm_resnet101(num_classes=1000):
model = ResNet(bottleneck_factory(layer_block=SRMWithCorrMatrix), [3, 4, 23, 3],
num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model
# Cifar10 ResNets32
def cifar_resnet20(**kwargs):
model = CifarResNetWithBlock(3, **kwargs)
return model
def cifar_se_resnet20(**kwargs):
model = CifarResNetWithBlock(3, layer_block=SELayer, reduction=16, **kwargs)
return model
def cifar_srm_resnet20(**kwargs):
model = CifarResNetWithBlock(3, layer_block=SRMLayer, **kwargs)
return model
# Cifar10 ResNets32
def cifar_resnet32(**kwargs):
model = CifarResNetWithBlock(5, **kwargs)
return model
def cifar_se_resnet32(**kwargs):
model = CifarResNetWithBlock(5, layer_block=SELayer, reduction=16,
**kwargs)
return model
def cifar_srm_resnet32(**kwargs):
model = CifarResNetWithBlock(5, layer_block=SRMLayer, **kwargs)
return model
def cifar_srm_with_corr_matrix_resnet32(**kwargs):
model = CifarResNetWithBlock(5, layer_block=SRMWithCorrMatrix, **kwargs)
return model
def cifar_srm_with_median_resnet32(**kwargs):
model = CifarResNetWithBlock(5, layer_block=SRMWithMedian, **kwargs)
return model
def cifar_srm_with_median_and_corr_matrix_resnet32(**kwargs):
model = CifarResNetWithBlock(5, layer_block=layer_blocks.SRMWithMedianAndCorrMatrix, **kwargs)
return model
<file_sep>/README.md
# SRM Network PyTorch
An implementation of "SRM : A Style-based Recalibration Module for Convolutional Neural Networks".
## Implementation
#### experiments.py
Run the requested model on the preffered dataset.
#### layer_blocks.py
Implementation of SE block as well as SRM block. Including all variations and attemps for improving the original SRM block proposed in the paper.
#### resnet_with_block
Combine the different layer blocks implemented in layer_blocks.py with resnet architecture.
#### Trainer
Containing a class abstracting the various tasks of training models, and a specific SRM trainer.
#### cifar10.py
An interface for loading cifar10 dataset.
#### plot.py print_fit_result.py
Those files are intended to print the results of the experiments.
## Training
#### python experiment.py --model_name <model_name>
model_name options are:
1. srmnet
2. senet
3. resnet
4. srm_with_corr
5. srm_with_median
6. srm_median_and_corr
```
## Training parameters
### Cifar
```python
batch_size = 128
epochs_count = 100
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = MultiStepLR(optimizer, [70, 80], 0.1)
```
## Results
### Cifar10
| |ResNet32|Se-ResNet32|SRM-ResNet32|
|:----------|:-------|:----------|:-----------|
|accuracy |92.1% |92.5% |89.7% |
<file_sep>/imagenet.py
import os
import torchvision
import torchvision.transforms as transforms
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform_train = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize
])
transform_test = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize
])
def get_datasets(data_dir):
return {
'train': torchvision.datasets.ImageNet(root=data_dir,
train=True,
download=True,
transform=transform_train),
'val': torchvision.datasets.ImageNet(root=data_dir,
train=False,
download=True,
transform=transform_test)
}
# def get_datasets(data_dir):
# train_dir = os.path.join(data_dir, 'train')
# val_dir = os.path.join(data_dir, 'val')
#
# return {
# 'train': torchvision.datasets.ImageFolder(root=train_dir,
# transform=transform_train),
# 'val': torchvision.datasets.ImageFolder(root=val_dir,
# transform=transform_test)
# }
<file_sep>/cifar10_train.py
import argparse
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import MultiStepLR
from back import Bone, utils
from resnet_with_block import cifar_resnet32, cifar_se_resnet32,\
cifar_srm_resnet32
import cifar10
data_dir = 'cifar10'
model_names = ['resnet', 'senet', 'srmnet']
num_classes = 10
batch_size = 128
epochs_count = 100
num_workers = 8
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', required=True, choices=model_names)
args = parser.parse_args()
datasets = cifar10.get_datasets(data_dir)
if args.model_name == 'resnet':
model = cifar_resnet32(num_classes=num_classes)
elif args.model_name == 'senet':
model = cifar_se_resnet32(num_classes=num_classes)
elif args.model_name == 'srmnet':
model = cifar_srm_resnet32(num_classes=num_classes)
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=1e-4)
scheduler = MultiStepLR(optimizer, [70, 80], 0.1)
criterion = nn.CrossEntropyLoss()
backbone = Bone(model,
datasets,
criterion,
optimizer,
scheduler=scheduler,
scheduler_after_ep=False,
metric_fn=utils.accuracy_metric,
metric_increase=True,
batch_size=batch_size,
num_workers=num_workers,
weights_path=f'weights/cifar_best_{args.model_name}.pth',
log_dir=f'logs/cifar_{args.model_name}')
backbone.fit(epochs_count)
| 43b877f775b0e888f95b56ca1ec52f6b95a4309e | [
"Markdown",
"Python",
"Shell"
] | 10 | Python | adi-horowitz/final-project | 0fd864663e92a6bcaa5f068e3e45b2a76460d335 | 693d0fbcc8be98dc49ba79800d074f535aef84ee |
refs/heads/master | <repo_name>Rcchin/TwitterBot<file_sep>/README.md
# TwitterBot
Welcome! This is a bot built using Python. It's a basic bot however it can help users manage their account by automatically
following back, reTweeting or favoriting tweets, and responding to other users Tweets.
## Getting Started
To start you'll need a twitter developer account. Go to apps.twitter.com and sign up if you haven't. Otherwise sign in.
Create a Twitter Application and generate Consumer Key, Consumer Secret, Access Token, and Access Token Secret. Then copy
and paste those values into the program. Once done the program will work.
## More Info
Tweepy is an API class that provides access to Twitter's RESTful API methods. Tweepy create model class instances that
contains the data returned from Twitter's RESTful API. We can then use these inside our program. An example of a model
is our user = api.me(). Although the bot has it's functionality working to make it more user friendly I should add a GUI
or at least a way to edit the search, keyword, number of tweets etc. through command line. Currently have to edit the
code to get it what you want to do exactly. Still a WIP.
## Built With
' ' '
* Python
* Tweepy
' ' '
## References
* [Free Code Camp](https://medium.freecodecamp.org/creating-a-twitter-bot-in-python-with-tweepy-ac524157a607)
* [Tweepy Documentation](https://tweepy.readthedocs.io/en/v3.5.0/index.html)<file_sep>/botMain.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 13:22:06 2019
Twitter Bot A using Tweepy
This bot can
1. Follow everyone following you.
2. Favorite and Retweet a Tweet based on keywords
3. Reply to a user based on a keyword
@author: <NAME>
"""
"""
runs through terminal but have to update the code with correct s
"""
import tweepy
"""
Must link your Twitter account to our bot. Must create a Twitter Application and generate a Consumer Key,
Consumer Secret, Access Token, and Access Token Secret.
"""
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
""" testing connection and making sure it program can connect to Twitter
user = api.me()
print(user.name)
"""
"""
followBack makes sure to follow all your current followers
"""
def followBack():
user = api.me()
for follower in tweepy.Cursor(api.followers).items():
follower.follow()
print ("Followed everyone that is following " + user.name)
"""
searches Twitter for keyword and reTweets or favorites based on that keyword
"""
def reTweetFavorite():
search = "Aimi" #This is the keyword you'll be searching for
numberOfTweets = 2
#This is the number of tweets you wish to interact with
for tweet in tweepy.Cursor(api.search,search).items(numberOfTweets):
try:
tweet.retweet() #can replace this as tweet.favorite to favorite instead of retweeting
print('Retweeted this tweet')
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
"""
Replies to Tweets based on keyword
"""
def reply():
search ="Bang Dream Aimi"
numberOfTweets = 2
phrase = "<3" #What your response tweet will be
for tweet in tweepy.Cursor(api.search,search).items(numberOfTweets):
try:
tweetId = tweet.user.id #id of tweet you're responding to
username = tweet.user.screen_name#user's username you're responding too.
api.update_status("@"+username + " " + phrase,in_reply_to_status_id = tweetId)
print("Replied with " + phrase + " to " +username)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
| 0c3230777319fac450dd112f1a84e054c106b8a4 | [
"Markdown",
"Python"
] | 2 | Markdown | Rcchin/TwitterBot | dc9a6e4104308c9dd808d7878a2669af1bc560d6 | 2a3b16df8b74e9302140a89c6209da28d87c2e14 |
refs/heads/master | <repo_name>hiketra/SimpleTetris<file_sep>/src/MainWindow.java
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* The MainWindow through which the user plays the game. Specifies the positioning
* of all the JComponents that make up the user interface.
* @author emma
* @see Canvas
*/
public class MainWindow extends JFrame{
private Canvas canvas; //the canvas for which the positioning of the
private int lineCount = 0; //the number of lines cleared
private Sidebar sidebar; //the side bar
/**
* Configures the layout, adds the appropriate JComponents, etc.
*/
public MainWindow(){
JPanel contentPane = new JPanel(new FlowLayout());
setContentPane(contentPane);
canvas = new Canvas();
contentPane.add(canvas);
sidebar = new Sidebar();
contentPane.add(sidebar);
setVisible(true);
setResizable(false);
pack();
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* Calls the moveActiveBlock method of the canvas
* @see Canvas
*/
public void moveActiveBlock(){
canvas.moveActiveBlock();
}
/**
* Calls the checkActiveBlockValid method of the canvas
* @see Canvas
* @return canvas.checkActiveBlockValid()
*/
public boolean checkActiveBlockValid(){
return canvas.checkActiveBlockValid();
}
/**
* Calls the getActiveBlock method of the canvas
* @see Canvas
* @return canvas.getActiveBlock()
*/
public ComplexShape getActiveBlock(){
return canvas.getActiveBlock();
}
/**
* Checks if the score has changed and returns true if so
*/
public boolean hasScoreChanged(){
if(lineCount!=canvas.getLineCount()){
lineCount = canvas.getLineCount();
sidebar.setScore(lineCount*10);
return true;
}
return false;
}
/**
* Get the current level
* @return sidebar.getLevel()
*/
public int getLevel(){
return sidebar.getLevel();
}
}
<file_sep>/src/Driver.java
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* Driver class - initialises the MoveActiveBlock thread and creates a MainWindow object
*
* @author emma
*/
public class Driver {
private static MainWindow window;//the main window of the game
private static boolean gameOver = false;//determines whether the game is over or not
public static void main(String args[]) throws InterruptedException{
window = new MainWindow();//the main window
Thread MoveActiveBlockThread = new Thread(new MoveActiveBlock());//the active block thread
MoveActiveBlockThread.start();//starting the thread
}
/**
* Thread for moving the active block and checking if the game is over
* @author emma
*
*/
private static class MoveActiveBlock implements Runnable {
public void run(){
while(!gameOver){//logic for when the game is running
if(!window.checkActiveBlockValid()){//if the active block has reached the top of the window
JFrame gameOverWindow = new JFrame("Game Over");//present game over window
gameOverWindow.setVisible(true);
gameOverWindow.setSize(200, 100);
gameOverWindow.add(new JLabel("Sorry! Game over!", JLabel.CENTER));
gameOver = true;
}
if(!gameOver){//if game is not over
window.moveActiveBlock();//move the active block down
window.hasScoreChanged();//check if score has changed and if so update
int level = window.getLevel() + 1;
try {
Thread.sleep(1000/level);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
<file_sep>/src/Canvas.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JPanel;
/**
* Represents the movement of the blocks and shapes, in addition to registering
* the user's key presses. Forms part of the MainWindow
* @author emma
* @see MainWindow
* @see Block
* @see ComplexShape
*/
public class Canvas extends JPanel {
public static final int WIDTH = 260; //the width of the canvas in pixels
public static final int HEIGHT = 640; //the height of the canvas in pixels
private int lineCount = 0; //the number of lines cleared
ComplexShape activeBlock = new Line(); //first shape will always be a line
private Block[][] blocksInPlace = new Block[13][32]; //array of blocks covering every possible coordinate
/**
* Defines mouse listeners and key listeners in addition to initialising the blocksInPlace array. Also
* defines properties of the JPanel it extends.
*/
public Canvas(){
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
requestFocusInWindow();
}
});
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
handleKeyPress(e);
}
});
for(int i=0; i<13; i++){
for(int j=0; j<32; j++){
blocksInPlace[i][j] = new Block(Color.BLUE, 0, 0, false, false);
//passing dummy default colour
}
}
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setOpaque(true);
setFocusable(true);
setBackground(Color.WHITE);
}
/**
* Returns the number of lines cleared
* @return lineCount
*/
public int getLineCount(){
return lineCount;
}
/**
* Contains all the logic to handle key presses, such as the logic for moving a shape
* to the left when the left key is pressed.
*
* @param e
*/
public void handleKeyPress(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT){
//move the activeBlock to the left
if(activeBlock.isValidLeftMove(blocksInPlace)){
activeBlock.moveLeft();
repaint();
}
}
if (key == KeyEvent.VK_RIGHT){
//move the activeBlock to the right
if(activeBlock.isValidRightMove(blocksInPlace)){
activeBlock.moveRight();
repaint();
}
}
if (key == KeyEvent.VK_DOWN){
//move the activeBlock down
if(activeBlock.isValidDownwardMove(blocksInPlace)){
activeBlock.moveDown();
repaint();
}
}
if(key == KeyEvent.VK_UP){
//rotate the activeBlock
if(activeBlock.isValidRotation(blocksInPlace)){
activeBlock.rotateBlocks();
repaint();
}
}
if(key == KeyEvent.VK_SPACE){
//move the block down continuously until there are no more valid moves to be made
while(activeBlock.isValidDownwardMove(blocksInPlace)){
activeBlock.moveDown();
repaint();
}
}
}
/**
* Move the activeBlock down one block.
*/
public void moveActiveBlock(){
detectFullLine();//check if there is a full line
if(activeBlock.isValidDownwardMove(blocksInPlace) ){
activeBlock.moveDown();
repaint();
}
}
/**
* Logic to detect whether there is a full line. If there is a full line the appropriate
* blocks will be eliminated and the blocks above the line will adjust appropriately. In addition
* the lineCount will be updated.
*/
public void detectFullLine(){
for(int i=0; i<32; i++){
//looping through each horizontal line
boolean isFullLine = true;
for(int j=0;j<13; j++){
if(!blocksInPlace[j][i].isVisible()){
//if one of the blocks in the line is not visible
isFullLine = false;
//then there is no full line
}
}
if(isFullLine){
//if there is a full line
lineCount++;//update the line count
for(int a = i; a>0; a--){
//loop through the blocksInPlace from the index of the full line upwards
if(a<i){
for(int b=0; b<13; b++){
//move the blocks downward
Block movedDownBlock = blocksInPlace[b][a];
movedDownBlock.moveDown(1);
blocksInPlace[b][a+1] = movedDownBlock;
repaint();
}
}
else{
for(int b=0; b<13; b++){
//make the detected line invisible and no longer active
blocksInPlace[b][a].setIsActive(false);
blocksInPlace[b][a].setIsVisible(false);
repaint();
}
}
}
}
}
}
/**
* Checking to see whether the activeBlock can continue to be 'active'. If it is
* no longer a valid activeBlock it will set in a fixed position and a new activeBlock
* will be generated. Such would be the case if the activeBlock had reached the bottom of
* the canvas.
*
* Returns true if it remains a valid activeBlock
*/
public boolean checkActiveBlockValid(){
if(!activeBlock.isValidDownwardMove(blocksInPlace)){
//if a valid downward move cannot be performed then it is no longer valid as an activeBlock
int minStdYCoord = activeBlock.getMinStdYCoord();
if(minStdYCoord<1){
return false;
}
//if we have hit the last row it can no longer be a valid active block
activeBlock.setIsActive(false);
//deactivate
int[][] stdCoords = activeBlock.getStdCoords();
Block[] blocks = activeBlock.getBlocks();
for(int i=0; i<4; i++){
blocksInPlace[stdCoords[i][0]][stdCoords[i][1]] = blocks[i];
}
//place in static blocks array
Random pickNextComplexShape = new Random();
int shapeToUse = pickNextComplexShape.nextInt(4);
switch(shapeToUse){
case 0:
activeBlock = new Cube();
break;
case 1:
activeBlock = new LShape();
break;
case 2:
activeBlock = new Line();
break;
case 3:
activeBlock = new TShape();
break;
}
if(!activeBlock.isValidDownwardMove(blocksInPlace)){
minStdYCoord = activeBlock.getMinStdYCoord();
if(minStdYCoord<1){
return false;
}
}
//create new active block
}
return true;
}
/**
* Generate a random x or y coord
* @param isXCoord
*/
public static int generateRandomCoord(boolean isXCoord){
Random generator = new Random();
if(isXCoord){
return (generator.nextInt(Canvas.WIDTH/Block.WIDTH)*Block.WIDTH) -1;
}
else{
return generator.nextInt(Canvas.HEIGHT/Block.HEIGHT)*Block.HEIGHT;
}
}
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.WHITE);
activeBlock.paintShape(g);
for(int i=0; i<13; i++){
for(int j=0; j<32; j++){
blocksInPlace[i][j].paintSquare(g);
}
}
}
/**
* Returns the activeBlock
* @return activeBlock
*/
public ComplexShape getActiveBlock() {
return activeBlock;
}
}
<file_sep>/src/ValidColour.java
import java.awt.Color;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Enum of colours that are valid for a Block object
* @see Block
* @author emma
*/
public enum ValidColour {
BLUE(0, Color.BLUE),
PINK(1, Color.PINK),
ORANGE(2, Color.ORANGE),
GREEN(3, Color.GREEN),
MAGENTA(4, Color.MAGENTA),
RED(5, Color.RED),
CYAN(6, Color.CYAN);
private final int iIndex;//the index of the colour
private final Color iColour;//the colour it self
private static final List<ValidColour> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));//a static list of all of the values
private static final int SIZE = VALUES.size();//the size of the list
private static final Random RANDOM = new Random();//seed for getting random colours
/**
* Default constructor
* @param index
* @param colour
*/
ValidColour(int index, Color colour){
iIndex=index;
iColour = colour;
}
/**
* Get the index of the ValidColour
* @return iIndex
*/
public int getIndex(){
return iIndex;
}
/**
* Get the colour of the ValidColour
* @return iColour
*/
public Color getColour(){
return iColour;
}
/**
* Static method for getting a random ValidColour entry
*/
public static ValidColour randomValidColour() {
return VALUES.get(RANDOM.nextInt(SIZE));
//get an element from the static VALUES arrayList at a random index value
}
}
| 853ff72a13b234229884c629cdf4f59eac0cc590 | [
"Java"
] | 4 | Java | hiketra/SimpleTetris | 9385bdd60efb31b793be2487823161b632f637c2 | e4dc94eed0e976e4e2ee30af1a1da2fa0ad9da05 |
refs/heads/master | <repo_name>Tahamosaad/Gulfcoupon_web<file_sep>/Gulfcoupon_web/Models/Pramters.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Gulfcoupon_web.Models
{
public class Pramters
{
public string Criteria { get; set; }
public string CriteriaCap { get; set; }
public string ReportID { get; set; }
public string Dest { get; set; }
public string RepPath { get; set; }
}
}<file_sep>/Gulfcoupon_web/Controllers/CountriesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAL;
using System.IO;
namespace Gulfcoupon_web.Controllers
{
public class CountriesController : Controller
{
GulfEntities db = new GulfEntities();
// GET: Countries
public ActionResult Index()
{
return View();
}
public ActionResult Create_country()
{
ViewBag.country_id = new SelectList(db.Countries.ToList(), "Country_ID", "name");
return View();
}
[HttpPost]
public ActionResult Create_country(Countries info, HttpPostedFileBase flag)
{
string newname = "";
string extention = Path.GetExtension(flag.FileName);
newname = DateTime.Now.Ticks.ToString() + extention;
var mypath = Path.Combine(Server.MapPath("~/FlagImg"), newname);
flag.SaveAs(mypath);
if (ModelState.IsValid)
{
info.flag = newname;
db.Countries.Add(info);
if (db.SaveChanges() > 0)
{
TempData["success"] = "success add country";
}
else
{
TempData["error"] = "not add yet";
}
}
else
{
TempData["error"] = "Check Some Errors";
}
return RedirectToAction("Create_country");
}
public PartialViewResult GetAll()
{
return PartialView("_GetAll", db.Countries.ToList());
}
}
}<file_sep>/Gulfcoupon_web/Controllers/BusinessController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using DAL;
using System.IO;
namespace Gulfcoupon_web.Controllers
{
public class BusinessController : Controller
{
private GulfEntities db = new GulfEntities();
// GET: Business
public ActionResult Index()
{
var businessName = db.BusinessName.Include(b => b.Branch).Include(b => b.BusinessType);
return View(businessName.ToList());
}
// GET: Business/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessName businessName = db.BusinessName.Find(id);
if (businessName == null)
{
return HttpNotFound();
}
return View(businessName);
}
// GET: Business/Create
public ActionResult Create()
{
ViewBag.Branch_id = new SelectList(db.Branch, "ID", "Branchname");
ViewBag.BusinessType_id = new SelectList(db.BusinessType, "ID", "BusinessType1");
return View();
}
// POST: Business/Create
[HttpPost]
public ActionResult Create([Bind(Include = "ID,BusinessName1,Logo,Email,Website,BusinessType_id,Branch_id")]BusinessName businessName, HttpPostedFileBase Logo)
{
string newname = "";
string extention = Path.GetExtension(Logo.FileName);
newname = DateTime.Now.Ticks.ToString() + extention;
var mypath = Path.Combine(Server.MapPath("~/Logoimg"), newname);
Logo.SaveAs(mypath);
if (ModelState.IsValid)
{
businessName.Logo = newname;
db.BusinessName.Add(businessName);
if (db.SaveChanges() > 0)
{
TempData["success"] = "success add business";
}
else
{
TempData["error"] = "not add yet";
}
return RedirectToAction("Index");
}
ViewBag.Branch_id = new SelectList(db.Branch, "ID", "Branchname", businessName.Branch_id);
ViewBag.BusinessType_id = new SelectList(db.BusinessType, "ID", "BusinessType1", businessName.BusinessType_id);
return View(businessName);
}
// GET: Business/Edit/5
public BusinessName Get(int id)
{
var query = db.BusinessName.Where(x => x.ID == id).FirstOrDefault();
if (query != null)
{
return query;
}
return null;
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessName businessName = db.BusinessName.Find(id);
if (businessName == null)
{
return HttpNotFound();
}
ViewBag.Branch_id = new SelectList(db.Branch, "ID", "Branchname", businessName.Branch_id);
ViewBag.BusinessType_id = new SelectList(db.BusinessType, "ID", "BusinessType1", businessName.BusinessType_id);
return View(businessName);
}
// POST: Business/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,BusinessName1,Logo,Email,Website,BusinessType_id,Branch_id")] BusinessName businessName)
{
if (ModelState.IsValid)
{
var query = Get(businessName.ID);
if (query != null)
{
query.ID = businessName.ID;
query.Logo = businessName.Logo;
query.Website = businessName.Website;
query.Email = businessName.Email;
query.BusinessName1 = businessName.BusinessName1;
query.BusinessType_id = businessName.BusinessType_id;
query.Branch_id = businessName.Branch_id;
}
//db.Entry(businessName).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Branch_id = new SelectList(db.Branch, "ID", "Branchname", businessName.Branch_id);
ViewBag.BusinessType_id = new SelectList(db.BusinessType, "ID", "BusinessType1", businessName.BusinessType_id);
return View(businessName);
}
// GET: Business/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BusinessName businessName = db.BusinessName.Find(id);
if (businessName == null)
{
return HttpNotFound();
}
return View(businessName);
}
// POST: Business/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BusinessName businessName = db.BusinessName.Find(id);
db.BusinessName.Remove(businessName);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>/Gulfcoupon_web/Controllers/TestController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using Gulfcoupon_web.Models;
namespace Gulfcoupon_web.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
// POST: Test/Create
[HttpPost]
public ActionResult Index(Pramters pram)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<file_sep>/Gulfcoupon_web/Controllers/business_typeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAL;
using System.IO;
namespace Gulfcoupon_web.Controllers
{
public class business_typeController : Controller
{
GulfEntities db = new GulfEntities();
public ActionResult Index()
{
return View();
}
public ActionResult Create_business()
{
ViewBag.country_id = new SelectList(db.BusinessType.ToList(), "ID", "BusinessType");
return View();
}
[HttpPost]
public ActionResult Create_business(BusinessType info, HttpPostedFileBase Photo)
{
string newname = "";
string extention = Path.GetExtension(Photo.FileName);
newname = DateTime.Now.Ticks.ToString() + extention;
var mypath = Path.Combine(Server.MapPath("~/businessImg"), newname);
Photo.SaveAs(mypath);
if (ModelState.IsValid)
{
info.Photo = newname;
db.BusinessType.Add(info);
if (db.SaveChanges() > 0)
{
TempData["success"] = "success add businesstype";
}
else
{
TempData["error"] = "not add yet";
}
}
else
{
TempData["error"] = "Check Some Errors";
}
return RedirectToAction("Create_business");
}
public PartialViewResult GetAll()
{
return PartialView("_GetAll", db.BusinessType.ToList());
}
}
}
<file_sep>/Gulfcoupon_web/Controllers/LoginController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gulfcoupon_web.Models;
using DAL;
namespace Gulfcoupon_web.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult LoginPage()
{
return View();
}
[HttpPost]
public ActionResult LoginPage(UserModel model)
{
GulfEntities db = new GulfEntities();
var sp = db.GetLoginInfo(model.UserName, model.Password);
var item = sp.FirstOrDefault();
if (item == "Success")
{
return Redirect("/Main/Index");
}
else if (item == "User Does not Exists")
{
TempData["NotValidUser"] = item;
}
else
{
TempData["Failedcount"] = item;
}
return View("LoginPage");
}
}
} | 73c0d61cab0eef7f317341f68eae637812948e84 | [
"C#"
] | 6 | C# | Tahamosaad/Gulfcoupon_web | 813fef2960ac9adb0afa6b970e2846474b3ee64a | 4ecac1c663ccfc0777c65eba742179521474b54d |
refs/heads/master | <repo_name>mvanbesien/eclipse-ledclock<file_sep>/README.md
eclipse-ledclock
================
A simple Eclipse plugin that displays the current time using leds
<file_sep>/fr.mvanbesien.ledclock/src/main/java/fr/mvanbesien/ledclock/LedColor.java
package fr.mvanbesien.ledclock;
import org.eclipse.swt.graphics.Image;
public enum LedColor {
YELLOW("/images/yellow.png"), BLUE("/images/blue.png"), GREEN("/images/green.png"), RED("/images/red.png"), OFF(
"/images/off.png"), BLACK("/images/black.png"), PURPLE("/images/purple.png"),
YELLOW_BIG("/images/yellow-big.png"), BLUE_BIG("/images/blue-big.png"), GREEN_BIG("/images/green-big.png"), RED_BIG(
"/images/red-big.png"), OFF_BIG("/images/off-big.png"), BLACK_BIG("/images/black-big.png"), PURPLE_BIG(
"/images/purple-big.png");
private String pathToImage;
LedColor(String pathToImage) {
this.pathToImage = pathToImage;
}
public Image image() {
return Activator.getDefault().getImage(this.pathToImage);
}
}
| 2e4b804f2ca505cddc225ee955c3a79976428f7d | [
"Markdown",
"Java"
] | 2 | Markdown | mvanbesien/eclipse-ledclock | db330570e260ead3ae834ca436b3b99606af2e37 | 5331bb9578a53043d2e4f997dfe8c2278adbc4bc |
refs/heads/master | <file_sep>
# secure_delete


secure_delete is a tool for safely delete files.
Files deleted with secure_delete will be difficult to recover.
# Environment requirements
Python 3.X
Support for Windows and Linux
# Install
```bash
pip install secure_delete
```
# Usage
## Command
```bash
secdel --help
```
## Python lib
```python
from secure_delete import secure_delete
secure_delete.secure_random_seed_init()
secure_delete.secure_delete('Z:\\TEST.exe')
```
# License
MIT License<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import secrets
import random
SECURE_BLOCK_SIZE = 1024 * 16
def enum_paths(root_dir, list_paths=list(), **dict_argv):
bool_include_file = bool(dict_argv.get('include_file', True))
bool_include_dir = bool(dict_argv.get('include_dir', False))
bool_recursion_dir = bool(dict_argv.get('recursion_dir', True))
for sub_path in os.listdir(root_dir):
full_path = os.path.join(root_dir, sub_path)
b_is_dir = os.path.isdir(full_path)
if b_is_dir:
if bool_recursion_dir is True:
enum_paths(full_path, list_paths, **dict_argv)
if bool_include_dir is False:
pass
else:
list_paths.append(full_path)
else:
if bool_include_file is True:
list_paths.append(full_path)
else:
pass
return list_paths
def os_force_remove(file_path: str):
try:
os.remove(file_path)
except OSError as err:
pass
finally:
pass
def os_force_remove_dirs(path: str):
try:
os.removedirs(path)
except OSError as err:
pass
finally:
pass
def secure_random_seed_init():
random.seed(secrets.randbits(64))
return True
def fast_random_bytes(bytes_size):
array = bytearray()
for i in range(bytes_size):
array.append(random.randint(0, 255))
return bytes(array)
def override_random_data(file_path: str):
file_bytes_size = os.path.getsize(file_path)
with open(file_path, "wb", buffering=0) as fp:
write_bytes_size = 0
while write_bytes_size < file_bytes_size:
fp.write(fast_random_bytes(SECURE_BLOCK_SIZE))
write_bytes_size += SECURE_BLOCK_SIZE
fp.flush()
fd = fp.fileno()
os.fsync(fd)
return
def override_fixed_data(file_path: str, fill_bytes=b'\xff'):
if type(fill_bytes) is not bytes:
fill_bytes = b'\xff'
file_bytes_size = os.path.getsize(file_path)
with open(file_path, "wb", buffering=0) as fp:
write_bytes_size = 0
while write_bytes_size < file_bytes_size:
for i in range(SECURE_BLOCK_SIZE):
fp.write(fill_bytes)
write_bytes_size += SECURE_BLOCK_SIZE
fp.flush()
fd = fp.fileno()
os.fsync(fd)
return
def write_random_block(root_path: str):
file_bytes_size = secrets.randbelow(SECURE_BLOCK_SIZE)
with open(root_path, "wb") as fp:
fp.write(fast_random_bytes(file_bytes_size))
fp.flush()
fd = fp.fileno()
os.fsync(fd)
os_force_remove(root_path)
return
def fill_random_data(file_path: str, fill_size=5 * 1024 * 1024 * 1024):
with open(file_path, "wb") as fp:
write_bytes_size = 0
while write_bytes_size < fill_size:
fp.write(fast_random_bytes(1))
write_bytes_size += 1
fp.flush()
fd = fp.fileno()
os.fsync(fd)
return
def upset_inodes(base_path, count=128):
base_name = os.path.basename(base_path)
if base_name == '':
base_path += 'cleanup'
cleanup_list = []
for index in range(count):
rand_path = '%s.%d.rand' % (base_path, index)
cleanup_list.append(rand_path)
write_random_block(rand_path)
for del_path in cleanup_list:
os_force_remove(del_path)
return
def wipe_free_space(base_path: str):
base_name = os.path.basename(base_path)
if base_name == '':
base_path += 'wipe'
cleanup_list = []
index = 0
while True:
try:
rand_path = '%s.%d.rand' % (base_path, index)
cleanup_list.append(rand_path)
fill_random_data(rand_path)
except OSError as err:
# print(err.characters_written)
break
for del_path in cleanup_list:
os_force_remove(del_path)
return
def secure_delete(base_path: str, count: int=3):
if count < 1:
count = 1
if os.path.exists(base_path) is False:
return
if os.path.isdir(base_path):
file_list = enum_paths(base_path)
for file_path in file_list:
secure_delete(file_path,count)
os_force_remove_dirs(base_path)
elif os.path.isfile(base_path):
random_count = count - 1
for num in range(random_count):
override_random_data(base_path)
# override_fixed_data(base_path)
override_fixed_data(base_path)
os_force_remove(base_path)
else:
os_force_remove(base_path)
return
if __name__ == '__main__':
# secure_random_seed_init()
# print(fast_random_bytes(10))
# secure_delete('I:\\1.exe')
# wipe_random_block('I:\\1.exe')
# wipe_free_space('I:\\')
pass
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import argparse
def insert_import_path(string_path):
sys.path.insert(0, string_path)
def insert_package_path():
current_file_path = os.path.abspath(__file__)
current_file_dir = os.path.dirname(current_file_path)
parent_file_dir = os.path.join(current_file_dir, '../')
insert_import_path(current_file_dir)
insert_import_path(parent_file_dir)
return
try:
# 自定义import路径
insert_package_path()
from secure_delete import secure_delete
except ImportError:
import secure_delete
pass
def main():
parser = argparse.ArgumentParser()
parser.add_argument('PATH', nargs='?', type=str)
parser.add_argument('--count', default=1, type=int)
parser.add_argument('--wipe_free_space', action='store_true')
parser.add_argument('--upset_inodes', action='store_true')
args = parser.parse_args()
if args.PATH is None:
parser.print_help()
exit(0)
if os.path.exists(args.PATH) is False:
pass
else:
secure_delete.secure_delete(args.PATH, args.count)
if args.wipe_free_space is True:
secure_delete.wipe_free_space(args.PATH)
if args.upset_inodes is True:
secure_delete.upset_inodes(args.PATH, args.count)
return
if __name__ == '__main__':
main()
pass
| c47a182cf5ee5b5c3ff0275d983b60089110d6fd | [
"Markdown",
"Python"
] | 3 | Markdown | ag-python/secure-delete | f10b0a505f0551e35959e0c4c3b0070398fad2a0 | 408f97cfb7ded4ef993e91ee2de42219f1014f9a |
refs/heads/master | <repo_name>marcuspitz/angular-reactivex-switchmap<file_sep>/README.md
# angular-reactivex-switchmap
Angular / ReactiveX - switchMap
# Purpose
Explain the use of RxJS - switchMap the simplest and easiest as possible.
# Why?
I've searched for some simple examples to learn about RxJS switchMap component, and I've had too much difficult to reach a simple example that could teach me how and when use it.
# Explanation
There're 3 main streams on the example given:
1) timer(0,5000)
2) interval(1000)
3) interval(100)
The first stream calls its subscribers each 5 seconds, the second stream calls each 1 second and the last one calls each 0.1 second.
Whatever stream, when it calls its subscribers and inside the PIPE there is a switchMap, this subscriber will be cancelled and create another one. That's the reason each 5 seconds the second stream restart counting and the reason each 1 second the last stream restart couting.
<b>Attention</b>: `tap` operator is just to do something inside the pipe ( the same as the old operator `do`).
# Live example
https://stackblitz.com/edit/angular-reactivex-switchmap
<file_sep>/app/index.ts
import { timer, interval } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
//start now and run each 5 seconds
const source = timer(0, 5000);
const example = source.pipe(tap((b) => (console.log("every 5 seconds, how many times is it running? " + b))),
switchMap(() => interval(1000).pipe(
tap((a) => (console.log("every 1 seconds:" + a))),
switchMap(() => interval(100).pipe(
tap((c) => console.log("every 0.1 seconds:" + c))))))
);
const subscribe = example.subscribe(); | f23c31ed624344e7bb829d3a0660814cc5821680 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | marcuspitz/angular-reactivex-switchmap | 591ce423b093ca3879f7906b159e82975420e58b | 4cef0af21b4067e630dd5f91c1f0441a15e6ccc4 |
refs/heads/master | <repo_name>spenserhale/laravel-priority-todo-lists<file_sep>/.env.php
<?php
$clear_db_url = parse_url(getenv("CLEARDB_DATABASE_URL"));
return array(
'clear_db_host' => $clear_db_url["host"],
'clear_db_database' => substr($clear_db_url["path"], 1),
'clear_db_username' => $clear_db_url["user"],
'clear_db_password' => $clear_db_url["pass"]
); | dbfb530a9f67acdfdf4d002e2c6d60bf9e3c0fd1 | [
"PHP"
] | 1 | PHP | spenserhale/laravel-priority-todo-lists | 04a9eac99dfb0b102749202fa064fb47824f4dcc | 89add9219f332b1963d07e35841d5bc927c108fb |
refs/heads/master | <file_sep>package com.pccw.expm.activemq;
import com.pccw.expm.activemq.plugin.DestinationCode;
public class MessageEntry implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -7463908979616882683L;
private String source;
private String target;
private String serverNo;
private String appKey;
private Object data;
public MessageEntry() {
}
/**
*
* @param source
* 消息生产者companyKey
* @param serverNo
* 企业端编号
* @param target
* 消息接收者companyKey
* @param appKey
* 应用Key
* @param data
* 应用数据
*/
public MessageEntry(String source, String serverNo, String target, String appKey, Object data) {
this.source = source;
this.target = target;
this.appKey = appKey;
this.data = data;
this.serverNo = serverNo;
}
public String getSource() {
return source;
}
public String getTarget() {
return target;
}
public String getAppKey() {
return appKey;
}
public Object getData() {
return data;
}
public String getServerNo() {
return serverNo;
}
@Override
public String toString() {
// Destination命名规范,QUEUE_CLIENT_PREFIX+"企业端编号serverNo"+."消息生产者comkey"+."消息发送目标(接收者)comkey"
return new StringBuilder(DestinationCode.QUEUE_CLIENT_PREFIX).append(serverNo).append(".").append(source).append(".")
.append(target).toString();
}
}
<file_sep>package com.pccw.expm.activemq.plugin;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ConsumerBrokerExchange;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.Subscription;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.security.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JdbcSecurityBroker extends BrokerFilter {
private static Logger logger = LoggerFactory.getLogger(JdbcSecurityBroker.class);
private JdbcAuthorizationManager jdbcAuthorizationManager;
public JdbcSecurityBroker(Broker next, JdbcAuthorizationManager jdbcAuthorizationManager) {
super(next);
this.jdbcAuthorizationManager = jdbcAuthorizationManager;
}
@Override
public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
// context.getBroker().
SecurityContext s = context.getSecurityContext();
if (s == null) {
jdbcAuthorizationManager.allowedConnection(info);
s = new SecurityContext(info.getUserName()) {
@Override
public Set<Principal> getPrincipals() {
Set<Principal> groups = new HashSet<Principal>();
groups.add(new GroupPrincipal("users"));
return groups;
}
};
context.setSecurityContext(s);
}
try {
super.addConnection(context, info);
} catch (Exception e) {
context.setSecurityContext(null);
throw e;
}
}
@Override
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
final SecurityContext securityContext = context.getSecurityContext();
if (securityContext == null) {
throw new SecurityException("User is not authenticated.");
}
if (!jdbcAuthorizationManager.allowedRemoveDestination(securityContext, destination)) {
throw new SecurityException("User " + securityContext.getUserName() + " is not authorized to remove: " + destination);
}
super.removeDestination(context, destination, timeout);
}
@Override
public Destination addDestination(ConnectionContext context, ActiveMQDestination destination, boolean create) throws Exception {
final SecurityContext securityContext = context.getSecurityContext();
String name = destination.getPhysicalName();
if (logger.isDebugEnabled()) {
logger.debug("destination:" + name);
}
if (securityContext == null) {
throw new SecurityException("User is not authenticated.");
}
Destination existing = this.getDestinationMap().get(destination);
if (existing != null) {
return super.addDestination(context, destination, create);
}
jdbcAuthorizationManager.allowedDestination(securityContext, destination);
return super.addDestination(context, destination, create);
}
@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
final SecurityContext subject = context.getSecurityContext();
if (subject == null) {
throw new SecurityException("User is not authenticated.");
}
jdbcAuthorizationManager.allowedConsumer(subject, info);
return super.addConsumer(context, info);
}
@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
SecurityContext subject = context.getSecurityContext();
if (subject == null) {
throw new SecurityException("User is not authenticated.");
}
jdbcAuthorizationManager.allowedProducer(subject, info);
super.addProducer(context, info);
}
@Override
public void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception {
SecurityContext subject = producerExchange.getConnectionContext().getSecurityContext();
if (subject == null) {
throw new SecurityException("User is not authenticated.");
}
jdbcAuthorizationManager.allowedSend(subject, messageSend);
super.send(producerExchange, messageSend);
}
@Override
public void acknowledge(ConsumerBrokerExchange consumerExchange, MessageAck ack) throws Exception {
SecurityContext subject = consumerExchange.getConnectionContext().getSecurityContext();
if (subject == null) {
throw new SecurityException("User is not authenticated.");
}
super.acknowledge(consumerExchange, ack);
jdbcAuthorizationManager.allowedAcknowledge(subject, ack);
}
@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
jdbcAuthorizationManager.allowedRemoveConnection( info);
super.removeConnection(context, info, error);
}
}
<file_sep>package com.pccw.expm.activemq;
public class MessageAppKeyConstant {
/** 企业确认关系应用KEY */
public static final String APP_KEY_CONFIRM_RELATION = "com.expm.relation.confirm";
/** 企业注销关系应用KEY */
public static final String APP_KEY_LOGOFF_RELATION = "com.expm.relation.logoff";
/** 修改可用信用额度 */
public static final String APP_KEY_UPDATE_CREDIT = "com.expm.relation.creditupdate";
/** 发送协议 */
public static final String APP_KEY_COMMIT_AGREEMENT = "com.expm.agreement.commit";
/** 确认协议 */
public static final String APP_KEY_CONFIRM_AGREEMENT = "com.expm.agreement.confirm";
/** 取消协议 */
public static final String APP_KEY_CANCEL_AGREEMENT = "com.expm.agreement.cancel";
/** 采购关闭协议 */
public static final String APP_KEY_CLOSE_AGREEMENT = "com.expm.agreement.close";
/** 发送订单 */
public static final String APP_KEY_SEND_ORDER = "com.expm.order.send";
/** 采购确认修改订单 */
public static final String APP_KEY_CONFIRMCHANGE_ORDER = "com.expm.order.confirmchange";
/** 采购取消订单 */
public static final String APP_KEY_PURCHASECANCEL_ORDER = "com.expm.order.purchasecancel";
/** 采购签收发货单 */
public static final String APP_KEY_SIGNCONSIGN_ORDER = "com.expm.order.signconsign";
/** 结算单处理 */
public static final String APP_KEY_EXECUTE_SETTLED = "com.expm.settled.execute";
/** 确认订单 */
public static final String APP_KEY_CONFIRM_ORDER = "com.expm.order.confirm";
/** 调整订单 */
public static final String APP_KEY_MODIFY_ORDER = "com.expm.order.modify";
/** 销售取消订单 */
public static final String APP_KEY_CANCEL_ORDER = "com.expm.order.cancel";
/** 创建发货单 */
public static final String APP_KEY_CREATECONSIGN_ORDER = "com.expm.order.createconsign";
/** 销售代签发货单 */
public static final String APP_KEY_AGENTSIGN_ORDER = "com.expm.order.agentsign";
/** 创建结算单 */
public static final String APP_KEY_CREATESETTLED_ORDER = "com.expm.order.createsettled";
/** 关闭结算单 */
public static final String APP_KEY_CLOSE_SETTLED = "com.expm.settled.close";
/** 退回结算单 */
public static final String APP_KEY_ROLLBACK_SETTLED = "com.expm.settled.rollback";
/** 商品发布 */
public static final String APP_KEY_RELEASE_PRODUCT = "com.expm.product.release";
/** 采购处理商品发布 */
public static final String APP_KEY_PROCRESS_PRODUCT = "com.expm.product.procress";
/** 提交评价 */
public static final String APP_KEY_COMMIT_EVAS = "com.expm.evas.commit";
/** 发送注册信息到指定公用平台端*/
public static final String APP_KEY_RECEIVE_COMPANY = "com.expm.company.receive";
/**发送退货单*/
public static final String APP_KEY_SEND_RETURN_BILL = "com.expm.returnBill.sendReturnBill";
/***/
public static final String APP_KEY_SUPPLY_CONFIRM_BILL ="com.expm.returnBill.confirmBill";
}
| f78e3763c51494f5122ae1240b87abb45e8e590a | [
"Java"
] | 3 | Java | anycrane/expm_activemq | 4c6552b3e8d2b27abb6e999e3de103e433f1e4dc | b734ca4caa1ed9b426fb1a8244ed3bbec4a31cd8 |
refs/heads/master | <repo_name>PhilipAnderson/due-raw-usb-hid-test<file_sep>/due/src/HID/HID_device.h
#ifndef HID_device_
#define HID_device_
#include "HID.h"
class HID_device : public HID_ {
public:
HID_device(const char *name) : name(name) {
}
int endpoint() {
return pluggedEndpoint;
}
int available() {
return USBD_Available(pluggedEndpoint + 1);
}
int write(const void *data) {
return USBD_Send(pluggedEndpoint, data, 64);
}
int read(void *data) {
return USBD_Recv(pluggedEndpoint + 1, data, 64);
}
protected:
uint8_t getShortName(char* name) {
int len = strlen(this->name);
for (int i = 0; i < len; i++) {
name[i] = this->name[i];
}
return len;
}
private:
const char *name;
};
#endif
<file_sep>/host/src/main/java/App.java
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
try (USBDevice device = USBDeviceFinder.bySerialNumberString("hid-echo-device")) {
if (device == null) {
System.out.println("device not found");
return;
}
String data = "1234567812345678123456781234567812345678123456781234567812345678";
System.out.println("writing: " + data);
device.write(data);
System.out.println("reading ...");
String received = device.read();
System.out.println("read: " + received);
} catch (IOException e) {
System.out.println(e);
System.out.flush();
}
}
}
<file_sep>/due/src/main.cpp
#include <Arduino.h>
#include "HID/HID_device.h"
HID_device hid("hid-echo-device");
void setup() {
hid.begin();
}
void loop() {
static uint8_t buffer[64] = {};
if (hid.available()) {
hid.read(buffer);
// echo
hid.write(buffer);
}
delay(1);
}
| eed101731f39017a91080261f6e6e678902e531b | [
"Java",
"C++"
] | 3 | C++ | PhilipAnderson/due-raw-usb-hid-test | 0388d6e54a60779394a9057aba15b8e19ece506b | fa8b276d60e7db970b2a3beff891e059441e6468 |
refs/heads/master | <file_sep>#include "clib_math.h"
#include "clib_string.h"
double sin(register double x) {
// A 90 degree phase shift to the right of a cosine function
// is equivalent to a sine function
return cos(x - M_PI_2);
}
float sinf(register float x) {
return (float)(sin((double)x));
}
double cos(register double x) {
register double ret_val_sign;
// For simpler computation, translate the angle x, into the first quadrant.
// Set the variable ret_val_sign to be ether positive or negative depending
// on what the cosine is should be.
// Make the angle positive
// Cosine Identity: cos(x) = cos(-x)
if (x < 0.0) {
x = -x;
}
// Make angle no larger than 360 degrees (2PI) (not inclusive)
while (x >= 2 * M_PI) {
x -= 2 * M_PI;
}
// Handle quadrant 4
if (x >= 3 * M_PI_2) {
x = (2 * M_PI) - x;
ret_val_sign = 1.0;
// Handle quadrant 3
} else if (x >= M_PI) {
x = x - M_PI;
ret_val_sign = -1.0;
// Handle quadrant 2
} else if (x >= M_PI_2) {
x = M_PI - x;
ret_val_sign = -1.0;
// Handle quadrant 1
} else {
ret_val_sign = 1.0;
}
// Now we can actually find the approximation of sin(x)
// Handle the easy cases
if (x <= 0.0) {
return ret_val_sign;
}
if (x == M_PI_2) {
return 0.0;
}
// Now we have an angle in quadrant 1.
// [How This Function Works]
//
// The examples provided here are in degrees for ease of comprehension.
// However, the actual function takes radians.
//
// Start at a 45 degree angle.
// The cosine of 45 degrees is (sqrt(2) / 2).
//
// With these known values the following formulas are used:
// Half Angle Formula: cos(x / 2) = sqrt((1 + cos(x)) / 2)
// Relationship of sine to cosine: sin(x) = sqrt(1 - (cos(x) * cos(x)))
// Add cosines: cos(a + b) = (cos(a) * cos(b)) - (sin(a) * sin(b))
// Subtract cosines: cos(a - b) = (cos(a) * cos(b)) + (sin(a) * sin(b))
//
// The general process is this:
// --The idea is to start with an estimation of 45 degrees and the known cosine value of that
// (sqrt(2) / 2).
// --Next, use the half angle formula to iteratively divide an angle, starting at 45 degrees,
// with the value of (sqrt(2) / 2), in half.
// --Then add or subtract the result to the previous estimation.
//
// Here is an example:
// To approximate the value of cos(56.25 degrees) to following process is preformed.
// 1) Start with a 45 degree angle and the known cosine value of it, (sqrt(2) / 2)
// A = 45 deg
// B = sqrt(2) / 2 = ~0.707
// 2) Next, starting again with 45 degrees and it's known cosine, divide the angle in half.
// a = 45 deg
// b = sqrt(2) / 2 = ~0.707
// new_a = a / 2 = 22.5 deg
// new_b = sqrt((1 + b) / 2) = ~0.924
// 3) new_a and new_b become the new values of a and b respectively.
// a = new_a = 22.5 deg
// b = new_b = ~0.924
// 4) Now, determine whether 45 degrees is more or less than 56.25 degrees.
// Since it is less, we should add this new half angle to it.
// To do this, we will need to find the sine of each of both the new half angle
// and the current working angle. These sine values will be used in the cosine addition
// formula.
// new_A = A + a = 45 deg + 22.5 deg = 67.5 deg
// sin_B = sqrt(1 - (B * B)) = sqrt(1 - (~0.707 * ~0.707)) = ~0.707
// sin_b = sqrt(1 - (b * b)) = sqrt(1 - (~0.924 * ~0.924)) = ~0.383
// new_B = (B * b) - (sin_B * sin_b) = (~0.707 * ~0.924) - (~0.707 * ~0.383) = ~0.383
// 5) new_A and new_B become the new values of A and B respectively.
// A = new_A = 67.5 deg
// B = new_B = ~0.383
// 6) Now, divide the angle in half again.
// new_a = a / 2 = 22.5 deg / 2 = 11.25 deg
// new_b = sqrt((1 + b) / 2) = sqrt((1 + ~0.924) / 2) = ~0.981
// 7) new_a and new_b become the new values of a and b respectively.
// a = new_a = 11.25 deg
// b = new_b = ~0.981
// 8) Now, determine whether 67.5 degrees is more or less than 56.25 degrees.
// Since it is more, we should subtract this new half angle from it.
// To do this, we will need to find the sine of each of both the new half angle
// and the current working angle. These sine values will be used in the cosine
// subtraction formula.
// new_A = A - a = 67.5 deg - 11.25 deg = 56.25 deg
// sin_B = sqrt(1 - (B * B)) = sqrt(1 - (~0.383 * ~0.383)) = ~0.924
// sin_b = sqrt(1 - (b * b)) = sqrt(1 - (~0.981 * ~0.981)) = ~0.195
// new_B = (B * b) + (sin_B * sin_b) = (~0.383 * ~0.981) + (~0.924 * ~0.195) = ~0.556
// 9) new_A and new_B become the new values of A and B respectively.
// A = new_A = 56.25 deg
// B = new_B = ~0.556
// And there you have it. The angle of 56.25 degrees with a cosine value of approximately 0.556.
//
// Below is the implementation of this:
register double working_angle;
register double half_angle;
register double working_angle_value;
register double half_angle_value;
// Initialize to 45 degrees (M_PI_4) and sqrt(2) / 2
working_angle = M_PI_4;
half_angle = working_angle;
working_angle_value = sqrt(2.0) / 2.0;
half_angle_value = working_angle_value;
// Begin iterating
while (working_angle != x && half_angle > 0.0 && half_angle_value > 0.0) {
// Half the angle
half_angle /= 2.0;
half_angle_value = sqrt((half_angle_value + 1) / 2);
register double sin_working_value;
register double sin_half_value;
// Use the Pythagorean Theorem / Unit Circle formula to find the sin values
// of the half angle and the current working angle.
sin_working_value = sqrt(1 - (working_angle_value * working_angle_value));
sin_half_value = sqrt(1 - (half_angle_value * half_angle_value));
// Do we need to add or subtract the half angle from the current approximation
// to get closer to the angle we are trying to approximate (x)?
if (working_angle < x) {
// Add the half angle
working_angle += half_angle;
working_angle_value = (working_angle_value * half_angle_value) - (sin_working_value * sin_half_value);
} else {
// Subtract the half angle
working_angle -= half_angle;
working_angle_value = (working_angle_value * half_angle_value) + (sin_working_value * sin_half_value);
}
}
// Take the resultant working angle approximated cosine value.
// Multiply it by the return sign to get the correct negation for the quadrant.
// Return the final value.
return working_angle_value * ret_val_sign;
}
float cosf(register float x) {
return (float)(cos((double)x));
}
double sqrt(register double x) {
if (x == 0.0) {
return 0.0;
}
if (x < 0.0) {
return NAN;
}
if (x == NAN) {
return NAN;
}
if (x == +INFINITY) {
return +INFINITY;
}
/*
TODO: Inline ASM Optimization
*/
// [How This Function Works]
//
// The process of computing a square root is an iterative process.
// The process approches the correct answer as it is repeated.
// We will repeat the process until one of 4 things is true:
// --The same number has been computed twice in a row. (We have probably reached the limit of precision of the data type)
// --The same number has been computed twice but is alternating with another value. (This is similar to the above case)
// --The number multiplied by itself (squared) equals the number we are trying to find the square root of. (We have found the square root)
// --We have iterated 10000 times and are probably caught in some kind of infinite loop. (Fault condition)
// If this happens, print an error so I know to look for a bug.
//
// For clarity in the equations and examples in this comment:
// --The symbol ^ means exponent.
// --The symbol == means that both sides of an equation equal each other.
// --The symbol = means assignment.
// --The symbol ~ means approximately.
//
// The procedure to find a square root is based on the Newton–Raphson method in Calculus math.
// The root(s) of a function are the value(s) that when passed into it, correspond to that
// function's intersecting of the the X-Axis. Or, in the other words, the value(s) of x that yield f(x) == 0.
// The Newton–Raphson method states that to find a better approximation of the root of a function f(x),
// Use the following formula with a starting approximation of the root(Our guess):
// new_guess == guess - f(guess) / f'(guess)
//
// Here is an example:
//
// Let's say that we want to get the square root of 25. We have the equation:
// x^2 == 25
//
// Convert to a function with an appropriate root:
// x^2 - 25 == 0
// f(x) == x^2 - 25
//
// Find the derivative:
// f'(x) == 2x
//
// Newton–Raphson method Formula:
// Let x be our guess for the iteration.
// new_guess == x - f(x) / f'(x)
//
// Subsitute our functions into the Newton–Raphson method formula:
// new_guess == x - (x^2 - 25) / (2x)
//
// Now just simplify:
// new_guess == (2x^2 - (x^2 - 25)) / (2x)
// new_guess == (2x^2 + -x^2 + 25) / (2x)
// new_guess == (2x^2 - x^2 + 25) / (2x)
// new_guess == (x^2 + 25) / (2x)
// new_guess == (x + 25 / x) / 2
//
// This formula can now be used to iterate to approach the square root of 25:
// new_guess == (x + 25 / x) / 2
// If you think about it, the above formula makes sense. It is basically just finding an average.
// If you divide 25 by less than it's square root, you will get an answer bigger than it's square root.
// If you divide 25 by more than it's square root, you will get an answer smaller than it's square root.
// The further off you are from the square root of 25 in your guess the further off from the result is
// from the square root of 25 in the other direction. Therefore, we just need to find the average
// between the result of the division from 25 and our guess to come up with a new guess that will be
// closer to the square root.
//
// Here we iterate with the formula:
// As I said earlier, let x be our guess for the iteration.
// Start with a guess of 1.
//
// x = 1
// Iteration 1) new_guess = (x + 25 / x) / 2
// Iteration 1) new_guess == 13
// Iteration 1) x = new_guess
// Iteration 2) new_guess = (x + 25 / x) / 2
// Iteration 2) new_guess == ~7.4615
// Iteration 2) x = new_guess
// Iteration 3) new_guess = (x + 25 / x) / 2
// Iteration 3) new_guess == ~5.4060
// Iteration 3) x = new_guess
// Iteration 4) new_guess = (x + 25 / x) / 2
// Iteration 4) new_guess == ~5.0152
// Iteration 4) x = new_guess
// Iteration 5) new_guess = (x + 25 / x) / 2
// Iteration 5) new_guess == ~5.0000
// Iteration 5) x = new_guess
// Iteration 6) new_guess = (x + 25 / x) / 2
// Iteration 6) new_guess == ~5.0000
// Iteration 6) x = new_guess
// THE SQUARE ROOT IS: 5
//
// We can also use N instead of 25 to find a formula that will work to get
// the square root of any real and positive input number:
//
// Let's say that we want to get the square root of N. We have the equation:
// x^2 == N
//
// Convert to a function with an appropriate root:
// x^2 - N == 0
// f(x) == x^2 - N
//
// Find the derivative:
// f'(x) == 2x
//
// Newton–Raphson method Formula:
// Let x be our guess for the iteration.
// new_guess == x - f(x) / f'(x)
//
// Subsitute our functions into the Newton–Raphson method formula:
// new_guess == x - (x^2 - N) / (2x)
//
// Now just simplify:
// new_guess == (2x^2 - (x^2 - N)) / (2x)
// new_guess == (2x^2 + -x^2 + N) / (2x)
// new_guess == (2x^2 - x^2 + N) / (2x)
// new_guess == (x^2 + N) / (2x)
// new_guess == (x + N / x) / 2
//
// We could stop here and use this formula to get the square root:
// new_guess == (x + N / x) / 2
//
// But there is a problem. It is not that it doesn't work.
// It does work, but the first step to solve it, the division of (N / x), is a computationally
// expensive operation. The divide by 2 is not comparatively expensive because it is just a
// decimal point shift in base 2. This formula has to be executed on every iteration. So if
// many iterations are required or many calls to this function are needed by an application,
// this becomes a bit of a bottleneck. What we need is a way to iterate without expensive
// division.
//
// Let's look back at the original problem equation:
// x^2 == N
//
// What if instead we use:
// 1/(x^2) == 1/N
// or
// x^(-2) == N^(-1)
// x^2 still equals N, but we write it as reciprocals.
//
// Now, let's break it up into 2 different equations:
// I == N^(-1)
// x^(-2) == I
//
// Convert the 2nd equation to a function with an appropriate root:
// x^(-2) - I == 0
// f(x) == x^(-2) - I
//
// Find the derivative:
// f'(x) == -2x^(-3)
//
// Newton–Raphson method Formula:
// Let x be our guess for the iteration.
// new_guess == x - f(x) / f'(x)
//
// Subsitute our functions into the Newton–Raphson method formula:
// new_guess == x - (x^(-2) - I) / (-2x^(-3))
//
// Now just simplify:
// new_guess == (x(-2x^(-3)) - (x^(-2) - I)) / (-2x^(-3))
// new_guess == (-2x^(-2) - (x^(-2) - I)) / (-2x^(-3))
// new_guess == (-2x^(-2) + -x^(-2) + I) / (-2x^(-3))
// new_guess == (-2x^(-2) - x^(-2) + I) / (-2x^(-3))
// new_guess == (-3x^(-2) + I) / (-2x^(-3))
// new_guess == (-3x^(-2) + I) / (-2(1 / x^3))
// new_guess == (-3x^(-2) + I) / (-2 / x^3)
// new_guess == (-3(1 / x^2) + I) / (-2 / x^3)
// new_guess == (-3 / x^2 + I) / (-2 / x^3)
// new_guess == (-3 / x^2 + I(x^2) / x^2) / (-2 / x^3)
// new_guess == (-3 + I(x^2) / x^2) / (-2 / x^3)
// new_guess == (-3 + I(x^2) / x^2) * (x^3 / -2)
// new_guess == (x^3)(-3 + I(x^2)) / -2x^2
// new_guess == (-3x^3 + I(x^2)(x^3)) / -2x^2
// new_guess == (-3x^3 + I(x^5)) / -2x^2
// new_guess == (-3x + I(x^3)) / -2
// new_guess == (3x - I(x^3)) / 2
// new_guess == x(3 - I(x^2)) / 2
//
// Now we have a formula that we can iterate with:
// new_guess == x(3 - I(x^2)) / 2
//
// It only requires multiplication, subtraction, and one division by 2 (computationally easy enough)
// You may notice, though, that the formula requires I (I == 1/N), not N (The square that we know
// and are trying to find the root of). So we do have to do one heavy division calculation up front
// to find it. That is okay because it doesn't have to be repeated for each iteration of the loop.
//
// Below is the implementation of this formula to find the square root.
// In the implementation:
// --guess(x) is in variable guess
// --new_guess(new_guess) is in variable new_guess
// --value_to_find_the_square_root_of(N) is in variable x
// --reciprocal_of_N(I) is in variable inverted
//
// Additional IMPORTANT Notes/Edge Cases:
// --Under certain circumstances, the guessed value can alternate when at the limits of the
// datatype's precision. For this reason, the variable old_guess was added to track the guess
// before the previous guess.
// --The Newton-Raphson interation will converge on the square root if the starting guess is less
// than the square root. However, in cases where we are trying to find the square root of a
// number less than 1, the square root will be both larger than that number and less than 1.
// In this case, we should start our guess with the number we are trying to find the square root
// of (x) instead of 1. We can not start out with a guess of 0. Doing so breaks the interation.
register double guess;
register double new_guess;
register double old_guess;
register double inverted;
register unsigned int iteration_count;
if (x < 1.0) {
guess = x;
} else {
guess = 1.0;
}
old_guess = 0.0;
inverted = 1.0 / x;
iteration_count = 0;
while (guess * guess != x && iteration_count < 10000) {
new_guess = (guess * (3.0 - (inverted * guess * guess))) / 2.0;
if (new_guess == guess || new_guess == old_guess) {
return guess;
}
old_guess = guess;
guess = new_guess;
iteration_count++;
}
if (iteration_count >= 10000) {
dprintf(2, "THIS IS A BUG!! If you see this, please report it. sqrt(value) iterations hit or exceeded 10000. Probable infinite loop broken on value == %f\n", x);
}
return guess;
}
float sqrtf(register float x) {
return (float)(sqrt((double)x));
}
<file_sep>#include "errno.h"
#include "syscalls.h"
#include "clib.h"
struct __errno_info __errno_base;
volatile struct __errno_info* __errno_base_threadmem;
volatile size_t __errno_base_threadmem_size;
volatile unsigned int __errno_base_thread_count;
mutex __errno_base_thread_mutex;
void __errno_init_errno() {
__errno_base.tid = gettid();
__errno_base.value = 0;
__errno_base_threadmem = NULL;
__errno_base_threadmem_size = 0;
__errno_base_thread_count = 0;
mutex_init(&__errno_base_thread_mutex);
return;
}
void __errno_init_thread() {
void* ptr;
ptr = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == NULL || ptr == (void*)-1) {
exit(-1);
}
__errno_base_threadmem = ptr;
__errno_base_threadmem_size = PAGE_SIZE;
__errno_base_thread_count = 0;
return;
}
void __errno_destroy_thread() {
munmap((void*)__errno_base_threadmem, __errno_base_threadmem_size);
return;
}
void __errno_remove_thread_entry(pid_t tid) {
/*
if (__errno_base_thread_mutex == 1) {
__errno_base_thread_mutex = 0;
}
*/
mutex_lock(&__errno_base_thread_mutex);
unsigned int j;
unsigned int i;
j = 0;
for (i = 0; i < __errno_base_thread_count; i++) {
if (__errno_base_threadmem[i].tid == tid) {
continue;
} else {
__errno_base_threadmem[j] = __errno_base_threadmem[i];
j++;
}
i++;
}
if (i == j) {
// This should never happen. It should not be reachable.
exit(-1);
} else {
__errno_base_thread_count--;
}
mutex_unlock(&__errno_base_thread_mutex);
return;
}
void __errno_add_thread_entry(pid_t tid) {
mutex_lock(&__errno_base_thread_mutex);
if ((__errno_base_thread_count + 1) * sizeof(struct __errno_info) > PAGE_SIZE) {
exit(-1);
}
__errno_base_threadmem[__errno_base_thread_count].tid = tid;
__errno_base_threadmem[__errno_base_thread_count].value = 0;
__errno_base_thread_count++;
mutex_unlock(&__errno_base_thread_mutex);
return;
}
signed int* __errno_location() {
pid_t tid = gettid();
if (__errno_base.tid == tid) {
return &(__errno_base.value);
}
unsigned int i = 0;
while (i < __errno_base_thread_count) {
if (__errno_base_threadmem[i].tid == tid) {
return (signed int*)(&(__errno_base_threadmem[i].value));
}
i++;
}
// This should never happen. It should not be reachable.
return NULL;
}
<file_sep>#ifndef _insertion_clib_h
#define _insertion_clib_h
#include <stddef.h>
//#include <asm/unistd.h>
//#include <asm/unistd.h>
//#include <asm/fcntl.h>
//#include <asm/stat.h>
//#include <linux/mman.h>
#include <sys/types.h>
#include <asm/signal.h>
//#include <stddef.h>
extern size_t PAGE_SIZE;
struct ethread {
volatile pid_t tid __attribute__((aligned(4)));
volatile pid_t tid2;
volatile void* stack_loc;
volatile size_t stack_size;
volatile void* retval;
};
typedef struct ethread ethread_t;
struct thread_tmp_args {
void* args;
void* (*fn)(void*);
ethread_t* ethread;
};
struct _mutex {
volatile unsigned int lock_flag __attribute__((aligned(4))); // Starts count at -1
volatile unsigned int lock_count;
volatile pid_t locking_tid;
};
typedef struct _mutex mutex;
void __init_libc();
void __destroy_libc();
signed int new_thread(ethread_t* thread, void* (*fn)(void*), void* arg);
signed int join_thread(ethread_t* thread, void** retval);
void mutex_init(mutex* mut);
void mutex_lock(mutex* mut);
void mutex_unlock(mutex* mut);
signed int sigemptyset(sigset_t *set);
signed int sigaction(signed int signum, const struct sigaction* act, struct sigaction* oldact);
pid_t wait(signed int* wstatus);
pid_t waitpid(pid_t pid, signed int* wstatus, signed int options);
void* calloc(size_t nmemb, size_t size);
void* malloc(size_t size);
void free(void* ptr);
void *memset(void *s, signed int c, size_t n);
void *memcpy(void* dest, const void* src, size_t n);
void exit(signed int code);
#endif
<file_sep>#include "clib.h"
// ASM functions
signed long printf(const char *format, ... );
signed long fprintf(signed int fd, const char *format, ... );
signed long dprintf(signed int fd, const char *format, ... );
// C functions
void print(char* str);
void itoa(register signed int number, register char* buf, register signed int buf_len, register signed int base, register signed int set_width);
signed long _dprintf(signed int fd, const char *format, unsigned long* gen_regs, long double* vec_regs, void* stack_params, unsigned long vector_regs_used);
unsigned int strlen(register const char* str);
<file_sep># Porting this project to other CPU Architectures under Linux
No MMU systems are not currently supported, otherwise, except for the exceptions
listed below, the C code should be portable. If you find something that is not
portable, please file a bug or submit a patch.
1) The syscall macros in the syscalls.h header file will need to be rewritten and
IFDEFed to support the target architecture.
2) The clone syscall changes it's order of arguments depending on CPU architecture.
This should be rewritten and IFDEFed in the clone syscall C function wrapper in
syscalls.c
3) For the:
-mutex_lock() function in clib.c and
-struct _mutex declaration
the variables:
-lock_flag,
-lock_count, and
-value
Should be the same type, and should be exactly 4 bytes in size on the target architecture.
4) The inline assembly inside functions:
-mutex_lock() in clib.c and
-mutex_unlock()
should be rewritten and IFDEFed to the target architecture's
equivalent of atomic instructions
5) The bootstrap _start replacement program will have to be rewriten and conditionally
included by architecture. This is the program currently called "caller.s" and is the custom
entry point for the program, replacing "_start" with "my_entry_pt".
6) For architectures under which the stack grows up. You will have to also rewrite and
IFDEF the C code which handles Thread creation, argument passing, and destruction in
"clib.c".
Optional and on my TODO list:
Assembly micro-optimization with C fallback.
<file_sep>#include "syscalls.h"
#include "errno.h"
signed int read(signed int fd, const void* buf, size_t count) {
register signed int retval;
SYSCALL3_R(retval, __NR_read, fd, buf, count);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int write(signed int fd, const void* buf, size_t count) {
register signed int retval;
SYSCALL3_R(retval, __NR_write, fd, buf, count);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int open(const char* pathname, unsigned int flags, mode_t mode) {
register signed int retval;
SYSCALL3_R(retval, __NR_open, pathname, flags, mode);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int close(signed int fd) {
register signed int retval;
SYSCALL1_R(retval, __NR_close, fd);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
void _exit(signed int status) {
SYSCALL1_V(__NR_exit, status);
return;
}
void exit_group(signed int status) {
SYSCALL1_V(__NR_exit_group, status);
return;
}
void* mmap(void *addr, size_t length, unsigned int prot, unsigned int flags, signed int fd, off_t offset) {
register void* retval;
SYSCALL6_R(retval, __NR_mmap, addr, length, prot, flags, fd, offset);
switch (((signed long)retval)) {
case -EACCES:
errno = -((signed long)retval);
break;
case -EAGAIN:
errno = -((signed long)retval);
break;
case -EBADF:
errno = -((signed long)retval);
break;
case -EEXIST:
errno = -((signed long)retval);
break;
case -EINVAL:
errno = -((signed long)retval);
break;
case -ENFILE:
errno = -((signed long)retval);
break;
case -ENODEV:
errno = -((signed long)retval);
break;
case -ENOMEM:
errno = -((signed long)retval);
break;
case -EOVERFLOW:
errno = -((signed long)retval);
break;
case -EPERM:
errno = -((signed long)retval);
break;
case -ETXTBSY:
errno = -((signed long)retval);
break;
default:
return retval;
}
return (void*)-1;
}
signed int munmap(void *addr, size_t length) {
register signed int retval;
SYSCALL2_R(retval, __NR_munmap, addr, length);
switch (retval) {
case -EACCES:
errno = -retval;
break;
case -EAGAIN:
errno = -retval;
break;
case -EBADF:
errno = -retval;
break;
case -EEXIST:
errno = -retval;
break;
case -EINVAL:
errno = -retval;
break;
case -ENFILE:
errno = -retval;
break;
case -ENODEV:
errno = -retval;
break;
case -ENOMEM:
errno = -retval;
break;
case -EOVERFLOW:
errno = -retval;
break;
case -EPERM:
errno = -retval;
break;
case -ETXTBSY:
errno = -retval;
break;
default:
return retval;
}
return -1;
}
pid_t gettid() {
register pid_t retval;
SYSCALL0_R(retval, __NR_gettid);
return retval;
}
pid_t clone(signed int (*fn)(void *), void* stack, unsigned long flags, void* arg, signed int* parent_tid, unsigned long tls, signed int* child_tid) {
register pid_t retval;
// Note: This syscall's argument order changes depending on architecture.
// Don't forget to update this with #ifdefs when porting.
SYSCALL5_R(retval, __NR_clone, flags, stack, parent_tid, child_tid, tls);
if (retval > 0) {
// Parent
return retval;
} else if (retval == 0) {
// Child
retval = fn(arg);
_exit(retval);
} else {
// Error
errno = -retval;
}
return -1;
}
pid_t fork() {
register pid_t retval;
SYSCALL0_R(retval, __NR_fork);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
pid_t wait4(pid_t pid, signed int* wstatus, signed int options, struct rusage* rusage) {
register pid_t retval;
SYSCALL4_R(retval, __NR_wait4, pid, wstatus, options, rusage);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int ioctl(signed int fd, unsigned long request, void* argp) {
register signed int retval;
SYSCALL3_R(retval, __NR_ioctl, fd, request, argp);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int rt_sigaction(signed int signum, const struct sigaction* act, struct sigaction* oldact, size_t sigsetsize) {
register signed int retval;
SYSCALL4_R(retval, __NR_rt_sigaction, signum, act, oldact, sigsetsize);
if (retval < 0) {
errno = -retval;
retval = -1;
}
return retval;
}
signed int nanosleep(const struct timespec* req, struct timespec* rem) {
register signed int retval;
SYSCALL2_R(retval, __NR_nanosleep, req, rem);
if (retval < 0) {
errno = -retval;
return -1;
}
return 0;
}
signed int stat(const char *path, struct stat* statbuf) {
register signed int retval;
SYSCALL2_R(retval, __NR_stat, path, statbuf);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
signed int fstat(signed int fd, struct stat* statbuf) {
register signed int retval;
SYSCALL2_R(retval, __NR_fstat, fd, statbuf);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
signed int futex(signed int *uaddr, unsigned int futex_op, signed int val, const struct timespec *timeout, signed int *uaddr2, signed int val3) {
register signed int retval;
SYSCALL6_R(retval, __NR_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
<file_sep>#ifndef _insertion_errno_h
#define _insertion_errno_h
#include "clib.h"
#include <stddef.h>
#include <sys/types.h>
#define errno (*(__errno_location()))
struct __errno_info {
signed int value;
pid_t tid;
};
extern struct __errno_info __errno_base;
extern volatile struct __errno_info* __errno_base_threadmem;
extern volatile size_t __errno_base_threadmem_size;
extern volatile unsigned int __errno_base_thread_count;
extern mutex __errno_base_thread_mutex;
void __errno_init_errno();
void __errno_init_thread();
void __errno_destroy_thread();
void __errno_remove_thread_entry(pid_t tid);
void __errno_add_thread_entry(pid_t tid);
signed int* __errno_location();
#endif
<file_sep>#include "clib.h"
#include "clib_string.h"
#include "clib_math.h"
#include "syscalls.h"
float rtod(float r);
float dtor(float r);
signed int main(unsigned int argc, char* argv[], char* envp[]) {
//dprintf(2, "TraceA %d %f\n", -10, -0.46455);
//return 0;
/*
long double D = 10000000000.3;
double d = 10000000000.3;
float f = 10000000000.3;
dprintf(1, "aa%Lfbb\n", D);
dprintf(1, "cc%fdd\n", d);
dprintf(1, "ee%fff\n", f);
dprintf(1, "gg%dhh\n", 10);
dprintf(1, "ii%sjj\n", "Hello, World!");
fprintf(1, "aa%Lfbb\n", D);
fprintf(1, "cc%fdd\n", d);
fprintf(1, "ee%fff\n", f);
fprintf(1, "gg%dhh\n", 10);
fprintf(1, "ii%sjj\n", "Hello, World!");
printf("aa%Lfbb\n", D);
printf("cc%fdd\n", d);
printf("ee%fff\n", f);
printf("gg%dhh\n", 10);
printf("ii%sjj\n", "Hello, World!");
*/
/*
float f0 = 20.0;
printf("f0: %f, sqrtf(f0): %f, sqrt(f0): %f\n", f0, sqrtf(f0), sqrt(f0));
double d0 = 20.0;
printf("f0: %f, sqrtf(f0): %f, sqrt(f0): %f\n", d0, sqrtf(d0), sqrt(d0));
d0 = f0;
printf("f0: %f, sqrtf(f0): %f, sqrt(f0): %f\n", d0, sqrtf(d0), sqrt(d0));
return 0;
*/
float deg_angle = -720.0;
while (deg_angle <= 721.0) {
printf("deg_angle: %f, ", deg_angle);
printf("rad_angle: %f, ", dtor(deg_angle));
printf("cosf: %f, ", cosf(dtor(deg_angle)));
printf("cos: %f\n", cos(dtor(deg_angle)));
deg_angle += 15.0;
}
printf("\n");
double num;
double res;
num = 1.0;
res = sqrt(num);
printf("sqrt(%f): %f\n", num, res);
num = 0.5;
res = sqrt(num);
printf("sqrt(%f): %f\n", num, res);
num = 0.25;
res = sqrt(num);
printf("sqrt(%f): %f\n", num, res);
num = 0.125;
res = sqrt(num);
printf("sqrt(%f): %f\n", num, res);
num = 0.0;
res = sqrt(num);
printf("sqrt(%f): %f\n", num, res);
return 0;
}
float rtod(float r) {
return (r * 180.0) / M_PI;
}
float dtor(float d) {
return (d * M_PI) / 180.0;
}
<file_sep>CC := gcc
CFLAGS := -Wall -Wextra -std=c99 -O2 -march=native -m64 -ffreestanding -nostdlib -nostartfiles -g
LDFLAGS := -e my_entry_pt
FILES := clib.o syscalls.o caller.o callee.o errno.o clib_math.o clib_string.o clib_string_asm.o
.PHONY: all rebuild clean
all: static-program dynamic-program
rebuild: clean all
clean:
rm -f static-program dynamic-program *.o
%.o: %.c
$(CC) $(CFLAGS) $^ -c -o $@
%.o: %.s
$(CC) $(CFLAGS) $^ -c -o $@
dynamic-program: $(FILES)
$(CC) -dynamic $(CFLAGS) $^ $(LDFLAGS) -o $@
static-program: $(FILES)
$(CC) -static $(CFLAGS) $^ $(LDFLAGS) -o $@
<file_sep>#if !defined(__linux__) || !defined(__x86_64__)
#error "This only works on Linux on x86-64."
#endif
#ifndef _insertion_syscalls_h
#define _insertion_syscalls_h
#include <sys/types.h>
#include <linux/time.h>
#include <linux/mman.h>
#include <linux/types.h>
#include <linux/resource.h>
#include <stddef.h>
#include <asm/unistd.h>
#include <asm/fcntl.h>
#include <asm/stat.h>
#include <asm/errno.h>
#include <asm/signal.h>
#define SYSCALL0_V(callnum) \
{ __asm__ __volatile__ ("syscall\n" : : "a" (callnum) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL1_V(callnum, arg1) \
{ __asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL2_V(callnum, arg1, arg2) \
{ __asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1), "S" (arg2) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL3_V(callnum, arg1, arg2, arg3) \
{ __asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL4_V(callnum, arg1, arg2, arg3, arg4) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
__asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL5_V(callnum, arg1, arg2, arg3, arg4, arg5) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
register unsigned long __r8 __asm__("r8") = (unsigned long)arg5; \
__asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10), "r" (__r8) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL6_V(callnum, arg1, arg2, arg3, arg4, arg5, arg6) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
register unsigned long __r8 __asm__("r8") = (unsigned long)arg5; \
register unsigned long __r9 __asm__("r9") = (unsigned long)arg6; \
__asm__ __volatile__ ("syscall\n" : : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10), "r" (__r8), "r" (__r9) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL0_R(retval, callnum) \
{ __asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL1_R(retval, callnum, arg1) \
{ __asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL2_R(retval, callnum, arg1, arg2) \
{ __asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1), "S" (arg2) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL3_R(retval, callnum, arg1, arg2, arg3) \
{ __asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL4_R(retval, callnum, arg1, arg2, arg3, arg4) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
__asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL5_R(retval, callnum, arg1, arg2, arg3, arg4, arg5) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
register unsigned long __r8 __asm__("r8") = (unsigned long)arg5; \
__asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10), "r" (__r8) : "rcx", "r11", "memory", "cc"); }
#define SYSCALL6_R(retval, callnum, arg1, arg2, arg3, arg4, arg5, arg6) \
{ register unsigned long __r10 __asm__("r10") = (unsigned long)arg4; \
register unsigned long __r8 __asm__("r8") = (unsigned long)arg5; \
register unsigned long __r9 __asm__("r9") = (unsigned long)arg6; \
__asm__ __volatile__ ("syscall\n" : "=a" (retval) : "a" (callnum), "D" (arg1), "S" (arg2), "d" (arg3), "r" (__r10), "r" (__r8), "r" (__r9) : "rcx", "r11", "memory", "cc"); }
signed int read(signed int fd, const void* buf, size_t count);
signed int write(signed int fd, const void* buf, size_t count);
signed int open(const char* pathname, unsigned int flags, mode_t mode);
signed int close(signed int fd);
void _exit(signed int status);
void exit_group(signed int status);
void* mmap(void *addr, size_t length, unsigned int prot, unsigned int flags, signed int fd, off_t offset);
signed int munmap(void *addr, size_t length);
pid_t gettid();
pid_t clone(signed int (*fn)(void*), void* stack, unsigned long flags, void* arg, signed int* parent_tid, unsigned long tls, signed int* child_tid);
pid_t fork();
pid_t wait4(pid_t pid, signed int* wstatus, signed int options, struct rusage* rusage);
signed int ioctl(signed int fd, unsigned long request, void* argp);
signed int rt_sigaction(signed int signum, const struct sigaction* act, struct sigaction* oldact, size_t sigsetsize);
signed int nanosleep(const struct timespec* req, struct timespec* rem);
signed int stat(const char *path, struct stat* statbuf);
signed int fstat(signed int fd, struct stat* statbuf);
signed int futex(signed int *uaddr, unsigned int futex_op, signed int val, const struct timespec *timeout, signed int *uaddr2, signed int val3);
#endif
<file_sep>#include "clib.h"
#include "syscalls.h"
#include "errno.h"
#include <linux/sched.h>
#include <linux/futex.h>
size_t PAGE_SIZE;
void __init_libc() {
__errno_init_errno();
struct stat statbuf;
if (stat("/dev/mem", &statbuf) < 0) {
exit(-1);
}
PAGE_SIZE = statbuf.st_blksize;
__errno_init_thread();
return;
}
void __destroy_libc() {
/*
Clean up dynamic memory mapping for thread errno locations.
I'm not sure this is really safe unless I halt or kill all threads first. This probably should
have already happened, but if there are rouge threads, this will probably induce segfaults just
prior to program exit as any rouge threads attempt to reference errno. Such a bug would be very
rare since it requires such specific conditions to manifest and would be a nightmare to debug.
The kernel will clean up the mapping for us anyway after we exit_group(). We can munmap()
safely if(__errno_base_thread_count == 0);.
*/
if (__errno_base_thread_count == 0) {
__errno_destroy_thread();
}
return;
}
signed int __new_thread(void* arg) {
// Retrieve thread information
struct thread_tmp_args* args;
args = arg;
// Add errno location for this thread
__errno_add_thread_entry(args->ethread->tid);
// Call the function
void* (*fn)(void*);
void *retptr;
fn = args->fn;
retptr = fn(args->args);
args->ethread->retval = retptr;
// Exit the thread
_exit(0);
return 0;
}
signed int new_thread(ethread_t* thread, void* (*fn)(void*), void* arg) {
pid_t retval;
struct thread_tmp_args args;
args.args = arg;
args.fn = fn;
args.ethread = thread;
thread->retval = 0;
thread->tid = 0;
thread->stack_size = 8192000 + sizeof(struct thread_tmp_args);
void* ptr = mmap(0, thread->stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
if (ptr == (void*)-1) {
return -1;
}
thread->stack_loc = ptr;
ptr = (ptr + thread->stack_size) - sizeof(struct thread_tmp_args);
*((struct thread_tmp_args*)ptr) = args;
retval = clone(__new_thread, ptr, CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_PARENT | CLONE_PARENT_SETTID | CLONE_FILES | CLONE_FS | CLONE_CHILD_CLEARTID, ptr, (void*)(&(thread->tid)), 0, (void*)(&(thread->tid)));
if (retval == -1) {
return -1;
}
thread->tid2 = retval;
return 0;
}
signed int join_thread(ethread_t* thread, void** retval) {
// TODO: Implement better error handling
pid_t tid = thread->tid;
if (tid != 0) {
futex((void*)(&(thread->tid)), FUTEX_WAIT, tid, NULL, 0, 0);
}
if (thread->stack_size != 0) {
__errno_remove_thread_entry(thread->tid2);
munmap((void*)thread->stack_loc, thread->stack_size);
thread->stack_loc = 0;
thread->stack_size = 0;
thread->tid = 0;
if (retval != NULL) {
*retval = (void*)(thread->retval);
}
}
return 0;
}
void mutex_init(mutex* mut) {
mut->lock_flag = 1;
mut->lock_count = 0;
mut->locking_tid = 0;
}
void mutex_lock(mutex* mut) {
unsigned int is_non_zero;
unsigned int value;
__asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \
: /* Output */ \
: /* Input */ "c" (&(mut->lock_count)) \
: /* Clobbers */ "cc" );
// Atomically decrement "mul->lock_flag" and check Zero-Flag status.
__asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \
"LOCK decl (%%rcx) \n" \
"setnz %%dl \n" \
: /* Output */ "=d" (is_non_zero) \
: /* Input */ "c" (&(mut->lock_flag)) \
: /* Clobbers */ "cc" );
value = mut->lock_flag;
while(is_non_zero == 1) {
if (value == 0) {
// Catch the race condition.
//
// In this case, the lock has been released(And the value
// of mut->lock_flag changed) between our atomic instruction
// on the value in memory and the retrieval of the value
// itself from memory. Since the value of "mut->lock_flag" is
// now "0", we can simply just assume ownership of the lock and
// therefore, we don't need to block after all. So we break out
// of the loop.
break;
}
// Match the variable "value" to the expected value
//of "mut->lock_flag" in memory
value++;
// Since we can't actually take ownership of the lock,
// atomically increment the "mul->lock_flag" back up
__asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \
: /* Output */ \
: /* Input */ "c" (&(mut->lock_flag)) \
: /* Clobbers */ "cc" );
// Wait for "mul->lock_flag" to change
// This will not block if "value" does not match "mul->lock_flag"
// In the event if this, we simply continue the loop to recompute what
// has changed outside of this thread and retry.
futex((void*)(&(mut->lock_flag)), FUTEX_WAIT, value, NULL, 0, 0);
// Atomically decrement the lock flag and check Zero-Flag status.
__asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \
"LOCK decl (%%rcx) \n" \
"setnz %%dl \n" \
: /* Output */ "=d" (is_non_zero) \
: /* Input */ "c" (&(mut->lock_flag)) \
: /* Clobbers */ "cc" );
value = mut->lock_flag;
}
mut->locking_tid = gettid();
return;
}
void mutex_unlock(mutex* mut) {
unsigned int is_non_zero;
if (mut->locking_tid != gettid()) {
return;
}
mut->locking_tid = 0;
__asm__ __volatile__ ( "LOCK incl (%%rcx) \n" \
: /* Output */ \
: /* Input */ "c" (&(mut->lock_flag)) \
: /* Clobbers */ "cc" );
__asm__ __volatile__ ( "xor %%rdx, %%rdx \n" \
"LOCK decl (%%rcx) \n" \
"setnz %%dl \n" \
: /* Output */ "=d" (is_non_zero) \
: /* Input */ "c" (&(mut->lock_count)) \
: /* Clobbers */ "cc" );
if (is_non_zero == 1) {
futex((void*)(&(mut->lock_flag)), FUTEX_WAKE, 1, NULL, 0, 0);
}
return;
}
signed int sigemptyset(sigset_t *set) {
*set = 0;
return 0;
}
signed int sigaction(signed int signum, const struct sigaction* act, struct sigaction* oldact) {
return rt_sigaction(signum, act, oldact, sizeof(sigset_t));
}
pid_t wait(signed int* wstatus) {
return waitpid(-1, wstatus, 0);
}
pid_t waitpid(pid_t pid, signed int* wstatus, signed int options) {
return wait4(pid, wstatus, options, NULL);
}
void* calloc(size_t nmemb, size_t size) {
if (nmemb == 0 || size == 0) {
return 0;
}
size_t max_val = ~0;
if (max_val / size < nmemb || max_val / nmemb < size) {
return 0;
}
return malloc(nmemb * size);
}
void* malloc(size_t size) {
if (size == 0) {
return NULL;
}
register void* retval;
retval = mmap(0, size + sizeof(size_t), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*((size_t*)retval) = size + sizeof(size_t);
return retval + sizeof(size_t);
}
void free(void* ptr) {
if (ptr == NULL) {
return;
}
//signed int retval;
ptr -= sizeof(size_t);
/*retval = */munmap(ptr, *((size_t*)ptr));
return;
}
void *memset(void *s, signed int c, size_t n) {
while (n > 0) {
n--;
((unsigned char*)s)[n] = (unsigned char)(c & 0xFF);
}
return s;
}
void *memcpy(void* dest, const void* src, size_t n) {
while (n > 0) {
n--;
((unsigned char*)dest)[n] = ((unsigned char*)src)[n];
}
return dest;
}
void exit(signed int code) {
exit_group(code);
}
<file_sep>#include "clib_string.h"
#include "syscalls.h"
void print(char *str) {
if (str == 0) {
return;
}
write(1, str, strlen(str));
return;
}
void itoa(register signed int number, register char* buf, register signed int buf_len, register signed int base, register signed int set_width) {
register signed long int num;
num = number;
if(base < 0) {
base = -base;
if(number < 0) {
num = -num;
}
}
if(base > 16 || base < 2){
return;
}
if(buf_len < 2){
return;
}
if(set_width != 0){
if (set_width < 0 || num >= 0) {
if (buf_len <= set_width) {
return;
}
} else {
if (buf_len <= set_width + 1) {
return;
}
}
}
//Check if zero since this will fail to loop and can be easily handled now
register unsigned char i_2;
if(num == 0){
if (set_width != 0) {
if (set_width < 0) {
set_width = -set_width;
}
i_2 = 0;
while (i_2 < set_width) {
buf[i_2] = '0';
i_2++;
}
buf[i_2] = 0;
return;
} else {
buf[0] = '0';
buf[1] = 0;
return;
}
}else{
register unsigned char i_then_length;
i_then_length = 0;
i_2 = 0;
//i_then_length is now an index
//Append "-" character for negatives
if(num < 0){
if (set_width < 0) {
set_width++;
}
num = -num;
buf[0] = '-';
buf_len--;
buf++;
}
if (set_width < 0) {
set_width = -set_width;
}
//Find Characters
while(num > 0 && i_then_length < buf_len){
i_2 = num % base;
if(i_2 < 10){
buf[(unsigned int)i_then_length] = '0' + i_2;
}else{
buf[(unsigned int)i_then_length] = '7' + i_2;
}
num /= base;
i_then_length++;
}
while (i_then_length < set_width && i_then_length < buf_len) {
buf[(unsigned int)i_then_length] = '0';
i_then_length++;
}
//i_then_length is now a length count for char array
//Loop to fix character order
i_2 = 0;
register char tmpchar;
while(i_2 < (i_then_length / 2) && i_2 < buf_len){
tmpchar = buf[(int)((i_then_length - i_2) - 1)];
buf[(int)((i_then_length - i_2) - 1)] = buf[(unsigned int)i_2];
buf[(unsigned int)i_2] = tmpchar;
i_2++;
}
if(i_then_length < buf_len){
buf[(unsigned int)i_then_length] = 0;
}else{
buf[(unsigned int)(i_then_length - 1)] = 0;
}
}
return;
}
signed long _dprintf(signed int fd, const char *format, unsigned long* gen_regs, long double* vec_regs, void* stack_params, unsigned long vector_regs_used) {
// Parse String
//void* stack_ptr = stack_params;
char buff[50];
const char* s = format;
unsigned int int_count = 0;
unsigned int float_count = 0;
//unsigned int long_double_count = 0;
unsigned int i = 0;
unsigned int mode = 0;
unsigned int alt_form = 0;
unsigned int zero_padding = 0;
unsigned int signage = 0;
unsigned int length = 0;
unsigned int precision = 0;
while (s[i] != 0) {
if (mode == 1 || mode == 2) {
if (s[i] == '%') {
mode = 0;
write(fd, "%", 1);
s += i + 1;
i = -1;
} else if (s[i] == '.') {
alt_form |= 4;
} else if (s[i] == '-') {
zero_padding |= 2;
} else if (s[i] == '+') {
signage |= 2;
} else if (s[i] == ' ') {
signage |= 1;
} else if (s[i] == '0') {
if (alt_form & 2) {
if (alt_form & 4) {
precision *= 10;
} else {
length *= 10;
}
} else {
zero_padding |= 1;
}
} else if (s[i] > '0' && s[i] <= '9') {
alt_form |= 2;
if (alt_form & 4) {
precision *= 10;
precision += s[i] - '0';
} else {
length *= 10;
length += s[i] - '0';
}
} else if (s[i] == '#') {
alt_form |= 1;
alt_form &= ~2;
} else if (s[i] == 'L') {
mode = 2;
alt_form &= ~2;
} else if (s[i] == 's') {
char* pstr;
if (int_count < 4) {
pstr = (char*)(*(gen_regs + int_count));
} else {
pstr = (char*)stack_params;
stack_params += sizeof(char*);
}
print(pstr);
s += i + 1;
i = -1;
int_count++;
mode = 0;
} else if (s[i] == 'd' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'x' || s[i] == 'X' || s[i] == 'c' || s[i] == 'p' || s[i] == 'n' || s[i] == 'm') {
signed long int tmp_int;
if (int_count < 4) {
tmp_int = *(gen_regs + int_count);
} else {
tmp_int = *((signed long int*)stack_params);
stack_params += sizeof(signed long int);
}
itoa(tmp_int, buff, 50, 10, 0);
write(fd, buff, strlen(buff));
s += i + 1;
i = -1;
int_count++;
mode = 0;
} else if (s[i] == 'e' || s[i] == 'E' || s[i] == 'f' || s[i] == 'F' || s[i] == 'g' || s[i] == 'G' || s[i] == 'a' || s[i] == 'A') {
long double tmp_ldouble;
if (mode == 2) {
// Long Double
if (float_count < vector_regs_used && float_count < 8) {
tmp_ldouble = *(vec_regs + float_count);
} else {
tmp_ldouble = *((long double*)stack_params);
stack_params += sizeof(long double);
}
//itoa(ftoi(tmp_ldouble), buff, 100, 10, 0);
} else {
// Double or Float
double tmp_double;
if (float_count < vector_regs_used && float_count < 8) {
//dprintf(1, "TraceA i: (%d)\n", float_count);
tmp_double = *((double*)(vec_regs + float_count));
} else {
tmp_double = *((double*)stack_params);
stack_params += sizeof(long double);
}
tmp_ldouble = tmp_double;
//itoa(ftoi(tmp_double), buff, 100, 10, 0);
}
if (tmp_ldouble < 0.0) {
tmp_ldouble = -tmp_ldouble;
write(1, "-", 1);
}
unsigned int k;
k = 1;
while (tmp_ldouble >= 1000000000.0) {
tmp_ldouble /= 1000000000.0;
k++;
}
unsigned int v;
unsigned int j;
j = 0;
while (j < k) {
v = tmp_ldouble;
tmp_ldouble -= v;
if (j == 0) {
itoa(v, buff, 50, 10, 0);
} else {
itoa(v, buff, 50, 10, 9);
}
write(1, buff, strlen(buff));
tmp_ldouble *= 1000000000.0;
j++;
}
/*
v = tmp_ldouble;
tmp_ldouble -= v;
if (j) {
j = 9;
}
itoa(v, buff, 50, 10, j);
write(1, buff, strlen(buff));
*/
// Precision
//tmp_ldouble *= 1000000000.0;
v = tmp_ldouble;
//tmp_ldouble -= v;
itoa(v, buff, 50, 10, 9);
write(1, ".", 1);
write(1, buff, strlen(buff) - 3);
//char* testing_str = "[DOUBLE_VALUE_HERE]";
//itoa(ftoi(2000000000.0), buff, 100, 10, 0);
//write(fd, testing_str, strlen(testing_str));
//write(fd, buff, strlen(buff));
s += i + 1;
i = -1;
float_count++;
/*
if (mode == 1) {
float_count++;
} else {
long_double_count++;
}
*/
mode = 0;
}
} else {
if (s[i] == '%') {
write(fd, s, i);
s += i + 1;
i = -1;
mode = 1;
alt_form = 0;
zero_padding = 0;
signage = 0;
length = 0;
precision = 0;
}
}
i++;
}
if (i > 0) {
write(fd, s, i);
}
return 0;
}
unsigned int strlen(register const char* str) {
if (str == 0) {
return 0;
}
register unsigned int i = 0;
while (str[i] != 0) {
i++;
}
return i;
}<file_sep># near_the_metal
Experimenting with ASM and C
Currently, this only works under Linux on x86-64 CPU Architecture.
The following are also requirements:
-None
TODO:
-Clean up custom itoa() implementation
-Create and run tests to verify the correctness of custom itoa() implementation
-Assembly micro-optimization with C fallback.
-printf, fprintf, and dprintf replacements are not complete, but probably good enough for now. These will need to be built out as needed.
-Update porting guide to include clib_supp.s and print variants
-Add dynamic expansion for thread errno location storage
-Implement realloc
-Make malloc, calloc, and free smart with their memory management
| 9c3e6a0944eb766d3a5cc5c16fd0a100167fba24 | [
"Markdown",
"C",
"Makefile"
] | 13 | C | echelonxray/near_the_metal | 9ffb7704339f56a9e022a7c69f2e91fee5ef0425 | baeb78b8f7089887f95f7e470e994d2b530463bb |
refs/heads/master | <repo_name>Moloq/ML-assignments<file_sep>/a3/a3.py
from grasp import core
from grasp import reader
import pandas as pd
import sklearn
df = reader.read("data/credit-data.csv")
obj = core.Grasp(df)
obj.data = df
obj.target_var = 'SeriousDlqin2yrs'
obj.data = obj.data[['NumberOfTimes90DaysLate','age','NumberOfOpenCreditLinesAndLoans', 'SeriousDlqin2yrs']]
test_grid = {
'RF':{'n_estimators': [1], 'max_depth': [1], 'max_features': ['sqrt'],'min_samples_split': [10]},
'LR': { 'penalty': ['l1'], 'C': [0.01]},
'SGD': { 'loss': ['perceptron'], 'penalty': ['l2']},
'ET': { 'n_estimators': [1], 'criterion' : ['gini'] ,'max_depth': [1], 'max_features': ['sqrt'],'min_samples_split': [10]},
'AB': { 'algorithm': ['SAMME'], 'n_estimators': [1]},
'GB': {'n_estimators': [1], 'learning_rate' : [0.1],'subsample' : [0.5], 'max_depth': [1]},
'NB' : {},
'DT': {'criterion': ['gini'], 'max_depth': [1], 'max_features': ['sqrt'],'min_samples_split': [10]},
'SVM' :{'C' :[0.01],'kernel':['linear']},
'KNN' :{'n_neighbors': [5],'weights': ['uniform'],'algorithm': ['auto']}
}
obj.split_test_train(0.8, 'SeriousDlqin2yrs')
obj.gridsearch(test_grid)
<file_sep>/a1/data/downloader.py
import requests
import numpy as np
def getFIPSforLocation(latitude, longitude):
try:
FTC_API_format = "http://data.fcc.gov/api/block/find?format=json&latitude={latitude}&longitude={longitude}"
return requests.get(FTC_API_format.format(longitude=longitude, latitude=latitude)).json()['Block']['FIPS'][:12]
except:
return np.nan
buildings_df.dropna(subset=['latitude'], inplace=True)
buildings_df.dropna(subset=['longitude'], inplace=True)
buildings_df['FIPS']=buildings_df.apply(lambda row: getFIPSforLocation(row['latitude'],row['longitude']), axis=1)
buildings_df.to_json("data/sanitation_df_with_fips.json")
sanitation_df.dropna(subset=['latitude'], inplace=True)
sanitation_df.dropna(subset=['longitude'], inplace=True)
sanitation_df['FIPS']=sanitation_df.apply(lambda row: getFIPSforLocation(row['latitude'],row['longitude']), axis=1)
sanitation_df.to_json("data/sanitation_df_with_fips.json")<file_sep>/README.md
# ML-assignments
Assignments for UChicago Machine Learning for Public Policy class
<file_sep>/a2/synapses/reader.py
# -*- coding: utf-8 -*-
"""This module includes functions for reading data from different types of sources.
Attributes:
None
Todo:
Add support for SQL databases and multiple datatypes.
"""
import pandas as pd
def read_csv(path, *args, **kwargs):
""" Reads a csv file"""
dataframe = pd.read_csv(path, *args, **kwargs)
return dataframe
def read_local_json(filepath):
""" Reads a json file"""
raise NotImplementedError
def read(filename):
""" Reads any type of file, infers which pandas reader to use based on extension"""
raise NotImplementedError
<file_sep>/a3/grasp/__init__.py
"""Module with different submodules for different parts of a basic Machine Learning pipeline.
Mostly a wrapper around Pandas, sklearn and plotting modules.
Dependencies:
Pandas 0.19+
SKLearn
"""
from grasp.core import Grasp
__all__ = ['reader', 'cleaner', 'core']
<file_sep>/a3/grasp/explorer.py
"""Helper functions to describe the data in a pandas Dataframe.
Todo:
Everything
"""
import pandas
import seaborn
def plot_correlation_heatmap(dataframe):
correlations = dataframe.corr()
sns.heatmap(corr)
<file_sep>/a3/grasp/cleaner.py
"""Functions to deal with basic data pre-processing and cleaning on a pandas Dataframe.
Todo:
Convince the python community to move towards overloading and polymorphism
"""
import pandas
def fill_in_column_using_mean(dataframe, column_list, inplace=True, **kwargs):
""" Fills in a column in a Pandas dataframe using the mean of the existing values"""
if not inplace:
dataframe = dataframe.copy()
for column in column_list:
fill_in_column_using_value(dataframe, column, dataframe[column].mean(), kwargs)
#dataframe[column].fillna(dataframe[column].mean(), inplace=True, *args)
return dataframe
def fill_in_column_using_median(dataframe, column_list, inplace=True, **kwargs):
""" Fills in a column in a Pandas dataframe using the mean of the existing values"""
if not inplace:
dataframe = dataframe.copy()
for column in column_list:
fill_in_column_using_value(dataframe, column, dataframe[column].median(), kwargs)
#dataframe[column].fillna(dataframe[column].mean(), inplace=True, *args)
return dataframe
def fill_in_column_using_value(dataframe, column, value, **kwargs)
dataframe[column].fillna(value, inplace=True, *kwargs)
def cap_values(dataframe, column, value):
dataframe[column] = dataframe[column].where(dataframe[column] <= value, value)
def drop_all_na(dataframe, *args):
raise NotImplementedError
def create_dummy_for_missing_data(dataframe, column_list=None, prefix='missing_'):
"""bla
"""
if column_list is None:
column_list = dataframe.columns.values.tolist()
for col in column_list:
# if dataframe[col].count() < len(dataframe)
if dataframe[col].isnull().any():
missing_col_name = prefix + col
dataframe[missing_col_name] = dataframe[col].isnull()
<file_sep>/a3/grasp/reader.py
# -*- coding: utf-8 -*-
"""This module includes functions for reading data from different types of sources.
Attributes:
None
Todo:
Add support for SQL databases and multiple datatypes.
"""
import pandas as pd
from os import path
def read_csv(path, *args, **kwargs):
""" Reads a csv file"""
dataframe = pd.read_csv(path, *args, **kwargs)
return dataframe
def read_local_json(filepath):
""" Reads a json file"""
raise NotImplementedError
def read(filepath, *args, **kwargs):
""" Reads any type of file, infers which pandas reader to use based on extension"""
extension = path.splitext(filepath)[1].lower()
if extension == '.csv':
data = pd.read_csv(filepath, *args, **kwargs)
elif extension == '.json':
data = pd.read_json(filepath, *args, **kwargs)
return data
<file_sep>/a2/synapses/__init__.py
"""Module with different submodules for different parts of a basic Machine Learning pipeline.
Dependencies:
Pandas 0.19+
"""
__all__ = ['reader', 'cleaner']
<file_sep>/a2/synapses/cleaner.py
"""Functions to deal with basic data pre-processing and cleaning on a pandas Dataframe.
Todo:
Convince the python community to move towards overloading and polymorphism
"""
import pandas
def fill_in_column_using_mean(dataframe, column_list, inplace=True, *args):
""" Fills in a column in a Pandas dataframe using the mean of the existing values"""
if not inplace:
dataframe = dataframe.copy()
for column in column_list:
dataframe[column].fillna(dataframe[column].mean(), inplace=True, *args)
def cap_values(dataframe, column, value):
dataframe[column] = dataframe[column].where(dataframe[column] <= value, value)
def drop_all_na(dataframe, *args):
raise NotImplementedError
<file_sep>/a3/grasp/manipulator.py
"""Helper function submodule with functions to generate features from existing dataframe
"""
import pandas
def continuous_to_bins(dataframe, num_bins, column_list, new_columns_list=None, \
by_quantile=True, inplace=True):
"""For each specified column, create new columns that place values into specified number of
bins, by value range or by quantile.
"""
if inplace is False:
dataframe = dataframe.copy()
if new_columns_list is None:
new_columns_list = [col + '_bin' for col in column_list]
for col, new_col in zip(column_list, new_columns_list):
if by_quantile:
dataframe[new_col] = pandas.qcut(dataframe[col], num_bins)
else:
dataframe[new_col] = pandas.cut(dataframe[col], num_bins)
return dataframe
def category_to_dummies(dataframe, column_list, inplace=True):
"""For each column in column_list, create new dummy variable columns for each of the categories
"""
return pandas.get_dummies(dataframe, columns=column_list)
<file_sep>/a2/synapses/classifier.py
"""
"""
from sklearn.linear_model import LogisticRegression
def get_trained_model(dataframe, features, target, method='logistic'):
""" Returns a sklearn model object from the selected dataframe, features and target column
that uses the specified method.
Currently only supports logistic regression, the default.
"""
if method == 'logistic':
model = LogisticRegression()
model.fit(dataframe[features], dataframe[target])
return model
else:
raise NotImplementedError
def predict(model, dataframe, features, target_name='score', inplace=True):
""" Adds a column 'score' (or target_name) with the predicted value for each row
according tot he prediction made by the model.
"""
if inplace is False:
dataframe = dataframe.copy()
dataframe[target_name] = model.predict(dataframe[features])
return dataframe
def get_accuracy(dataframe, actual, predicted):
""" """
raise NotImplementedError<file_sep>/a3/grasp/core.py
""" Core definitions and imports
"""
import pandas as pd
from os import path
from sklearn import preprocessing, cross_validation, svm, metrics, tree, decomposition, svm
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier, AdaBoostClassifier
from sklearn.linear_model import LogisticRegression, Perceptron, SGDClassifier, OrthogonalMatchingPursuit, RandomizedLogisticRegression
from sklearn.neighbors.nearest_centroid import NearestCentroid
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import ParameterGrid
from sklearn.metrics import *
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
class Grasp(object):
"""A ML project complete with data, options, etc.
Attributes:
data: The data read
train_set: The set for training
test_set: the set for testing
"""
def __init__(self, data):
self.data = data
self.scores = ['accuracy']
pass
available_classifiers = {
'RF': RandomForestClassifier(n_estimators=50, n_jobs=-1),
'ET': ExtraTreesClassifier(n_estimators=10, n_jobs=-1, criterion='entropy'),
'AB': AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), algorithm="SAMME", n_estimators=200),
'LR': LogisticRegression(penalty='l1', C=1e5),
'SVM': svm.SVC(kernel='linear', probability=True, random_state=0),
'GB': GradientBoostingClassifier(learning_rate=0.05, subsample=0.5, max_depth=6, n_estimators=10),
'NB': GaussianNB(),
'DT': DecisionTreeClassifier(),
'SGD': SGDClassifier(loss="hinge", penalty="l2"),
'KNN': KNeighborsClassifier(n_neighbors=3)
}
def split_test_train(self, test_fraction, target):
self.X = self.data.drop(target, axis=1)
self.y = self.data[target]
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, \
test_size=test_fraction)
def gridsearch(self, params_dict, scores=['accuracy']):
models = [(x, Grasp.available_classifiers[x], params_dict[x]) for x in list(params_dict.keys())]
for score in scores:
for model_abbr, model, params in models:
clf = GridSearchCV(model, params, scoring=score, n_jobs=4)
clf.fit(self.X_train, self.y_train)
print(clf.best_params_)
| a6efb45d50c0e2560019e477431fdb87a8167654 | [
"Markdown",
"Python"
] | 13 | Python | Moloq/ML-assignments | 36f2c128c278cc92ae7d5ff54b0675f0c8792fd6 | cb04e1ece0c382129c1630ecd62fca8bac4f6830 |
refs/heads/master | <repo_name>mgorav/springbootdrools<file_sep>/README.md
A Spring Boot and Drools integration. It exposes the validaiton service as API using Swagger 2.0. To compile the
application issue below command:
mvn clean install -DskipTests
To run the application issue the following command:
java -jar target/DataCleansingRules-0.0.1-SNAPSHOT.jar
Open the browser and hit the below url:
http://localhost:8080/swagger-ui.html<file_sep>/src/main/java/com/gonnect/cleansing/rules/app/model/Person.java
package com.gonnect.cleansing.rules.app.model;
import java.util.Date;
public class Person {
private String firstName;
private String lastName;
private String dob;
boolean isValid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public boolean isValid() {
return isValid;
}
public void setValid(boolean valid) {
isValid = valid;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dob='" + dob + '\'' +
", isValid=" + isValid +
'}';
}
}
| 923abc04b986bc2d8e14ee3db1dac041a86b6948 | [
"Markdown",
"Java"
] | 2 | Markdown | mgorav/springbootdrools | a135bad28193a331da38a98379e3e46b599390a8 | 1f0a586f8a5aa7c9987288ae2a69624495636ae0 |
refs/heads/master | <repo_name>nulligor/poop-killer<file_sep>/src/GameOverScene.js
class GameOverScene extends Phaser.Scene {
constructor() {
super({key: 'GameOverScene'});
}
create() {
this.pressX = this.add.bitmapText(this.sys.game.config.width/6,
this.sys.game.config.height/2,
'font',
"PRESS X TO PLAY AGAIN", 15);
this.add.bitmapText(this.sys.game.config.width/6,
this.sys.game.config.height/6,
'font',
"YOU DEFEATED THE POOP MONSTER!!", 15);
this.blink = 1000;
this.startKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.X);
this.add.image(this.sys.game.config.width/1.3,
this.sys.game.config.height/1.5, 'diploma')
}
update(time, delta) {
this.blink-=delta;
if(this.blink<0){
this.pressX.alpha = this.pressX.alpha === 1 ? 0 : 1;
this.blink = 500;
}
if(this.startKey.isDown){
this.scene.start('MainScene');
}
}
}
export default GameOverScene;
<file_sep>/src/MainScene.js
// ===========================================================================
// GLOBALS
let shotTimer = 0;
let poopTimer = [0, 0, 0,];
let pathCounter = 0;
// ===========================================================================
// HELPER FUNCTIONS
function hitBoss(boss, bullet) {
bullet.disableBody(true, true);
boss.HP = boss.HP - 5;
boss.text.destroy();
boss.text = this.add.bitmapText(this.sys.game.config.width/10,
this.sys.game.config.height/5,
'font',
"BOSS HP " + boss.HP, 15);
}
function killPlayer(player, entity) {
return player.alive = false;
}
function bossMoveSet_1(boss, bullets, time) {
// Shot Patterns
if(pathCounter < 400) {
shootPoopLeft(time, bullets, 0, boss);
shootPoopLeft(time, bullets, 1, boss);
shootPoopLeft(time, bullets, 2, boss);
} else {
shootPoopRight(time, bullets, 0, boss);
shootPoopRight(time, bullets, 1, boss);
shootPoopRight(time, bullets, 2, boss);
}
// Main Boss Path
if (pathCounter < 100) {
boss.body.velocity.x = -50;
boss.body.velocity.y = Math.sin(pathCounter) * 2 + 100;
} else if (pathCounter < 250) {
boss.body.velocity.x = -100;
boss.body.velocity.y = -(Math.sin(pathCounter) * 2 + 100);
}
else if (pathCounter < 300) {
boss.body.velocity.x = +100;
boss.body.velocity.y = +(Math.sin(pathCounter) * 2 + 100);
}
else {
boss.body.velocity.x = 0;
boss.body.velocity.y = 0;
}
}
function bossMoveSet_2(boss, bullets, time) {
// Shot Patterns
if(pathCounter < 400) {
shootPoopRight(time, bullets, 0, boss);
shootPoopRight(time, bullets, 1, boss);
shootPoopRight(time, bullets, 2, boss);
} else {
shootPoopLeft(time, bullets, 0, boss);
shootPoopLeft(time, bullets, 1, boss);
shootPoopLeft(time, bullets, 2, boss);
}
// Secondary Boss Path
if (pathCounter < 100) {
boss.body.velocity.x = +150;
boss.body.velocity.y = Math.sin(pathCounter) * 2 + 100;
} else if (pathCounter < 250) {
boss.body.velocity.x = -100;
}
else if (pathCounter < 300) {
boss.body.velocity.x = +50;
}
else {
bossMoveSet_1(boss, bullets, time);
}
}
function shootPoopLeft(time, bullets, direction , boss) {
if (poopTimer[direction] < time.now && Object.keys(bullets).length != 0) {
poopTimer[direction] = time.now + 700;
let bullet;
bullet = bullets.create(boss.body.x + boss.body.width - 200 * direction,
boss.body.y + boss.body.height / 150 * direction, 'boss_bullet');
bullet.setVelocityY(-200);
bullet.setVelocityX(-150);
bullet.setAccelerationY(-500);
bullet.outOfBoundsKill = true;
}
}
function shootPoopRight(time, bullets, direction , boss) {
if (poopTimer[direction] < time.now && Object.keys(bullets).length != 0) {
poopTimer[direction] = time.now + 700;
let bullet;
bullet = bullets.create(boss.body.x + boss.body.width - 200 * direction,
boss.body.y + boss.body.height / 150 * direction, 'boss_bullet');
bullet.setVelocityY(150);
bullet.setVelocityX(150);
bullet.setAccelerationY(100);
bullet.outOfBoundsKill = true;
}
}
function shoot(time, bullets, facing, player) {
if (shotTimer < time.now) {
shotTimer = time.now + 400;
let bullet;
if (facing == 'left') {
bullet = bullets.create(player.body.x + player.body.width - 50,
player.body.y + player.body.height / 2 - 4, 'bullet');
} else {
bullet = bullets.create(player.body.x + player.body.width,
player.body.y + player.body.height / 2 - 4, 'bullet');
}
bullet.setVelocityY(-250);
bullet.setAccelerationY(-250);
bullet.outOfBoundsKill = true;
if (facing == 'right') {
bullet.setVelocityX(700);
} else {
bullet.setVelocityX(-700);
}
}
}
// ===========================================================================
// CLASS
class MainScene extends Phaser.Scene {
constructor() {
super({key: 'MainScene'});
}
create() {
// Background
this.add.tileSprite(this.sys.game.config.width/2,
this.sys.game.config.height/2.1, 960, 540, 'background');
// Ground
this.platforms = this.physics.add.staticGroup();
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
this.platforms.create(400, 400, 'ground').refreshBody();
// Player
this.player = this.physics.add.sprite(100,230,'contra');
this.player.setBounce(0.2);
this.player.alive = true;
this.player.setGravityY(500);
this.player.setCollideWorldBounds(true);
this.physics.add.collider(this.player, this.platforms);
this.facing = 'right';
// Player Bullets
this.bullets = this.physics.add.group();
// Player Animations
this.anims.create({
key: 'player_left',
frames: this.anims.generateFrameNumbers('contra', { start: 8, end: 15 }),
frameRate: 12,
repeat: -1
});
this.anims.create({
key: 'player_right',
frames: this.anims.generateFrameNumbers('contra', { start: 0, end: 7 }),
frameRate: 12,
repeat: -1
});
this.anims.create({
key: 'player_idle_left',
frames: this.anims.generateFrameNumbers('contra', { start: 8, end: 8 }),
frameRate: 12,
repeat: -1
});
this.anims.create({
key: 'player_idle_right',
frames: this.anims.generateFrameNumbers('contra', { start: 0, end: 0 }),
frameRate: 12,
repeat: -1
});
// Keyboard
this.jumpKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.X);
this.fireKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Z);
this.cursors = this.input.keyboard.createCursorKeys();
// Boss
this.boss = this.physics.add.sprite(750, 200,'boss');
this.boss.HP = 100;
this.boss.setGravityY(-900);
this.boss.setCollideWorldBounds(false);
this.boss.text = this.add.bitmapText(this.sys.game.config.width/10,
this.sys.game.config.height/5,
'font',
"BOSS HP " + this.boss.HP, 15);
// Boss Bullets
this.bossBullets = this.physics.add.group();
}
update() {
// ===========================================================================
// PLAYER CONTROLS
// Walk
if (this.cursors.right.isDown) {
this.player.setVelocityX(170);
this.player.anims.play('player_right', true);
this.facing = 'right';
} else if (this.cursors.left.isDown) {
this.player.setVelocityX(-170);
this.player.anims.play('player_left', true);
this.facing = 'left';
} else {
this.player.setVelocityX(0);
this.player.anims.play('player_idle_' + this.facing, true);
}
// Jump
if (this.jumpKey.isDown && this.player.body.touching.down) {
this.player.setVelocityY(-650);
}
// Shoot
if (this.fireKey.isDown) {
shoot(this.time, this.bullets, this.facing, this.player);
}
if(!this.player.alive) {
pathCounter = 0;
this.scene.start('MainScene');
}
// COLLIDERS
this.physics.add.collider(this.bossBullets, this.player, killPlayer, null, this);
this.physics.add.collider(this.bullets, this.boss, hitBoss, null, this);
// ===========================================================================
// BOSS ACTIONS
// Move
pathCounter += 1;
if(pathCounter >= 650) {
pathCounter = 0;
}
if(this.time.now >= 30000) {
this.boss.setCollideWorldBounds(true);
bossMoveSet_2(this.boss, this.bossBullets, this.time);
} else {
bossMoveSet_1(this.boss, this.bossBullets, this.time);
}
// Die and trigger Game Over
if(this.boss.HP <= 0) {
this.scene.start('GameOverScene');
}
}
}
export default MainScene;
<file_sep>/README.md
# Poop Killer 💩
## Agradecimentos
Esse projeto foi totalmente feito na plataforma [Phaser.js](http://phaser.io/) utilizando sua versão 3 (suporte ES6).
## Requisitos
Você precisa de [Node.js](https://nodejs.org) para instalar e rodar os scripts.
## Instalar e Rodar
Abra seu terminal, `cd` no diretório da aplicação e:
| Command | Description |
|---------|-------------|
| `npm install` | Instala as dependências.|
| `npm start` | Roda o bundler da aplicação e inicia um proceso **http-server**. <br> Pressione `Ctrl + c` para matar o processo. |
----
<br>
## Documentação
### Objetivo:
Derrotar o **Chefe Cocozão** e conseguir o seu diploma.
### Gênero:
Plataforma 2D
### Recursos:
* Node.js,
* Phaser.js
* Git/Github
* Um editor de texto
* Windows (💩)
* (???) mãos
### Estrutura de pastas:
```
.
| index.html
| LICENSE
| package.json
| README.md
| webpack.config.js
|
+---assets
| +---font
| | font.fnt
| | font.png
| |
| +---icon
| | favicon.ico
| |
| +---img
| | background.png
| | boss.png
| | boss_2.png
| | boss_bullet.png
| | bullet.png
| | diploma.png
| | platform.png
| |
| \---sprites
| contra.png
|
\---src
BootScene.js
GameOverScene.js
index.js
MainScene.js
TitleScene.js
```
### Funcionamento da Aplicação:
* Ao rodar `npm start` estamos invocando o comando `scripts.start` dentro de `package.json`, assim, invocando consequentemente o nosso bundler [Webpack](https://webpack.js.org/) que pega todo o conteúdo localizado em `/src` e cria o arquivo `build/project.bundle.js` com todo o nosso código dentro, referenciado pelo arquivo `index.html`, sendo assim servimos um web-server com uma página HTML e dentro dela todo o nosso código Javascript, a bundle começa invocando `index.js` na estrutura de pastas.
* Seguindo a documentação (ainda escassa) do Framework (Phaser) https://photonstorm.github.io/phaser3-docs/#api-documentation houve a separação de cenas a serem carregadas pela aplicação:
BootScene, // <-- carrega os componentes visuais (assets)
TitleScene, // <-- cena do inicio
MainScene, // <-- cena principal (toda a lógica reside aqui)
GameOverScene // <-- cena de fim de jogo
* MainScene...<file_sep>/src/TitleScene.js
class TitleScene extends Phaser.Scene {
constructor() {
super({key: 'TitleScene'});
}
create() {
this.pressX = this.add.bitmapText(this.sys.game.config.width/6,
this.sys.game.config.height/2,
'font',
"PRESS X TO START", 15);
this.blink = 1000;
this.startKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.X);
this.tweens.add({
targets: this.add.image(this.sys.game.config.width/1.3,
this.sys.game.config.height, 'bossTitle'),
y: 450,
duration: 2000,
ease: 'Power3',
yoyo: true,
loop: -1
});
}
update(time, delta) {
this.blink-=delta;
if(this.blink<0){
this.pressX.alpha = this.pressX.alpha === 1 ? 0 : 1;
this.blink = 500;
}
if(this.startKey.isDown){
this.scene.start('MainScene');
}
}
}
export default TitleScene;
| c17c0051ff85f8e46d3c3dcb20df7c57f186b12a | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | nulligor/poop-killer | 2a9be858861a27f406996a9d3bded29b076bd33e | 18b4eceaad7e5ad0ac231ccd349956f08761425c |
refs/heads/master | <file_sep>import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
fun main(args: Array<String>) {
/*exampleOf("toList") {
val subscriptions = CompositeDisposable()
// 1
val items = Observable.just("A", "B", "C",2)
subscriptions.add(
items
// 2
.toList()
.subscribeBy {
println(it)
}
)
}*/
/*exampleOf("map") {
val subscriptions = CompositeDisposable()
subscriptions.add(
// 1
Observable.just("M", "C", "V", "I")
// 2
.map {
// 3
it.romanNumeralIntValue()
}
// 4
.subscribeBy {
println(it)
})
}*/
/*exampleOf("flatMap") {
val subscriptions = CompositeDisposable()
// 1
val ryan = Student(BehaviorSubject.createDefault(80))
val charlotte = Student(BehaviorSubject.createDefault(90))
// 2
val student = PublishSubject.create<Student>()
student
// 3
.flatMap { it.score }
// 4
.subscribe { println(it) }
.addTo(subscriptions)
student.onNext(ryan)
ryan.score.onNext(85)
student.onNext(charlotte)
ryan.score.onNext(95)
charlotte.score.onNext(100)
}*/
/*exampleOf("switchMap") {
val ryan = Student(BehaviorSubject.createDefault(80))
val charlotte = Student(BehaviorSubject.createDefault(90))
val student = PublishSubject.create<Student>()
student
.switchMap { it.score }
.subscribe { println(it) }
student.onNext(ryan)
ryan.score.onNext(85)
student.onNext(charlotte)
ryan.score.onNext(95)
charlotte.score.onNext(100)
}*/
exampleOf("materialize/dematerialize") {
val subscriptions = CompositeDisposable()
val ryan = Student(BehaviorSubject.createDefault(80))
val charlotte = Student(BehaviorSubject.createDefault(90))
val student = BehaviorSubject.create<Student>()
// 1
val studentScore = student
.switchMap { it.score.materialize() }
// 2
subscriptions.add(studentScore
// 1
.filter {
if (it.error != null) {
println(it.error)
false
} else {
true
}
}
// 2
.dematerialize<Int>()
.subscribe {
println(it)
}
.addTo(subscriptions))
// 3
student.onNext(ryan)
ryan.score.onNext(85)
ryan.score.onError(RuntimeException("Error!"))
ryan.score.onNext(90)
// 4
student.onNext(charlotte)
}
}
<file_sep>import io.reactivex.subjects.BehaviorSubject
fun exampleOf(description: String, action: () -> Unit) {
println("\n--- Example of: $description ---")
action()
}
class Student(val score: BehaviorSubject<Int>)
fun String.romanNumeralIntValue(): Int {
return when (this) {
"I" -> 1
"V" -> 5
"X" -> 10
"L" -> 50
"C" -> 100
"D" -> 500
"M" -> 1000
else -> -1
}
} | 1eda984c13081fe8a8612dc7b240e9de191c5752 | [
"Kotlin"
] | 2 | Kotlin | LutLas/c7transformingOperators | aae6aa6fc3273a2253d008aada3310d71e933789 | e67cdede1ca9772ea1d061d0924eed15a170c316 |
refs/heads/master | <repo_name>blancheta/global_python_task<file_sep>/track/migrations/0001_initial.py
# Generated by Django 3.1.5 on 2021-01-19 10:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Artist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=80, unique=True)),
],
),
migrations.CreateModel(
name='Track',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('duration', models.DecimalField(decimal_places=1, max_digits=4)),
('external_id', models.IntegerField(unique=True)),
('last_play', models.DateTimeField()),
('artists', models.ManyToManyField(blank=True, to='track.Artist')),
],
),
]
<file_sep>/track/tests.py
from django.test import TestCase
from rest_framework.reverse import reverse
class TrackViewTest(TestCase):
fixtures = ['test_data.json']
def test_fetch_single_track_good(self):
response = self.client.get(
reverse('track-detail', args=('1',)),
)
response_json = response.json()
assert response.status_code == 200
assert 'title' in response_json
def test_create_new_track_good(self):
response = self.client.post(
'/api/tracks/',
data={
'external_id': 10000,
'title': 'Lalalal',
'duration': '300',
'artists': '1',
'last_play': '2018-05-17 15:23:20'
}
)
assert response.status_code == 201
def test_list_100_most_recent_tracks_good(self):
response = self.client.get(
reverse('track-list')
)
response_json = response.json()['results']
last_track_played = response_json[0]
second_last_track_played = response_json[1]
assert response.status_code == 200
assert last_track_played['last_play'] > second_last_track_played['last_play']
assert len(response_json) <= 100
def test_filter_tracks_by_name_good(self):
response = self.client.get(
reverse('track-list'), kwargs={
'title': 'love'
}
)
response_json = response.json()
assert 'Love' in response_json['results'][0]['title']
def test_list_artists_good(self):
response = self.client.get(
reverse('artist-list'),
)
response_json = response.json()
assert response.status_code == 200
first_artist = response_json[0]
first_artist_keys = first_artist.keys()
assert 'name' in first_artist_keys
assert 'tracks_count' in first_artist_keys
assert 'most_recent_played_track' in first_artist_keys
<file_sep>/track/serializers.py
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from track.models import Track, Artist
class TrackSerializer(ModelSerializer):
class Meta:
model = Track
fields = ['title', 'artists', 'last_play', 'external_id', 'duration']
class ArtistSerializer(ModelSerializer):
most_recent_played_track = serializers.CharField()
tracks_count = serializers.IntegerField()
class Meta:
model = Artist
fields = ['most_recent_played_track', 'tracks_count', 'name']
<file_sep>/track/views.py
from django.db.models import Count, OuterRef, Subquery
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from track.models import Track, Artist
from track.serializers import TrackSerializer, ArtistSerializer
class TrackPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
class TrackViewSet(viewsets.ModelViewSet):
"""
A viewset that provides `retrieve`, `create`, and `list` actions for Track model.
"""
queryset = Track.objects.all().order_by('-last_play')
serializer_class = TrackSerializer
pagination_class = TrackPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['title']
class ArtistListView(ListAPIView):
"""
Provides a list view for Artist model.
"""
def get_queryset(self):
latest_track = Subquery(Track.objects.filter(
artists__id=OuterRef("id"),
).values('title')[:1])
qs = Artist.objects.annotate(
most_recent_played_track=latest_track
)
qs = qs.annotate(
tracks_count=Count('track')
)
return qs
serializer_class = ArtistSerializer
<file_sep>/README.md
Global Python task
==================
I completed the challenge in 2:45.
I had fun with this challenge and decided to focus on end to end tests to check the expected endpoints.
I used the pagination system to display the first 100 results for tracks.
# Init the project
```
python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt
./manage.py migrate
```
# Run tests
```
./manage.py test
```
# Import data into the db
```
./manage.py import_tracks
```
# Run project
```
./manage.py runserver
```
<file_sep>/track/models.py
from django.db import models
class Artist(models.Model):
name = models.CharField(unique=True, max_length=80)
class Track(models.Model):
title = models.CharField(max_length=100)
duration = models.DecimalField(decimal_places=1, max_digits=4)
external_id = models.IntegerField(unique=True)
last_play = models.DateTimeField()
artists = models.ManyToManyField(Artist, blank=True)
<file_sep>/track/management/commands/import_tracks.py
import json
import re
from django.core.management import BaseCommand
from track.models import Artist, Track
class Command(BaseCommand):
help = 'Import tracks from file to db'
def handle(self, *args, **kwargs):
with open('tracks.json') as json_file:
tracks = json.load(json_file)
artists_to_create_per_track = {}
tracks_to_create = []
for track in tracks:
artist_names = map(
str.strip,
re.split(
'/|feat.|vs|&',
track['artist'],
flags=re.IGNORECASE
)
)
artists = []
for artist_name in artist_names:
artist, created = Artist.objects.get_or_create(name=artist_name)
artists.append(artist)
artists_to_create_per_track[track['id']] = artists
track['external_id'] = track.pop('id')
track.pop('artist')
tracks_to_create.append(Track(**track))
Track.objects.bulk_create(tracks_to_create)
# Add artists to tracks
for track_ext_id, artists in artists_to_create_per_track.items():
if artists:
Track.objects.get(external_id=track_ext_id).artists.add(*artists)
| b015deadb96f78067c5887fea5c913f037aed92f | [
"Markdown",
"Python"
] | 7 | Python | blancheta/global_python_task | 17c67adf1ee8b3b5cf5bd54d85a860f1ec308507 | a723b5263a0f04db7939aef9ecbd86a6dc573871 |
refs/heads/master | <repo_name>LasseLund-Egmose/02121BasicProject<file_sep>/Controller.java
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Controller {
protected ArrayList<CheckerPiece> checkerPieces = new ArrayList<>(); // A list of all pieces
protected HashMap<Integer, HashMap<Integer, Field>> fields = new HashMap<>(); // A map (x -> y -> pane) of all fields
protected HashMap<Team, Integer> activeCount = new HashMap<>(); // A map (Team -> int) of number of active pieces on each team
protected HashMap<Field, Field> possibleJumpMoves = new HashMap<>(); // A map (pane -> jumped pane) of all possible jump moves
protected ArrayList<Field> possibleRegularMoves = new ArrayList<>(); // A list of all possible regular moves
protected int dimension; // Dimension of board
protected GridPane grid;
protected boolean isWhiteTurn = false; // Keep track of turn
protected EventHandler<MouseEvent> moveClickEventHandler; // EventHandler for click events on black fields
protected CheckerPiece selectedPiece = null; // Keep track of selected piece
protected View view; // Reference to view instance
// Team enum
public enum Team {
BLACK,
WHITE
}
// Check if a team has won
protected void checkForWin() {
if (this.activeCount.get(Team.BLACK) == 0) {
this.view.displayWin("White won");
}
if (this.activeCount.get(Team.WHITE) == 0) {
this.view.displayWin("Black won");
}
}
// Handle a jump move
protected void doJumpMove(Field toField, Field jumpedField) {
// Detach (remove) jumped CheckerPiece
jumpedField.getAttachedPiece().detach(this.activeCount);
// Handle rest of move as a regular move
this.doRegularMove(toField);
}
// Handle a regular move
protected void doRegularMove(Field toField) {
// Attach selected piece to chosen field
this.getSelectedPiece().attachToField(toField, this.activeCount);
// Remove highlight of piece and fields
this.selectedPiece.assertHighlight(false);
this.normalizeFields();
// Reset highlight-related properties
this.selectedPiece = null;
this.possibleJumpMoves.clear();
this.possibleRegularMoves.clear();
// Finish turn
this.finishTurn();
}
// Check if a jump move is eligible (e.g. no piece behind jumped piece)
// Return pane from new position if yes and null if no
protected Object eligibleJumpMoveOrNull(CheckerPiece thisPiece, Point opponentPosition) {
Point thisPos = thisPiece.getPosition();
Point diff = new Point(opponentPosition.x - thisPos.x, opponentPosition.y - thisPos.y);
Point newPos = (Point) opponentPosition.clone();
newPos.translate(diff.x, diff.y);
return this.isPositionValid(newPos) ? fields.get(newPos.x).get(newPos.y) : null;
}
// Check if game is over, toggle isWhiteTurn and setup turn for other team
protected void finishTurn() {
this.isWhiteTurn = !this.isWhiteTurn;
checkForWin();
this.view.setupDisplayTurn(this.isWhiteTurn);
this.view.rotate();
}
// Highlight fields a selected piece can move to
protected void highlightEligibleFields(CheckerPiece piece) {
// Iterate surrounding diagonal fields of given piece
for (Point p : this.surroundingFields(piece.getPosition())) {
// Get pane of current field
Field field = this.fields.get(p.x).get(p.y);
// Is this position occupied - and is it possible to jump it?
if (field.getChildren().size() > 0) {
Object eligibleJumpMove = this.eligibleJumpMoveOrNull(piece, p);
// Check if jump move is eligible - per eligibleJumpMoveOrNull
if (eligibleJumpMove instanceof Field) {
// Handle jump move if not null (e.g. instance of Field)
Field eligibleJumpMoveField = (Field) eligibleJumpMove;
this.possibleJumpMoves.put(eligibleJumpMoveField, field);
this.view.highlightPane(eligibleJumpMoveField);
}
} else { // Else allow a regular move
this.possibleRegularMoves.add(field);
this.view.highlightPane(field);
}
}
}
// Check if position is within boundaries of board
protected boolean isPositionValid(Point p) {
return p.x >= 1 && p.y >= 1 && p.x <= this.dimension && p.y <= this.dimension;
}
// Remove highlights from highlighted fields
protected void normalizeFields() {
ArrayList<Field> allHighlightedPanes = new ArrayList<>();
allHighlightedPanes.addAll(this.possibleJumpMoves.keySet());
allHighlightedPanes.addAll(this.possibleRegularMoves);
for (Field field : allHighlightedPanes) {
this.view.normalizePane(field);
}
}
// Handle click on black field
protected void onFieldClick(Object clickedElement) {
// Check if Field is clicked and a selectedPiece is chosen
if (!(clickedElement instanceof Field) || this.getSelectedPiece() == null) {
return;
}
Field clickedElementField = (Field) clickedElement;
// Is a jump move chosen?
if (this.possibleJumpMoves.containsKey(clickedElement)) {
this.doJumpMove(clickedElementField, this.possibleJumpMoves.get(clickedElement));
return;
}
// Is a regular move chosen?
if (this.possibleRegularMoves.contains(clickedElement)) {
this.doRegularMove(clickedElementField);
}
}
// Setup one black field by position
protected void setupField(Point p) {
Field field = new Field(p);
field.addEventFilter(MouseEvent.MOUSE_PRESSED, this.moveClickEventHandler);
if (!this.fields.containsKey(p.x)) {
this.fields.put(p.x, new HashMap<>());
}
this.fields.get(p.x).put(p.y, field);
this.view.setupField(field, p);
}
// Create a piece by team and attach it to given position
protected void setupPiece(Point position, Team team) {
CheckerPiece piece = new CheckerPiece(this.view.getFieldSize(), team);
Field field = this.fields.get(position.x).get(position.y);
// Attach to field by position
piece.attachToField(
field,
this.activeCount
);
// Setup click event for field
piece.setupEvent(this);
// Add to list of pieces
this.checkerPieces.add(piece);
}
// Get diagonally surrounding fields (within board boundaries) from a given position
protected ArrayList<Point> surroundingFields(Point p) {
ArrayList<Point> eligiblePoints = new ArrayList<>();
Point[] points = new Point[]{
new Point(p.x - 1, p.y + 1),
new Point(p.x + 1, p.y + 1),
new Point(p.x - 1, p.y - 1),
new Point(p.x + 1, p.y - 1)
};
for (int i = 0; i < 4; i++) {
Point ip = points[i];
if (this.isPositionValid(ip)) {
eligiblePoints.add(ip);
}
}
return eligiblePoints;
}
// Construct controller
public Controller(View view, int dimension, GridPane grid) {
this.dimension = dimension;
this.grid = grid;
this.moveClickEventHandler = mouseEvent -> this.onFieldClick(mouseEvent.getSource());
this.view = view;
this.activeCount.put(Team.BLACK, 0);
this.activeCount.put(Team.WHITE, 0);
this.view.setupDisplayTurn(this.isWhiteTurn);
}
// Get selected piece
public CheckerPiece getSelectedPiece() {
return this.selectedPiece;
}
// Set selected piece
public void setSelectedPiece(CheckerPiece piece) {
// Remove highlight from currently selected piece
if (this.selectedPiece != null) {
this.normalizeFields();
this.selectedPiece.assertHighlight(false);
}
// Select piece if turn matches the piece's team
if (this.selectedPiece != piece && isWhiteTurn == (piece.getTeam() == Team.WHITE)) {
this.selectedPiece = piece;
this.selectedPiece.assertHighlight(true);
// Highlight fields around selected piece
this.highlightEligibleFields(this.selectedPiece);
return;
}
// Reset selectedPiece
this.selectedPiece = null;
}
// Setup black fields
public void setupFields() {
for (int i = 0; i < this.dimension; i++) {
for (int j = i % 2; j < this.dimension; j += 2) {
this.setupField(new Point(j + 1, i + 1));
}
}
}
// Setup a piece in each corner
public void setupPieces() {
this.setupPiece(new Point(1, 1), Team.BLACK);
this.setupPiece(new Point(this.dimension, this.dimension), Team.WHITE);
}
}
<file_sep>/CheckerPiece.java
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Cylinder;
import javafx.scene.transform.Rotate;
import java.awt.*;
import java.util.HashMap;
public class CheckerPiece {
protected Cylinder cylinder; // Cylinder shape
protected StackPane cylinderContainer = new StackPane(); // Cylinder container
protected boolean isActive = false; // Is this piece added to board?
protected PhongMaterial material; // Cylinder texture
protected Field parent = null; // Parent field containing cylinderContainer
protected double size; // Size of one field
protected Controller.Team team; // Team of this piece
// Setup pane, shape and material
protected void setupPiece() {
double radius = (this.size * 2) / 5;
double height = radius / 1.5;
this.material = new PhongMaterial();
this.material.setDiffuseMap(
new Image(getClass().getResourceAsStream(
team == Controller.Team.BLACK ? "/assets/piece_black.jpg" : "/assets/piece_white.jpg"
))
);
this.cylinder = new Cylinder(radius, height);
this.cylinder.setMaterial(this.getMaterial());
this.cylinder.setRotationAxis(Rotate.X_AXIS);
this.cylinder.setRotate(90);
this.cylinder.setTranslateZ(height / 2);
this.cylinderContainer.getChildren().add(this.cylinder);
}
// Construct
public CheckerPiece(double size, Controller.Team team) {
this.size = size;
this.team = team;
this.setupPiece();
}
// Make sure piece is either highlighted or not
public void assertHighlight(boolean shouldHighlight) {
if (shouldHighlight) {
this.cylinder.setMaterial(new PhongMaterial(Color.LIMEGREEN));
return;
}
this.cylinder.setMaterial(this.getMaterial());
}
// Detach and afterwards attach piece to given pane (black field)
public void attachToField(Field field, HashMap<Controller.Team, Integer> activeCount) {
// Detach
this.detach(activeCount);
// Add to field
field.getChildren().add(this.getPane());
// Setup references between piece and field
this.parent = field;
field.setAttachedPiece(this);
// Justify activeCount if applicable
if (!this.isActive) {
int activeCountInt = activeCount.get(this.team);
activeCountInt++;
activeCount.put(this.team, activeCountInt);
}
// Set active
this.isActive = true;
}
// Detach from current field and set activeCount accordingly
public void detach(HashMap<Controller.Team, Integer> activeCount) {
if (this.parent != null) {
this.parent.getChildren().clear();
this.parent.setAttachedPiece(null);
this.parent = null;
}
if (this.isActive) {
int activeCountInt = activeCount.get(this.team);
activeCountInt--;
activeCount.put(this.team, activeCountInt);
}
this.isActive = false;
}
public PhongMaterial getMaterial() {
return this.material;
}
public Pane getPane() {
return this.cylinderContainer;
}
public Field getParent() {
return this.parent;
}
public Point getPosition() {
if(this.getParent() == null) {
return null;
}
return this.getParent().getPosition();
}
public Controller.Team getTeam() {
return this.team;
}
// Setup click event on piece
public void setupEvent(Controller controller) {
this.cylinderContainer.setOnMouseClicked(e -> controller.setSelectedPiece(this));
}
} | b990ee02e81f6c024ef9261ecdcdbf31273b5bc3 | [
"Java"
] | 2 | Java | LasseLund-Egmose/02121BasicProject | e91bebaa8b53e671a2de470f804cd6f010efce51 | 47c3c78ceefbb297135f6648dc033b3117782687 |
refs/heads/master | <repo_name>yuhogun/hogun_codehouse<file_sep>/main.cpp
//main.cpp
#include <arrayfire.h>
#include <iostream>
using namespace af;
void MatAdd(array mat1, array mat2)
{
std::cout << "empty function!!" << std::endl;
}
void MatSub(array mat1, array mat2)
{
std::cout << "empty function!!" << std::endl;
}
void MatMul(array mat1, array mat2)
{
std::cout << "empty function!!" << std::endl;
}
void MatDiv(array mat1, array mat2)
{
std::cout << "empty function!!" << std::endl;
}
void MatMod(array mat1, array mat2)
{
std::cout << "empty function!!" << std::endl;
}
int main(void)
{
array mat1 = randu(3, 3);
array mat2 = randu(3, 3);
MatAdd(mat1, mat2);
MatSub(mat1, mat2);
MatMul(mat1, mat2);
MatDiv(mat1, mat2);
MatMod(mat1, mat2);
return 0;
}
<file_sep>/readme.md
이것은 Git 파일 입니다. | 9aa6d4947a7e57eeca1f4b9088e950c6c42ca5e8 | [
"Markdown",
"C++"
] | 2 | C++ | yuhogun/hogun_codehouse | b5d9c8ddd2c75ec73d2a107a408528d2faf41ac9 | 00b7f4fc74d9461edf7dab6887fa3704612d42cd |
refs/heads/development | <file_sep>import calculate from '../../logic/Calculate';
describe('calculate', () => {
it('Should treat Caculate as a function', () => {
expect(typeof calculate).toEqual('function');
});
it('Should return an object', () => {
const result = calculate({ total: null, next: null, operation: null }, 45);
expect(typeof result).toEqual('object');
});
it('Should return a string as Total', () => {
const result = calculate({ total: '6', next: null, operation: null }, 13);
expect(typeof result.total).toEqual('string');
});
it('If operation, number will be added to the next', () => {
const result = calculate({ total: '6', next: null, operation: '+' }, '9');
expect(result.total).toEqual('6');
expect(result.next).toEqual('9');
});
it('Should add number to total if next and operation is null', () => {
const result = calculate({ total: '1', next: null, operation: null }, '4');
expect(result.total).toEqual('14');
});
it('Should return 0 if operation is AC', () => {
const result = calculate({ total: null, next: null, operation: null }, 'AC');
expect(result).toEqual({ next: null, operation: null, total: 0 });
});
it('Should place . inbetween total and next if operation is "."', () => {
const result = calculate({ total: null, next: null, operation: null }, '.');
expect(result).toEqual({ next: null, operation: null, total: '0.' });
});
it('Should add neagtive to total and next if operation is "+/-"', () => {
const result = calculate({ total: '2', next: null, operation: null }, '+/-');
expect(result).toEqual({ next: -0, operation: null, total: -2 });
});
});
<file_sep>import Big from 'big.js';
const operate = (numberOne, numberTwo, operation) => {
const num1 = Big(numberOne);
const num2 = Big(numberTwo);
let result = '';
if (operation === '+') {
result = num1.plus(num2);
}
if (operation === '-') {
result = num1.minus(num2);
}
if (operation === 'X') {
result = num1.times(num2);
}
if (operation === '÷') {
result = num1.div(num2);
}
if (operation === '%') {
result = num1.mod(num2);
}
return result.toString();
};
export default operate;
<file_sep>import PropTypes from 'prop-types';
import '../stylesheets/button.css';
const Button = (props) => {
const { clickHandler, buttonName } = props;
const handleClick = () => {
clickHandler(buttonName);
};
return (
<button type="button" onClick={handleClick} className="button">
{buttonName}
</button>
);
};
Button.propTypes = {
buttonName: PropTypes.string,
clickHandler: PropTypes.func,
};
Button.defaultProps = {
buttonName: null,
clickHandler: null,
};
export default Button;
<file_sep>/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow } from 'enzyme';
import App from '../../App';
describe('App', () => {
let wrapper;
it('wraps content in a div with .container class', () => {
wrapper = shallow(<App />);
expect(wrapper.find('.container').length).toEqual(1);
});
it('must show valid contents and NOT null', () => {
wrapper = shallow(<App />);
expect(wrapper.find('.container').length).not.toEqual(null);
});
it('must display valid contents that is defined', () => {
wrapper = shallow(<App />);
expect(wrapper.find('.container').length).toBeDefined;
});
it('must be truthy', () => {
wrapper = shallow(<App />);
expect(wrapper.find('.container').length).toBeTruthy;
});
});
<file_sep># math-calc-app
This is a simple calculator application developed to demonstrate React.js's functionality and for educational purposes.
## Built With
- React
- JavaScript
- HTML
- CSS
## Tools
- Big.js
- PropTypes
## Live Demo
[Deployed app](https://fervent-sammet-cc944d.netlify.app/)
## Getting Started
To run a local copy of this application, follow the steps below:
- Go to the "Code" section of this repository and press the green button that says "Code". Copy the URL or the SSH key.
- Go to the terminal and enter:
```
git clone URL/SSH key
```
The URL or SSH are the links copied from the step above.
- If you don't have git installed, you can download this project and unzip it.
- Change directory into the folder the application is saved.
```
cd directory
```
Directory is the name of your folder.
- Once you have the local copy in your desired folder, go back to your terminal and run:
```
npm install
```
This command installs all the dependencies of the application. Once you complete all installations successfully, you're ready to use the application.
- To start using the application, run:
```
npm start
```
- The calculator will open up in your browser.
## Developer
👤 **<NAME>**
- GitHub: [george-shammar](https://github.com/george-shammar)
- Twitter: [@GeorgeShammar](https://twitter.com/GeorgeShammar)
- LinkedIn: [<NAME>](https://www.linkedin.com/in/georgegbenle/)
## 🤝 Contributing
Contributions, issues and feature requests are welcome!
## Show your support
Give a ⭐️ if you like this project!
## 📝 License
This project is [MIT](LICENSE) licensed.
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
import '../stylesheets/buttonpanel.css';
const ButtonPanel = (props) => {
const { clickHandler } = props;
const handleClick = (buttonName) => {
clickHandler(buttonName);
};
const renderButton = (i) => (
<Button buttonName={i} clickHandler={handleClick} />
);
return (
<div>
<div className="button-row">
{renderButton('AC')}
{renderButton('+/-')}
{renderButton('%')}
{renderButton('÷')}
</div>
<div className="button-row">
{renderButton('7')}
{renderButton('8')}
{renderButton('9')}
{renderButton('X')}
</div>
<div className="button-row">
{renderButton('4')}
{renderButton('5')}
{renderButton('6')}
{renderButton('-')}
</div>
<div className="button-row">
{renderButton('1')}
{renderButton('2')}
{renderButton('3')}
{renderButton('+')}
</div>
<div className="button-row">
{renderButton('0')}
{renderButton('.')}
{renderButton('=')}
</div>
</div>
);
};
ButtonPanel.propTypes = {
clickHandler: PropTypes.func,
};
ButtonPanel.defaultProps = {
clickHandler: null,
};
export default ButtonPanel;
<file_sep>import React from 'react';
import renderer from 'react-test-renderer';
import Display from '../Display';
import App from '../App';
import ButtonPanel from '../ButtonPanel';
it('renders the Display component correctly', () => {
const tree = renderer.create(<Display />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders the Display component correctly with result props', () => {
const total = '13';
const tree = renderer.create(<Display result={total} />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders the Display component correctly with next props', () => {
const next = '20';
const tree = renderer.create(<Display next={next} />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders the Display component correctly with operation props', () => {
const operation = '+';
const tree = renderer.create(<Display operation={operation} />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders the App component correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders the ButtonPanel component correctly', () => {
const tree = renderer.create(<ButtonPanel />).toJSON();
expect(tree).toMatchSnapshot();
});
<file_sep>/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow } from 'enzyme';
import ButtonPanel from '../../ButtonPanel';
describe('ButtonPanel', () => {
let wrapper;
it('wraps content in a div with .button-row class', () => {
wrapper = shallow(<ButtonPanel />);
expect(wrapper.find('.button-row').length).toEqual(5);
});
it('must show valid contents and NOT null', () => {
wrapper = shallow(<ButtonPanel />);
expect(wrapper.find('.button-row').length).not.toEqual(null);
});
it('must display valid contents that is defined', () => {
wrapper = shallow(<ButtonPanel />);
expect(wrapper.find('.button-row').length).toBeDefined;
});
it('must be truthy', () => {
wrapper = shallow(<ButtonPanel />);
expect(wrapper.find('.button-row')).toBeTruthy;
});
});
<file_sep>import PropTypes from 'prop-types';
import '../stylesheets/display.css';
const Display = (props) => {
const { result, operation } = props;
return (
<div className="bg-display">
<h1 className="result">{result}</h1>
<p>{operation}</p>
</div>
);
};
Display.defaultProps = { result: '0', operation: '' };
Display.propTypes = {
result: PropTypes.string,
operation: PropTypes.string,
};
export default Display;
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import '../stylesheets/nav.css';
function Navbar() {
return (
<div className="nav-container">
<h1>Math Magicians</h1>
<div>
<Link to="/" className="links">Home </Link>
<Link to="/calculator" className="links">Calculator </Link>
<Link to="/quote" className="links">Quote </Link>
</div>
</div>
);
}
export default Navbar;
| f9f34bd1140e52a3bc7ff637d4031286f20acb19 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | george-shammar/math-calc-app | 9d10f98a21eee65d92dde1bb3ecef846609496f4 | a729c6f5bfcdc82765808b1c481a251e6a23bbee |
refs/heads/master | <file_sep>package sh.iwmc.netty.exceptions;
public class NoDefaultConstructorException extends Exception {
public NoDefaultConstructorException(String s) {
super(s);
}
}
<file_sep>package sh.iwmc.netty.exceptions;
import sh.iwmc.netty.message.AbstractMessage;
import java.util.Map;
/**
* Exception meant to indicate that the {@link sh.iwmc.netty.message.MessageProvider} loaded but with warnings.
* The warnings are stored in a Map where the key is the class concerning the warning and the value is the raised exception.
*/
public class InitializationException extends Exception {
private Map<Class<? extends AbstractMessage>, Exception> ignoredClasses;
public InitializationException(Map<Class<? extends AbstractMessage>, Exception> ignoredClasses) {
super("The MessageProvider initialized with errors/warnings!");
StringBuilder sb = new StringBuilder("The following classes were ignored: \n");
for (Map.Entry<Class<? extends AbstractMessage>, Exception> entry : ignoredClasses.entrySet()) {
sb.append("\t").append(entry.getKey().getSimpleName()).append(" - cause: ").append(entry.getValue().getMessage()).append("\n");
}
this.ignoredClasses = ignoredClasses;
initCause(new InitializationException(sb.toString()));
}
private InitializationException(String message) {
super(message);
}
public Map<Class<? extends AbstractMessage>, Exception> getIgnoredClasses() {
return ignoredClasses;
}
}
<file_sep>package sh.iwmc.netty.exceptions;
public class MissingAnnotationException extends Exception {
public MissingAnnotationException() {
}
public MissingAnnotationException(String message) {
super(message);
}
}
<file_sep>package sh.iwmc.netty.message;
public class MessageContext {
private MessageProvider provider;
MessageContext(MessageProvider provider) {
this.provider = provider;
}
public MessageProvider getProvider() {
return provider;
}
MessageDefinition definitionFor(Class<? extends AbstractMessage> aClass) {
for(MessageDefinition def : getProvider().getDefinitions()) {
if(def.getMessageClass().equals(aClass)) {
return def;
}
}
return null;
}
}
<file_sep>package sh.iwmc.netty.message;
import com.google.common.base.Optional;
public class InstanceCreator {
private MessageDefinition definition;
private int triggeringOpcode;
private Class triggeringGroup;
InstanceCreator(MessageDefinition definition, int triggeringOpcode, Class group) {
this.definition = definition;
this.triggeringOpcode = triggeringOpcode;
triggeringGroup = group;
}
/**
* Creates a new instance of the found message. The found message must have a default constructor.
* @return
*/
public Optional<AbstractMessage> newInstance() {
if (definition == null) {
return Optional.absent();
}
Optional<AbstractMessage> m = definition.newInstance();
if (m.isPresent()) {
m.get().setTriggeredOpcode(triggeringOpcode);
}
return m;
}
}
<file_sep>package sh.iwmc.netty.message;
import com.google.common.base.Optional;
public class MessageDefinition {
private Class<? extends AbstractMessage> messageClass;
private sh.iwmc.netty.annot.Message messageAnnot;
private Class group;
private MessageContext context;
public MessageDefinition(MessageContext context, Class<? extends AbstractMessage> messageClass, sh.iwmc.netty.annot.Message messageAnnot) {
this(context, messageClass, messageAnnot, null);
}
public MessageDefinition(MessageContext context, Class<? extends AbstractMessage> messageClass, sh.iwmc.netty.annot.Message messageAnnot, Class group) {
this.context = context;
this.messageClass = messageClass;
this.messageAnnot = messageAnnot;
this.group = group;
}
public boolean hasGroup() {
return group != null;
}
public Class<? extends AbstractMessage> getMessageClass() {
return messageClass;
}
public sh.iwmc.netty.annot.Message getMessageAnnot() {
return messageAnnot;
}
public Class getGroup() {
return group;
}
public boolean hasOpcode(int opcode) {
for(int oc : messageAnnot.opcodes()) {
if(oc == opcode) {
return true;
}
}
return false;
}
Optional<AbstractMessage> newInstance() {
try {
AbstractMessage m = messageClass.newInstance();
m.setContext(context);
return Optional.of(m);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return Optional.absent();
}
@Override
public String toString() {
return "MessageDefinition{" +
"messageClass=" + messageClass +
", messageAnnot=" + messageAnnot +
", group=" + group +
", context=" + context +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageDefinition that = (MessageDefinition) o;
if (!messageClass.equals(that.messageClass)) return false;
return messageAnnot.equals(that.messageAnnot);
}
@Override
public int hashCode() {
int result = messageClass.hashCode();
result = 31 * result + messageAnnot.hashCode();
return result;
}
}
| 69f58739422ec451cf07ebbb25c625b4dd8c8c70 | [
"Java"
] | 6 | Java | brentco/netty-messages | c4162a8d4cf18effb301a013efd7a84560687911 | 303443bc5bd126724ac75fd21888b58cf7c780d2 |
refs/heads/master | <repo_name>tcowern/iOS-Class<file_sep>/DreamLister/DreamLister/Store+CoreDataClass.swift
//
// Store+CoreDataClass.swift
// DreamLister
//
// Created by <NAME> on 8/6/17.
// Copyright © 2017 AppCoda. All rights reserved.
//
import Foundation
import CoreData
//@objc(Store)
public class Store: NSManagedObject {
}
<file_sep>/README.md
# iOS-Class
iOS Class
<file_sep>/Protocols.playground/Contents.swift
//: Playground - noun: a place where people can play
import UIKit
extension Double {
var dollarString: String {
return String(format: "$%.02f", self)
}
}
var pct = 32.15 * 0.15
print(pct.dollarString)
<file_sep>/SocialApp/SocialApp/Constants.swift
//
// Constants.swift
// SocialApp
//
// Created by <NAME> on 8/16/17.
// Copyright © 2017 vetDevHouse. All rights reserved.
//
import UIKit
let SHADOW_GRAY: CGFloat = 120.0 / 255.0
<file_sep>/TacoPop/TacoPop/HeaderView.swift
//
// HeaderView.swift
// TacoPop
//
// Created by <NAME> on 8/10/17.
// Copyright © 2017 vetDevHouse. All rights reserved.
//
import UIKit
class HeaderView: UIView, DropShadow {
}
<file_sep>/NewNotifications/NewNotifications/ViewController.swift
////
//// ViewController.swift
//// NewNotifications
////
//// Created by <NAME> on 8/11/17.
//// Copyright © 2017 vetDevHouse. All rights reserved.
////
//
//import UIKit
//import UserNotifications
//
//class ViewController: UIViewController {
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// //Request Permision
//
// UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {(granted, error) in
//
// if granted {
//
// print("Notification access granted")
//
// } else {
//
// print(error?.localizedDescription)
// }
//
// })
//
// }
//
// @IBAction func notifyMeButtonTapped(sender: UIButton) {
// scheduleNotification(inSeconds: 5, completion: { success in
// if success {
// print("Successfully scheduled notification")
// } else {
// print("Error scheduling notification")
// }
// })
// }
//
//
//
//// @IBAction func notifyButtonTapped(sender: UIButton) {
////
//// scheduleNotification(inSeconds: 5, completion: { success in
////
//// if success {
////
//// print("Successfully scheduled notification")
////
//// } else {
////
//// print("Error scheduling notification")
////
//// }
////
//// })
////
//// }
//
// func scheduleNotification(inSeconds: TimeInterval, completion: @escaping () -> ()) {
//
// let notif = UNMutableNotificationContent()
//
// notif.title = "New Notification"
// notif.subtitle = "These are great"
// notif.body = "This is the notification body"
//
// let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)
//
// let request = UNNotificationRequest(identifier: "My notification", content: notif, trigger: notifTrigger)
//
// UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
//
// if error != nil {
//
// print(error)
//
// completion()
//
// } else {
//
// completion()
//
// }
//
// })
// }
//
//}
<file_sep>/TacoPop/TacoPop/ReusableView.swift
//
// ReusableView.swift
// TacoPop
//
// Created by <NAME> on 8/11/17.
// Copyright © 2017 vetDevHouse. All rights reserved.
//
//import Foundation
import UIKit
protocol ReusableView: class {
}
extension ReusableView where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
<file_sep>/DreamLister/DreamLister/ItemType+CoreDataClass.swift
//
// ItemType+CoreDataClass.swift
// DreamLister
//
// Created by <NAME> on 8/6/17.
// Copyright © 2017 AppCoda. All rights reserved.
//
import Foundation
import CoreData
//@objc(ItemType)
public class ItemType: NSManagedObject {
}
<file_sep>/Generics.playground/Contents.swift
//: Playground - noun: a place where people can play
import UIKit
//print("Wow this is slow!")
func intAdder(number: Int) -> Int {
return number + 1
}
intAdder(number: 67)
func genericAdder<T: Strideable>(number: T) -> T {
return number + 1
}
genericAdder(number: 12)
genericAdder(number: 12.4)
func intMultiplier(lhs: Int, rhs: Int) -> Int {
return lhs * rhs
}
intMultiplier(lhs: 2, rhs: 4)
protocol Numeric {
func *(lhs: Self, rhs: Self) -> Self
}
extension Double: Numeric {}
extension Float: Numeric {}
extension Int: Numeric {}
func genericMultiplier<T: Numeric>(lhs: T, rhs: T) -> T {
return lhs * rhs
}
genericMultiplier(lhs: 2.3, rhs: 3)
| df1418a6e2aa0f281e859d4635e35640facd0b80 | [
"Swift",
"Markdown"
] | 9 | Swift | tcowern/iOS-Class | 659fffd1fe8aa1cfdb3d4a8558bac1083c4b2c3f | 3bc6b185053072c6e32b24222b056233e75d308b |
refs/heads/master | <repo_name>sorimachi0414/loopPlayer<file_sep>/src/features/counter/Counter.js
import React, {useRef, useState} from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from "react";
import {timeColoned, toNoteString} from '../../index'
import 'bootstrap/dist/css/bootstrap.min.css';
import {
playThis,shiftActivePosition,shiftQuarterNote, playToneBySoft, switchPlay, fileInput, setClickedPosition,
} from './counterSlice';
import {Container, Row, Col, Button,Overlay} from "react-bootstrap";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPowerOff} from "@fortawesome/free-solid-svg-icons/faPowerOff";
import {faClock} from "@fortawesome/free-regular-svg-icons/faClock";
import {faCaretSquareUp} from "@fortawesome/free-regular-svg-icons/faCaretSquareUp"
import {faCaretSquareDown, faCaretSquareLeft, faKeyboard} from "@fortawesome/free-regular-svg-icons";
import {faCaretSquareRight} from "@fortawesome/free-regular-svg-icons";
//export let player
export function Counter() {
const rowLength=8
const numberOf4n = useSelector((state) => state.counter.numberOf4n)
const activePosition = useSelector((state) => state.counter.activePosition)
const clickedPosition = useSelector((state) => state.counter.clickedPosition)
const quarterNotes = useSelector((state) => state.counter.quarterNotes)
const dispatch = useDispatch();
const audioLength = useSelector((state) => state.counter.musicLength)
const [incrementAmount,setIncrementAmount,keyPosition,setKeyPosition] = useState(0);
const isPlaySynth = useSelector((state) => state.counter.isPlaySynth)
let eachSynthNode = (isPlaySynth)?"my-1":"my-1 collapse"
let button4n=[]
for(let i=0;i<numberOf4n;i++){
//Block Loop
if (i%(rowLength)==0){
button4n.push(
<>
<Col className={"p-1 offset-sm-1"} xs={2} sm={1}>
<button
className={"btn btn btn-outline-dark w-75 my-1 px-1"}
onClick={()=>dispatch(
playThis({a:i,b:i+rowLength})
)
}
>↺8</button>
</Col>
<Col className={"p-1"} xs={2} sm={1}>
<button
className={"btn btn btn-outline-dark w-75 my-1 px-1"}
onClick={()=>dispatch(playThis({a:i,b:i+rowLength/2}))}
>↺4</button>
</Col>
</>
)
}
//Block loop
if(i%(rowLength)!==0 && i%(rowLength/2)==0){
button4n.push(
<Col className={"p-1 offset-2 offset-sm-0"} xs={2} sm={1}>
<button
className={"btn btn-outline-dark w-75 px-1"}
onClick={()=>dispatch(playThis({a:i,b:i+rowLength/2}))}
>↺4</button>
</Col>
)
}
//Quarter Note
let inactiveButtonClass ="btn btn btn-outline-success w-100 h-100 py-1"
let activeButtonClass ="btn btn btn-success w-100 h-100 py-1"
let buttonClass = (activePosition==i) ? activeButtonClass: inactiveButtonClass
button4n.push(
<Col className={"m-0 px-1 h-100"} id='buttonDiv' xs={2} sm={1}>
<Row>
<Col xs={12}>
<button
className={buttonClass+" px-0 px-sm-0"}
onClick={()=>dispatch(playThis({a:i,b:i+1}))}
><span style={{"font-size":1.5+"em"}}>{i+1}</span></button>
</Col>
<Col id="eachNode" className={eachSynthNode} xs={12}>
<button
className={"btn btn-outline-secondary w-75 py-0 rounded-0"}
onClick={()=>dispatch(shiftQuarterNote({position:i,shift:1}))}
> {"∧"} </button>
<button
className={"btn btn-outline-secondary w-75 py-0 rounded-0 px-0"}
onClick={()=>dispatch(playToneBySoft(quarterNotes[i]))}
> {toNoteString(quarterNotes[i])} </button>
<button
className={"btn btn-outline-secondary w-75 py-0 rounded-0"}
onClick={()=>dispatch(shiftQuarterNote({position:i,shift:-1}))}
> {"∨"} </button>
</Col>
</Row>
</Col>
)
}
let rowButton4n=[]
for(let i=0;i<button4n.length;i++){
let actualRowLength = rowLength + 2
let n=~~(i/actualRowLength)
if(i%(actualRowLength)==0) rowButton4n[n]=[]
rowButton4n[n].push(
button4n[i]
)
}
let allRowButton4n=[]
for(let i=0;i<rowButton4n.length;i++){
let secOfBar = Math.floor(audioLength*(i*rowLength)/numberOf4n)
let timeString = timeColoned(secOfBar)
allRowButton4n.push(
<Col xs={12} className={"px-sm-0 px-4 mx-sm-0 mb-2"} id="ParentOfTimeAndButton">
<Row className={"justify-content-center"} id="row">
<Col xs={12} lg={12} className={"px-sm-0 py-sm-0 text-start offset-sm-2"}>
<FontAwesomeIcon icon={faClock}/>{timeString}-
</Col>
</Row>
<Row xs={12} className={"px-0 mx-0"} id='row2'>
{rowButton4n[i]}
</Row>
</Col>
)
}
//Key Listner
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
return function cleanup() {
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('keyup', handleKeyUp);
};
});
const handleKeyDown = (event) => {
//console.debug("Key event", event);
if (event.code=='Space') {
//dispatch(playThis({a:activePosition,b:activePosition+1}))
dispatch(switchPlay())
event.preventDefault()
}else if (event.code=='ArrowRight') {
dispatch(playThis({a:clickedPosition+1,b:clickedPosition+2}))
dispatch(shiftActivePosition(clickedPosition + 1))
dispatch(setClickedPosition(clickedPosition + 1))
event.preventDefault()
}else if (event.code=='ArrowLeft') {
dispatch(playThis({a:clickedPosition-1,b:clickedPosition}))
dispatch(shiftActivePosition(clickedPosition - 1))
dispatch(setClickedPosition(clickedPosition - 1))
event.preventDefault()
}else if (event.code=='ArrowUp') {
dispatch(shiftQuarterNote({position:clickedPosition,shift:1}))
//dispatch(shiftActivePosition(activePosition - 1))
event.preventDefault()
}else if (event.code=='ArrowDown') {
dispatch(shiftQuarterNote({position:clickedPosition,shift:-1}))
//dispatch(shiftActivePosition(activePosition - 1))
event.preventDefault()
}
//dispatch(handleKeyInput(game_state, connection_status, event.key));
document.removeEventListener('keydown', handleKeyDown);
};
const handleKeyUp = (event) => {
console.log(1)
document.addEventListener('keydown', handleKeyDown, {once: true});
event.preventDefault()
};
//FIFO
const uploadFile = React.createRef();
//const file = uploadFile.current.files[0];
return (
<div className={"mb-5"}>
<Container className={"justify-content-center mb-4"}>
<Row id="intro" className={"text-left justify-content-center bg-success text-light mb-2 p-2"}>
<Col xs={12} sm={"auto"} className={" align-self-center"}>
<FontAwesomeIcon
icon={faPowerOff}
size={"1.4rem"}
/>
<span className={"fw-bold px-2"} style={{fontSize:"1.2rem"}}>
Get started
</span>
</Col>
<Col xs={12} sm={6} className={""}>
<Row>
<Col xs={12} className={" "}>
Load your music file. Or you can test sample music file
</Col>
<Col xs={12} className={""}>
<input
type="file"
ref={uploadFile}
onChange={()=>dispatch(fileInput(uploadFile))}
/>
</Col>
<Col xs={12} style={{"letterSpacing":"0.02rem"}}>
You can use Arrow Keys
<FontAwesomeIcon
icon={faCaretSquareLeft}
style={{"margin-left":"0.3rem"}}
/>
<FontAwesomeIcon
icon={faCaretSquareUp}
style={{"margin-left":"0.3rem"}}
/>
<FontAwesomeIcon
icon={faCaretSquareDown}
style={{"margin-left":"0.3rem"}}
/>
<FontAwesomeIcon
icon={faCaretSquareRight}
style={{"margin-left":"0.3rem"}}
/>
</Col>
</Row>
</Col>
</Row>
<Row className={"justify-content-center"}>
<Col xs={12} sm={12} lg={10} className={"px-0 mx-0"}>
<Row>
{allRowButton4n}
</Row>
</Col>
</Row>
<Row className={"my-5"}>
<Col></Col>
</Row>
</Container>
</div>
);
}
<file_sep>/src/features/footer/Footer.js
import {faPause, faPauseCircle, faPlay, faPlayCircle, faStepBackward} from "@fortawesome/free-solid-svg-icons";
import {useDispatch, useSelector} from "react-redux";
import {Col, Container, Overlay, Row} from "react-bootstrap";
import {
changeBpm, changeExpandAfter,
changeExpandBefore,
changeSpeed,
changeVolume,
changeWait, moveSeek,
switchLoop, switchPlay, switchPlayBySeek,
switchPlaySynth
} from "../counter/counterSlice";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faVolumeUp} from "@fortawesome/free-solid-svg-icons/faVolumeUp";
import * as Tone from "tone";
import React, {useRef, useState} from "react";
import {faCogs} from "@fortawesome/free-solid-svg-icons/faCogs";
import {timeColoned} from "../../index";
let lastClick=0
let tempo = 100
let fontObject =(min,nom,max)=> {
let result = {
"font-size":`clamp(${min}rem,${nom}vw,${max}rem)`}
return result
}
const ChangeSpeed=()=>{
const dispatch = useDispatch();
const speed = useSelector((state) => state.counter.speed)
return(
<Row>
<Col className={""}>
<span
className="input-group-text px-1" id="inputGroup-sizing-sm"
>
Speed Rate
</span>
</Col>
<Col>
<input
type="number"
className="form-control p-1"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={speed}
type="number"
step='0.25'
max={1}
min={0.5}
onChange={(e) => dispatch(changeSpeed(e.target.value))}
/>
</Col>
</Row>
)
}
const InputCuePoint=()=>{
const dispatch = useDispatch();
const wait = useSelector((state) => state.counter.wait)
return(
<Row>
<Col className={""}>
<span
className="input-group-text px-1" id="inputGroup-sizing-sm"
>
Cue point [s]
</span>
</Col>
<Col>
<input
type="number"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={wait}
type="number"
step='0.1'
onChange={(e) => dispatch(changeWait(e.target.value))}
/>
</Col>
</Row>
)
}
const Volume=()=>{
const dispatch = useDispatch();
const volume = useSelector((state) => state.counter.volume)
return(
<Row className={"px-0"}>
<Col className={"col-auto px-0"}>
<span
style={{
...fontObject(0.5,2,1),
color:"#ccc",
}}
className="input-group-text px-2"
id="inputGroup-sizing-sm"
>.
<FontAwesomeIcon
icon={faVolumeUp}
size={"1x"}
color={"#888"}
/>
</span>
</Col>
<Col xs={"auto px-0"}>
<input
type="number"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={volume}
type="number"
max={100}
min={0}
step='10'
style={fontObject(0.5,2,1)}
onChange={(e) => dispatch(changeVolume(e.target.value))}
/>
</Col>
</Row>
)
}
const InputBPM=()=>{
const dispatch = useDispatch();
const bpm=useSelector((state) => state.counter.bpm)
return(
<Row className={""}>
<Col className={"col-auto px-0"}>
<TapTempo />
</Col>
<Col xs={"auto px-0"}>
<input
type="number"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={bpm}
value={bpm}
size={3}
style={{
maxWidth:"5rem",
...fontObject(0.5,2,1)
}}
onChange={(e) => dispatch(changeBpm(e.target.value))}
/>
</Col>
</Row>
)
}
const TapTempo=()=>{
const dispatch = useDispatch();
let calcTempo=()=>{
let lastTempo = tempo
let thisClick = Tone.now()
let interval = thisClick - lastClick
interval = (interval<12) ? interval : 12
let newTempo = 60 / interval
tempo = Math.round((lastTempo+newTempo)/2)
lastClick = thisClick
return tempo
}
return(
<button
className={"btn btn-outline-secondary mx-0 px-1"}
type="button"
id="button-addon1"
style={fontObject(0.5,2,1)}
onClick={() =>{
tempo = calcTempo()
dispatch(changeBpm(tempo))
}
}
>BPM(Tap)</button>
)
}
let ToggleLoop=()=>{
const dispatch = useDispatch();
const isLoop = useSelector((state) => state.counter.isLoop)
return(
<div className={"text-start"}>
<input
className={"form-check-input m-1"}
id={'loop'}
type="checkbox"
name="inputNames"
checked={isLoop}
onChange={() => dispatch(switchLoop())}
value={0}
/>
<label
className={"form-check-label text-left ms-1"}
htmlFor={"loop"}
style={fontObject(0.5,2,1)}
>
Loop
</label>
</div>
)
}
const ToggleSynth=()=>{
const dispatch = useDispatch();
const isPlaySynth = useSelector((state) => state.counter.isPlaySynth)
return(
<div className={"text-start"}>
<input
className={"form-check-input m-1"}
id={'synth'}
type="checkbox"
name="inputNames"
checked={isPlaySynth}
onChange={() => dispatch(switchPlaySynth())}
value={0}
/>
<label
className={"form-check-label ms-1"}
htmlFor={"synth"}
style={fontObject(0.5,2,1)}
>
Soft piano
</label>
</div>
)
}
const PopContent =()=> {
const dispatch = useDispatch();
const [show, setShow] = useState(false);
const target = useRef(null);
return (
<>
<a tabIndex={0} className={"btn btn-outline-dark p-1 p-sm-2"} ref={target} onClick={() => setShow(!show)}>
<FontAwesomeIcon
icon={faCogs}
style={{
fontSize:"clamp(1rem,5vw,2rem)",
}}
color={"#888"}
/>
</a>
<Overlay
target={target.current}
show={show}
placement="top"
>
{({ placement, arrowProps, show: _show, popper, ...props }) => (
<Container>
<Row>
<Col
{...props}
style={{
backgroundColor: 'rgba(255,255,255, 0.9)',
padding: '',
color: 'black',
borderRadius: 3,
border:"solid 1px #000",
maxWidth:'50%',
...props.style,
}}
className={"mb-2"}
xs={7}
sm={6}
md={4}
lg={3}
xl={2}
>
<Row>
<Col className={"text-start"}>
<b>Additional Settings</b>
</Col>
<Col xs={12} className={""}>
<Row className={"px-2"}>
<Col xs={12}>
Expand play range.
</Col>
<Col xs={"auto"} id={"1ofRow"}>
<Row>
<Col>
<span
className="input-group-text px-1" id="inputGroup-sizing-sm">
Before [s]
</span>
</Col>
<Col >
<input
type="number"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={0}
type="number"
step='0.1'
min={0}
onChange={(e) => dispatch(changeExpandBefore(e.target.value))}
/>
</Col>
</Row>
</Col>
<Col xs={"auto"} className={"pb-2"}>
<Row>
<Col className={""}>
<span
className="input-group-text px-1" id="inputGroup-sizing-sm">
After [s]
</span>
</Col>
<Col>
<input
type="number"
className="form-control"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
defaultValue={0}
type="number"
step='0.1'
min={0}
onChange={(e) => dispatch(changeExpandAfter(e.target.value))}
/>
</Col>
</Row>
</Col>
<Col xs={12}>
Change the beginning point.
</Col>
<Col xs={"auto"} className={"pb-2"}>
<InputCuePoint />
</Col>
<Col xs={12}>
Slow down the music speed.
0.5/ 0.75/ 1.0
</Col>
<Col xs={"auto"} className={"pb-2"}>
<ChangeSpeed />
</Col>
</Row>
</Col>
</Row>
</Col>
</Row>
</Container>
)}
</Overlay>
</>
);
}
export function Footer() {
const dispatch = useDispatch();
const numberOf4n = useSelector((state) => state.counter.numberOf4n)
const activePosition = useSelector((state) => state.counter.activePosition)
const audioLength = useSelector((state) => state.counter.musicLength)
const isPlay = useSelector((state) => state.counter.isPlay)
//const [incrementAmount,setIncrementAmount,keyPosition,setKeyPosition] = useState(0);
let playStopLabel = (isPlay) ? faPause : faStepBackward
let globalPlayStopLabel =(isPlay)? faPauseCircle:faPlayCircle
return(
<Container className={"mt-4"} id={"footer"}>
<Row className="navbar navbar-light bg-light fixed-bottom">
<Col className="offset-sm-0 offset-md-0 offset-lg-0" xs={12} sm={12} md={12}>
<Row className="px-1 mx-0 justify-content-center">
<Col xs={2} sm={2} md={1} id={'resumeButton'}>
<FontAwesomeIcon
icon={globalPlayStopLabel}
style={{
fontSize:"clamp(2rem,10vw,4rem)",
}}
color={"#0077ff"}
onClick={()=>dispatch(switchPlay())}
/>
</Col>
<Col xs={5} sm={5} md={3} lg={4} className={"mb-2"}>
<div>
<input
id="typeinp"
type="range"
className={""}
style={{'width':100+'%'}}
min="0"
max="100"
defaultValue={activePosition}
value={activePosition/numberOf4n*100}
//onChange={(e)=>console.debug(e)}
onChange={(e)=>dispatch(moveSeek(Math.floor(numberOf4n*Number(e.target.value)/100)))}
step="1"
/>
</div>
<div>
<button
className={"btn btn-outline-dark p-1"}
onClick={()=>dispatch(switchPlayBySeek())}
>
<FontAwesomeIcon
icon={playStopLabel}
color={"#179317"}
size={"2x"}
style={fontObject(1,3,2)}
className={"my-0 py-0 mx-1"}
/>
</button>
<span
style={{
marginLeft: 5 + "px",
...fontObject(0.1,4,0.8)
}}
>
{timeColoned(audioLength*activePosition/numberOf4n)}
{" / "}
{timeColoned(audioLength)}
</span>
</div>
</Col>
<Col xs={3} sm={3} md={2} className={"form-check form-switch text-left px-0"}>
<ToggleLoop />
<ToggleSynth />
</Col>
<Col xs={"auto"} sm={4} md={3} lg={2} className={" order-2 order-md-1"}>
<InputBPM />
</Col>
<Col xs={"auto"} sm={4} md={2} lg={2} className={" order-3 order-md-2"}>
<Volume />
</Col>
<Col xs={2} sm={2} md={1} lg={1} className={" p-0 order-1 order-md-3"}>
<PopContent />
</Col>
</Row>
</Col>
</Row>
</Container>
)
}<file_sep>/src/features/counter/counterSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { fetchCount } from './counterAPI';
import {
newPlayer,
synth,
toNoteString,
playMusic,
resumeTest, setSlicedBuffers, originalBuffer,
} from '../../index'
import * as Tone from 'tone'
const initialState = {
activePosition:0,
clickedPosition:0,
isLoop:true,
isPlaySynth:false,
loaded:0,
value: 0,
bpm:90,
wait:0,
expandBefore:0,
expandAfter:0,
musicLength:0,
numberOf4n:3,
quarterNotes:[],
speed:1.0,
volume:50,
lastStartPoint:0,
lastEndPoint:0,
};
export const incrementAsync = createAsyncThunk(
'counter/fetchCount',
async (amount) => {
const response = await fetchCount(amount);
// The value we return becomes the `fulfilled` action payload
return response.data;
}
);
export const counterSlice = createSlice({
name: 'counter',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
setIsPlay:(state,action)=>{
state.isPlay=action.payload
},
playThis:(state,action)=>{
state.isPlay=true
let startStep = action.payload.a
let endStep = action.payload.b
state.activePosition = startStep
state.clickedPosition = startStep
playMusic(startStep, endStep)
state.lastStartPoint = startStep
state.lastEndPoint = endStep
},
changeSpeed:(state,action)=>{
let rate = action.payload
state.speed = rate
let shift=0
if (rate<=0.5){
rate=0.5
shift=12
}else if (rate<=0.75){
rate=0.75
shift=5
}else if(rate<1.5){
rate=1.0
shift=0
}else if(rate<=1.75){
rate=1.5
shift=-7
}else{
rate=2.0
shift=-12
}
newPlayer.playbackRate = rate
let shifter = new Tone.PitchShift({
pitch:shift,
windowSize:0.1,
}).toDestination()
newPlayer.disconnect()
newPlayer.connect(shifter)
},
switchPlayBySeek:(state,action)=>{
if (newPlayer.state=='stopped') {
playMusic(0,state.numberOf4n)
state.isPlay=true //slicerで変えないとエラーが出る時が。
}else{
resumeTest()
state.isPlay=false
}
},
moveSeek:(state,action)=>{
state.activePosition = action.payload
state.clickedPosition = action.payload
playMusic(action.payload,state.numberOf4n)
state.isPlay=true
},
switchPlay:(state)=>{
if (newPlayer.state=='stopped'){
//停止中
playMusic(state.activePosition,state.numberOf4n)
state.isPlay=true //slicerで変えないとエラーが出る時が。
}else{
//再生中
resumeTest()
state.isPlay=false
}
},
build:(state,action)=>{
let musicLength = action.payload
state.musicLength = musicLength
let numberOf4n = Math.ceil(musicLength * state.bpm /60)
state.numberOf4n = numberOf4n
state.loaded=1
for(let i=0;i<numberOf4n;i++){
state.quarterNotes.push(36)
}
Tone.Transport.bpm.value=state.bpm
},
changeBpm:(state,action)=>{
let bpm = Number(action.payload)
bpm = (bpm<1) ? 1 : bpm
bpm = (bpm>999) ? 999 : bpm
state.bpm=bpm
setSlicedBuffers(
originalBuffer,
state.expandBefore,
state.expandAfter,
state.wait,
bpm,
)
state.numberOf4n = Math.ceil(state.musicLength * state.bpm /60)
Tone.Transport.bpm.value=bpm
},
changeWait:(state,action)=>{
state.wait=Number(action.payload)
setSlicedBuffers(
originalBuffer,
state.expandBefore,
state.expandAfter,
Number(action.payload),
state.bpm,
)
playMusic(state.lastStartPoint,state.lastEndPoint)
//reBuild
let musicLength = state.musicLength-Number(action.payload)
let numberOf4n = Math.ceil(musicLength * state.bpm /60)
state.numberOf4n = numberOf4n
state.loaded=1
for(let i=0;i<numberOf4n;i++){
state.quarterNotes.push(36)
}
},
changeVolume:(state,action)=>{
let vol = Number(action.payload)
state.volume=vol
let dB = -36 + 36*vol/100
dB =(vol==0) ? -100:dB
dB =(dB>0) ? 0 : dB
newPlayer.volume.value=dB
},
changeExpandBefore:(state,action)=>{
state.expandBefore=Number(action.payload)
setSlicedBuffers(
originalBuffer,
Number(action.payload),
state.expandAfter,
state.wait,
state.bpm,
)
playMusic(state.lastStartPoint,state.lastEndPoint)
},
changeExpandAfter:(state,action)=>{
state.expandAfter=Number(action.payload)
setSlicedBuffers(
originalBuffer,
state.expandBefore,
Number(action.payload),
state.wait,
state.bpm,
)
playMusic(state.lastStartPoint,state.lastEndPoint)
},
secToActivePosition:(state,action)=>{
let sec = action.payload
state.activePosition = Math.floor(state.numberOf4n * sec / state.musicLength)
},
setClickedPosition:(state,action)=>{
state.clickedPosition = action.payload
},
shiftActivePosition:(state,action)=>{
state.activePosition=action.payload
state.activePosition = (state.activePosition<0) ? 0: (state.activePosition>=state.numberOf4n) ? state.numberOf4n-1 : state.activePosition
},
shiftQuarterNote:(state,action)=>{
let i = action.payload.position
let shift = action.payload.shift
state.quarterNotes[i] = state.quarterNotes[i]+shift
let note = toNoteString(state.quarterNotes[i]+shift)
synth.triggerAttackRelease(note, "8n");
},
playToneBySoft:(state,action)=>{
let note = toNoteString(action.payload)
if (state.isPlaySynth) synth.triggerAttackRelease(note, "8n");
//sub function
},
playActiveToneBySoft:(state,action)=>{
let note = toNoteString(state.quarterNotes[state.activePosition])
//if (state.isPlaySynth) synth.triggerAttackRelease(note, "8n",action.payload);
},
switchLoop:(state)=>{
state.isLoop = !state.isLoop
},
switchPlaySynth:(state)=>{
state.isPlaySynth = !state.isPlaySynth
},
fileInput:(state,action)=>{
console.debug(action.payload)
let file = action.payload.current.files[0]
console.log(file)
let blob = URL.createObjectURL(file)
newPlayer.load(blob)
}
},
});
export const {
increment,
decrement,
incrementByAmount,
initPlayer,
playFull,
build,
playThis,
changeBpm,
changeWait,
changeExpandBefore,
changeExpandAfter,
shiftActivePosition,
shiftQuarterNote,
playToneBySoft,
switchPlay,
playActiveToneBySoft,
switchLoop,
switchPlaySynth,
fileInput,
playBySeek,
switchPlayBySeek,
secToActivePosition,
moveSeek,
changeSpeed,setClickedPosition,
changeVolume,setSeq,newTest,testSwitch,setIsPlay,clickedPosition,
} = counterSlice.actions;
export default counterSlice.reducer;
<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { store } from './app/store';
import {Provider} from 'react-redux';
import * as serviceWorker from './serviceWorker';
import * as Tone from 'tone'
import music from "./bensound-happyrock.mp3"
import {build,shiftActivePosition,} from "./features/counter/counterSlice";
// ///////////////////////////////////
// Explain a method of play music
// when onLoaded cut whole audio buffer to "4n" length of buffers
// when push a button, tiny length of buffer is played
// after buffer has played, soft synth is also play by scheduleRepeat callback
// ///////////////////////////////////
//Tone.js------------------------------
let musicLength=0
let slicedBuffers=[]
let slicedBuffers4=[]
let slicedBuffers8=[]
export let setSlicedBuffers=(
buf,
expandBefore = store.getState().counter.expandBefore,
expandAfter = store.getState().counter.expandAfter,
wait = store.getState().counter.wait,
bpm = store.getState().counter.bpm,
)=>{
let length = buf.duration
let step = 60/bpm
let buffers=[]
let buffers4=[]
let buffers8=[]
let sp=0+wait
let ep=step+wait
let bufIdx=0
while(ep<musicLength+step){
let spEx = sp-expandBefore
let epEx = ep+expandAfter
let ep4Ex= ep+3*step+expandAfter
let ep8Ex= ep+7*step+expandAfter
spEx = (spEx<0) ? 0 : (spEx>length) ? length :spEx
epEx = (epEx<0) ? 0 : (epEx>length) ? length :epEx
ep4Ex = (ep4Ex<0) ? 0 : (ep4Ex>length) ? length :ep4Ex
ep8Ex = (ep8Ex<0) ? 0 : (ep8Ex>length) ? length :ep8Ex
if(spEx>=epEx) spEx =sp
buffers[bufIdx]= buf.slice(spEx,epEx)
if(bufIdx%8===0) buffers8[bufIdx] = buf.slice(spEx,ep8Ex)
if(bufIdx%4===0) buffers4[bufIdx] = buf.slice(spEx,ep4Ex)
sp+=step
ep+=step
bufIdx+=1
}
slicedBuffers=buffers
slicedBuffers8=buffers8
slicedBuffers4=buffers4
}
export let originalBuffer
let musicOnLoad=()=>{
musicLength = newPlayer.buffer.duration
setSlicedBuffers(newPlayer.buffer)
originalBuffer = newPlayer.buffer.slice(0,musicLength)
store.dispatch(build(musicLength))
}
//主音源再生用のオブジェクト
export const newPlayer = new Tone.Player(music,()=>musicOnLoad()).toDestination();
newPlayer.loop = false;
newPlayer.autostart = false;
newPlayer.volume.value=-18
export let synthScore=[]
//get score from state
let score,isLoop,isPlaySynth,expandBefore,expandAfter,wait,bpm,activePosition
let reloadState=()=>{
//Call back of state change
let counter = store.getState().counter
isLoop = counter.isLoop
isPlaySynth = counter.isPlaySynth
expandBefore = counter.expandBefore
expandAfter = counter.expandAfter
wait = counter.wait
bpm = counter.bpm
activePosition = counter.activePosition
let rawScore = counter.quarterNotes
score = rawScore.map(x=>toNoteString(x))
}
store.subscribe(reloadState)
newPlayer.loop=false
//let loop = new Tone.Loop(()=>{},60/90)
let subCallBack=()=>{}
let loop = new Tone.Loop((time)=>{
newPlayer.start(time)
subCallBack(time)
}, "2")//.start()
//Audio context error
newPlayer.context._context.resume()
newPlayer.context.resume()
loop.context._context.resume()
loop.context.resume()
let resumed = false
export const playMusic = (startStep, endStep)=>{
//This block is a key of sound delay. You should reduce the delay. Below is one of the solutions.
if(endStep===startStep) return "Abnormal called"
let nowStep = startStep
//0.005 object 0.05 now =>0.005 without constructor
loop.cancel()
newPlayer.buffer = slicedBuffers[nowStep]
loop.interval=newPlayer.buffer.duration
if(!resumed){
loop.context.resume()
resumed=true
}
loop.start()
subCallBack=(time)=>{
let synthNoteDuration =0.3
if (isPlaySynth) synth.triggerAttackRelease(score[nowStep], synthNoteDuration, time);
store.dispatch(shiftActivePosition(nowStep))
//次のステップをセット
nowStep = (nowStep+1<endStep) ?nowStep+1 : startStep;
newPlayer.buffer = slicedBuffers[nowStep]
}
Tone.Transport.start()
}
export const resumeTest=()=>{
if(newPlayer.state==="stopped"){
Tone.Transport.start()
newPlayer.start() //is this needed?
}else {
Tone.Transport.stop()
newPlayer.stop() //is this needed?
}
}
export const synth = new Tone.Synth().toDestination();
synth.volume.value=0
export const toNoteString=(num)=>{
// 24 = C2
// noteNumber = noteSymbol + noteHeight
const toToneLetter=['C','C#','D','D#','E','F','F#','G','G#','A','A#','B',]
let noteNumber=num
let noteSymbol = toToneLetter[noteNumber%12]
let noteHeight = ~~(noteNumber/12)
return String(noteSymbol)+String(noteHeight)
}
export const timeColoned =(sec)=>{
// 105 -> 1:45
let date = new Date(null);
date.setSeconds(sec); // specify value for SECONDS here
if(Number.isNaN(date.getTime())){
//to avoid a case date = Invalid Date
return 0
}
return date.toISOString().substr(14, 5);
}
//------------
require('react-dom');
window.React2 = require('react');
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
| 10ac5b6ea0bd45942b905ab851f48bce052206f4 | [
"JavaScript"
] | 4 | JavaScript | sorimachi0414/loopPlayer | 3e7badeb061905a8a3754a8060e03b4b826af34e | 5f198803464dc5505d8248f6db3bd9f8ee9162f8 |
refs/heads/master | <file_sep>return "<img>" | 89f9da7ab2dc546e5beaa1f6bc002ea065384c8e | [
"JavaScript"
] | 1 | JavaScript | claria4u/testo | acd3a8aebe15e026e1c5afc09928dbab98a19bf5 | c1b85c79c6fcf7188b0c6896b8a1538d0e95ee89 |
refs/heads/master | <repo_name>yutamiyauchi/location-share<file_sep>/docker-compose.yml
version: '3'
services:
web:
image: nginx:1.15.6
ports:
- "8000:80"
depends_on:
- app
volumes:
- ./docker/web/default.conf:/etc/nginx/conf.d/default.conf
- ./:/var/www/
app:
build:
context: .
dockerfile: ./docker/php/Dockerfile
depends_on:
- mysql
volumes:
- ./:/var/www/
mysql:
image: mysql:5.7
environment:
MYSQL_DATABASE: test
MYSQL_USER: root
MYSQL_PASSWORD: <PASSWORD>
MYSQL_ROOT_PASSWORD: <PASSWORD>
ports:
- "3306:3306"
volumes:
- ./docker/mysql/mysql-data:/var/lib/mysql
workspace:
build: docker/workspace
volumes:
- ./:/var/www/
ports:
- "22:22"<file_sep>/.env.example
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=<PASSWORD>
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
AWS_ACCESS_KEY_ID=$(AWS_ACCESS_KEY_ID)
AWS_SECRET_ACCESS_KEY=$(AWS_SECRET_ACCESS_KEY)
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=$(AWS_BUCKET)
AWS_ECR_ACCOUNT_URL=$(AWS_ECR_ACCOUNT_URL)
AWS_ECS_TASK_NAME=$(AWS_ECS_TASK_NAME)
AWS_ECS_CLUSTER_NAME=$(AWS_ECS_CLUSTER_NAME)<file_sep>/readme.md
<!-- <p align="center"><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></p>
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p> -->
# 災害情報共有サービス DISASTER SHARE
災害時に地域毎の有益な情報を共有し合うことにより、二次被害を防いだり、身を守る行動をより早く取れるようにすることを目的としたサービスです。
<!-- Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as: -->
## URL
URL: [https://www.disaster-share.com](https://www.disaster-share.com)
<!-- - [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting). -->
トップページのログインボタンからログインページに遷移していただき、「ゲストログインボタン」からゲストユーザーとしてログインしアプリをご使用いただけます。こちらのサービスで用いている災害の写真は以下のサイトのものを利用しており、実際に起こった災害とは一切関係がありません。
<br>
災害写真データベース: [http://www.saigaichousa-db-isad.jp/drsdb_photo/photoSearch.do](http://www.saigaichousa-db-isad.jp/drsdb_photo/photoSearch.do)
<!-- Laravel is accessible, yet powerful, providing tools needed for large, robust applications. -->
## アプリ作成の目的
<!-- Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of any modern web application framework, making it a breeze to get started learning the framework.
If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 1100 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library. -->
私は大学時代に自然災害をはじめとする災害の被害最小化について学んできました。 その中で、災害が起こった後の二次被害(地震後の津波、大雨の後の土砂崩れなど)により命を落としたり、怪我を負ってしまう方が自分の想像よりも多くいることを知ります。 そこで、二次災害が起きる前にその情報を共有できれば被害を減少させられるのではないか、自分にも災害の被害を最小化し、いち早く安全安心な暮らしへ復興するためにできることがあるのではないか?と考え本サービスを作成しました。
<!-- ## 工夫した点
・無限コメント機能
・CI/CDパイプラインの構築 -->
## 機能一覧
### ユーザー機能
- ユーザー登録・編集・削除
- 一覧表示
- ゲストログイン
- プロフィール画像の登録・編集
- マイページにて以下の投稿の一覧表示
- 全ての自分の投稿
- フォローしたユーザー
- フォロワー
- お気に入りに追加した投稿
### 投稿機能
- 投稿(画像, タイトル, メッセージ, 都道府県・市区町村, 場所, 位置情報)・編集・削除
- 一覧表示、詳細表示
- 地図表示(Google Maps API)
- お気に入り追加(いいね数のカウント, 非同期)
- 検索(キーワード検索・メニュー検索)
- 場所一覧
### コメント機能
- 投稿(コメント対しコメントが延々とできる, 非同期)
- コメントの表示(同一スレッド上にある直前・直後のコメントを表示可能, 非同期)
- 削除(非同期)
### フォロー機能
- ユーザーのフォロー・フォロー解除(非同期)
- フォロー中のユーザーとフォロワーの一覧表示
### その他
- レスポンシブ対応
- テスト
<!-- ## Laravel Sponsors -->
## 使用技術
### フロント
- HTML
- CSS
- JavaScript
- jQuery(Ajax)
- bootstrap
### バックエンド
- PHP 7.2.33
- Laravel 6.18.40
### サーバー
- Nginx
- PHP-FPM
### DB
- MySQL 8.0.19
### インフラ・開発環境等
- AWS(ACM,EC2,ALB,ECR,ECS,RDS,Route53,VPC,S3)
- Docker/docker-compose
- CircleCI(CI/CD)
### その他
- Google API
- PHPUnit
- Larastan
<!-- We would like to extend our thanks to the following sponsors for helping fund on-going Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell): -->
<!-- - **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[British Software Development](https://www.britishsoftware.co)**
- [Fragrantica](https://www.fragrantica.com)
- [SOFTonSOFA](https://softonsofa.com/)
- [User10](https://user10.com)
- [Soumettre.fr](https://soumettre.fr/)
- [CodeBrisk](https://codebrisk.com)
- [1Forge](https://1forge.com)
- [TECPRESSO](https://tecpresso.co.jp/)
- [Pulse Storm](http://www.pulsestorm.net/)
- [Runtime Converter](http://runtimeconverter.com/)
- [WebL'Agence](https://weblagence.com/) -->
## インフラ構成図
<img width="618" alt="AWS構成図" src="https://user-images.githubusercontent.com/47106952/96061588-94f3f580-0ece-11eb-8afc-2f7db68f278e.png">
<!-- ## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to <NAME> via [<EMAIL>](mailto:<EMAIL>). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). -->
<file_sep>/app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use Auth;
use Hash;
use DB;
use App\Http\Requests\StoreUser;
use App\User; // 追加
class UsersController extends Controller
{
public function index()
{
$users = User::orderBy('id', 'desc')->paginate(10);
return view('users.index', [
'users' => $users,
]);
}
public function show($id)
{
$user = User::find($id);
$alerts = $user->alerts()->orderBy('created_at', 'desc')->paginate(8);
$data = [
'user' => $user,
'alerts' => $alerts,
];
$data += $this->counts($user);
return view('users.show', $data);
}
public function destroy($id)
{
$user = User::find($id);
if(Auth::id() ==1){
return back()->with('error', 'ゲストユーザーは退会することができません。');
}
$user->delete();
return back();
}
public function followings($id)
{
$user = User::find($id);
$followings = $user->followings()->paginate(10);
$data = [
'user' => $user,
'users' => $followings,
];
$data += $this->counts($user);
return view('users.followings', $data);
}
public function followers($id)
{
$user = User::find($id);
$followers = $user->followers()->paginate(10);
$data = [
'user' => $user,
'users' => $followers,
];
$data += $this->counts($user);
return view('users.followers', $data);
}
public function favorites($id)
{
$user = User::find($id);
$favorites = $user->favorites()->paginate(10);
$data = [
'user' => $user,
'alerts' => $favorites,
];
$data += $this->counts($user);
return view('users.favorites', $data);
}
public function edit($id)
{
$user = Auth::user();
return view('users.edit',[ 'user' => $user ]);
}
public function update(StoreUser $request, $id)
{
$user = User::find($id);
if($request->email !== $user->email){
if(DB::table('users')->where('email', $request->email)->exists()){
return back()->with('error', 'そのメールアドレスは既に使用されています。');
}
}{
$filename='';
$url='';
if( request()->hasFile('thefile')){
//画像ファイル受け取り処理
if (request()->file('thefile')->isValid()) {
$filename = $request->file('thefile')->store('img');
//s3アップロード開始
$image = $request->file('thefile');
// バケットの`pogtor528`フォルダへアップロード
$path = Storage::disk('s3')->putFile('pogtor528', $image, 'public');
// アップロードした画像のフルパスを取得
$url = Storage::disk('s3')->url($path);
}
$user->introduction = $request->introduction;
$user->image = $url;
if($id !==1){
$user->name = $request->name;
$user->email = $request->email;
if($request->password !== null){
if(Hash::check($request->current_password, $user->password)){
$user->password = Hash::make($request->password);
}
else{
return back()->with('error', '現在のパスワードが間違っています。');
}
}
}
else if($request->password !== null){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else if($user->name !== $request->name){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else if($user->email !== $request->email){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else{
$user->name = $request->name;
$user->email = $request->email;
}
$user->save();
}
else{
$user->introduction = $request->introduction;
if(Auth::id() !==1){
$user->name = $request->name;
$user->email = $request->email;
if($request->password !== null){
if(Hash::check($request->current_password, $user->password)){
$user->password = Hash::make($request->password);
}
else{
return back()->with('error', '現在のパスワードが間違っています。');
}
}
}
else if($request->password !== null){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else if($user->name !== $request->name){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else if($user->email !== $request->email){
return back()->with('error', 'ゲストユーザーは氏名, メールアドレス, パスワードの変更ができません。');
}
else{
$user->name = $request->name;
$user->email = $request->email;
}
$user->save();
}
return redirect()->route('users.show', [Auth::id()]);
}
}
}
<file_sep>/app/Http/Controllers/AlertsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Alert;
use App\Alertcomment;
use Storage;
use App\Http\Requests\StoreAlert;
use App\User;
class AlertsController extends Controller
{
// getでalerts/にアクセスされた場合の「一覧表示処理」
public function index()
{
$data = [];
if (\Auth::check()) {
$user = \Auth::user();
$alerts = Alert::orderBy('created_at', 'desc')->paginate(9);
$data = [
'user' => $user,
'alerts' => $alerts,
];
}
return view('alerts.index', $data);
}
// getでalerts/createにアクセスされた場合の「新規登録画面表示処理」
public function create()
{
$alert = new Alert;
return view('alerts.create', [
'alert' => $alert,
]);
}
// postでalerts/にアクセスされた場合の「新規登録処理」
public function store(StoreAlert $request)
{
//画像ファイル受け取り処理
$filename='';
$url='';
if ($request->file('thefile')->isValid()) {
$filename = $request->file('thefile')->store('img');
//s3アップロード開始
$image = $request->file('thefile');
// バケットの`pogtor528`フォルダへアップロード
$path = Storage::disk('s3')->putFile('pogtor528', $image, 'public');
// アップロードした画像のフルパスを取得
$url = Storage::disk('s3')->url($path);
}
//時間のセット
date_default_timezone_set('Asia/Tokyo');
$now = date("Y/m/d H:i");
$request->user()->alerts()->create([
'content' => $request->content,
'title' => $request->title,
'area' => $request->area,
'city' => $request->city,
'location' => $request->location,
'time' => $now,
'image' => $url,
'lat' => $request->lat,
'lng' => $request->lng,
]);
return redirect('/alerts');
}
// getでalerts/idにアクセスされた場合の「取得表示処理」
public function show($id)
{
$alert = Alert::find($id);
$user = \Auth::user();
$alertcomments = Alertcomment::where('alert_id', $id)->orderBy('created_at', 'desc')->get();
$data = [
'alert' => $alert,
'user' => $user,
'alertcomments' => $alertcomments,
];
return view('alerts.show', $data);
}
public function update(StoreAlert $request, $id)
{
//画像ファイル受け取り処理
$filename='';
$url='';
if ($request->file('thefile')->isValid()) {
$filename = $request->file('thefile')->store('img');
//s3アップロード開始
$image = $request->file('thefile');
// バケットの`pogtor528`フォルダへアップロード
$path = Storage::disk('s3')->putFile('pogtor528', $image, 'public');
// アップロードした画像のフルパスを取得
$url = Storage::disk('s3')->url($path);
}
//時間のセット
date_default_timezone_set('Asia/Tokyo');
$now = date("Y/m/d H:i");
$alert = Alert::find($id);
$alert->content = $request->content;
$alert->title = $request->title;
$alert->area = $request->area;
$alert->city = $request->city;
$alert->location = $request->location;
$alert->time = $now;
$alert->image = $url;
$alert->lat = $request->lat;
$alert->lng = $request->lng;
$alert->edit = $request->edit;
$alert->save();
return redirect('/alerts');
}
// getでalerts/id/editにアクセスされた場合の「更新画面表示処理」
public function edit($id)
{
$alert = Alert::find($id);
return view('alerts.edit', [
'alert' => $alert,
]);
}
// deleteでalerts/idにアクセスされた場合の「削除処理」
public function destroy($id)
{
$alert = \App\Alert::find($id);
if (\Auth::id() === $alert->user_id) {
$alert->delete();
}
return back();
}
}
<file_sep>/app/Http/Controllers/Auth/RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Storage;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
protected $redirectTo = '/alerts';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:15',
'email' => 'required|string|email|max:30|unique:users',
'password' => '<PASSWORD>',
'introduction' =>'nullable|max:140',
'thefile' => [
'nullable',
'file',
'image',
'mimes:jpeg,png',
]
]);
}
protected function create(array $data)
{
//画像ファイル受け取り処理
$filename='';
$url='';
if( request()->hasFile('thefile')){
if (request()->file('thefile')->isValid()) {
$filename = request()->file('thefile')->store('img');
//s3アップロード開始
$image = request()->file('thefile');
// バケットの`pogtor528`フォルダへアップロード
$path = Storage::disk('s3')->putFile('pogtor528', $image, 'public');
// アップロードした画像のフルパスを取得
$url = Storage::disk('s3')->url($path);
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => <PASSWORD>($data['<PASSWORD>']),
'image' => $url,
'introduction' => $data['introduction'],
]);
}
else{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => <PASSWORD>($data['<PASSWORD>']),
'introduction' => $data['introduction'],
]);
}
}
}<file_sep>/docker/workspace/Dockerfile
FROM php:7.2.15-fpm
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y \
git \
curl \
vim \
zip \
unzip \
&& apt-get clean
RUN docker-php-ext-install pdo_mysql
RUN curl -s http://getcomposer.org/installer | php && \
echo "export PATH=${PATH}:/var/www/vendor/bin" >> ~/.bashrc && \
mv composer.phar /usr/local/bin/composer
RUN . ~/.bashrc
WORKDIR /var/www/
<file_sep>/docker/web/Dockerfile
FROM alpine:3.6
# nginxのインストール
RUN apk update && \
apk add --no-cache nginx
# ドキュメントルート
ADD ./docker/web/default.conf /etc/nginx/conf.d/default.conf
# ポート設定
EXPOSE 80
RUN mkdir -p /run/nginx
#public追加
RUN mkdir -p /var/www/public
COPY ./public /var/www/public
# フォアグラウンドでnginx実行
CMD nginx -g "daemon off;"
<file_sep>/docker/php/Dockerfile
FROM php:7.2.15-fpm
RUN { \
echo 'max_execution_time=-1'; \
echo 'memory_limit=-1'; \
echo 'post_max_size=-1'; \
echo 'upload_max_filesize=100M'; \
} > /usr/local/etc/php/conf.d/wp-recommended.ini
RUN docker-php-ext-install pdo_mysql
COPY ./ /var/www/
RUN chown -R www-data:www-data /var/www | 4bbff1ba4729bf3d5a1a23d567f8eda8bbc94356 | [
"YAML",
"Markdown",
"PHP",
"Dockerfile",
"Shell"
] | 9 | YAML | yutamiyauchi/location-share | cadcabc5593aee42f9bf8abe48c8c81d02fc8e2c | eea6eb097fbfcfa0d907fc31734066bfad43bc93 |
refs/heads/master | <repo_name>wolfstudy/WatchBTCAddress<file_sep>/README.md
# WatchBTCAddress
By BTC and BCH address can watch any changer
[beego](https://github.com/astaxie/beego)
<file_sep>/controllers/default.go
package controllers
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/astaxie/beego"
"github.com/tidwall/gjson"
"go4.org/sort"
)
type BitcoinSite struct {
Site string
T string
}
type TxInfo struct {
//是否为输入的钱数
IsIN bool
//交易是否被更新过
Updated bool
//交易类型(BTC && BCH)
Type string
//拼接url前缀,调用API文档
TxPrefix string
//地址
AdPrefix string
//tx_hash的值
TxID string
//交易日期
Date string
//交易钱数
Amount float64
}
//需要监控的BTC && BCH的地址,通过地址获取btc.com的数据。
var siteInfo []BitcoinSite = []BitcoinSite{
{"<KEY>", "BTC"},
{"<KEY>", "BTC"},
{"3<KEY>", "BCH"},
{"1<KEY>", "BCH"},
{"<KEY>", "BCH"},
}
type MainController struct {
beego.Controller
}
func (c *MainController) Get() {
var info = make(map[string][]TxInfo)
length := len(siteInfo)
for i := 0; i < length; i++ {
value := siteInfo[i]
var prefix string
//内部端口(BTC && BCH)
if value.T == "BTC" {
prefix = "https://chain.api.btc.com/v3/address/"
} else {
prefix = "https://bch-chain.api.btc.com/v3/address/"
}
//接收获取到的请求,是一个string的字符串
content := getContet(prefix + value.Site)
//gjson解析获取到的json串
hash := gjson.Get(content, "data.list.#.hash").Array()
amount := gjson.Get(content, "data.list.#.inputs_value").Array()
created := gjson.Get(content, "data.list.#.created_at").Array()
inputs := gjson.Get(content, "data.list.#.inputs").Array()
//循环遍历所有的hash值
for index, iterm := range hash {
txinfo := TxInfo{}
if value.T == "BTC" {
txinfo.TxPrefix = "https://btc.com/"
txinfo.AdPrefix = "https://btc.com/"
txinfo.Type = "BTC"
} else {
txinfo.TxPrefix = "https://bch.btc.com/"
txinfo.AdPrefix = "https://bch.btc.com/"
txinfo.Type = "BCH"
}
//money数量
txinfo.Amount = amount[index].Float() / float64(100000000)
//时间戳转时间
tm := time.Unix(created[index].Int(), 0)
txinfo.Date = tm.Format("2006-01-02 15:04:05")
txinfo.TxID = iterm.String()
//判断是否为最新交易
if created[index].Int() > 151489440 {
http.Get("http://v.juhe.cn/sms/send?mobile=18410205081&tpl_id=嫁给我!&tpl_value=%23code%23%3D654654&key=<KEY>c3468683d32338")
txinfo.Updated = true
}
//input adjust
if(!strings.Contains(inputs[index].String(), value.Site)){
txinfo.IsIN = true
}
info[value.Site] = append(info[value.Site], txinfo)
}
}
//用时间+地址拼接为一个字符串,利用时间的有序性,排序。
address := make([]string, 0)
for key, iterm := range info {
address = append(address, iterm[0].Date+key)
}
sort.Strings(address)
l := len(address)
str := make([]string, 0)
//排好序之后,截取后面的地址,这样做的目的是为了规避map结构的无序性。
for i := l - 1; i >= 0; i-- {
str = append(str, address[i][19:])
}
c.Data["str"] = str
c.Data["lists"] = info
c.TplName = "index.html"
}
//获取btc.com网站的数据。
func getContet(url string) string {
get, err := http.Get(url + "/tx")
if err != nil {
fmt.Println(err)
return ""
}
defer get.Body.Close()
content, _ := ioutil.ReadAll(get.Body)
return string(content)
}
| 8bef04fcee9c28b4d5d46795d9feacd0a4d9ed1f | [
"Markdown",
"Go"
] | 2 | Markdown | wolfstudy/WatchBTCAddress | 0686e5ed151e4b12f168b2540ba337d3c94c3f16 | 6606813ee8c226aae1cf63e1c9c168e24647461d |
refs/heads/master | <repo_name>redlocust/watchstock-fullstack<file_sep>/server/models/stock.js
import mongoose from 'mongoose';
mongoose.Promise = global.Promise;
//mongoose.connect('mongodb://localhost:27017/watchstock', (error) => {
mongoose.connect("mongodb://redlocust:7895789<EMAIL>:63612/heroku_9zrzpbcf", (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!');
throw error;
}
});
var querySchema = mongoose.Schema({
code: String,
cuid: String,
});
var Stock = mongoose.model('Stock', querySchema);
export default Stock;<file_sep>/client/components/Main.jsx
import React, {Component} from 'react';
import Chart from './Chart.jsx';
import AddStock from './AddStock.jsx';
import StocksList from './StocksList';
let socket = io();
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dataArray: [],
loading: true
};
this.handleAddStock = this.handleAddStock.bind(this);
this.handleDeleteStock = this.handleDeleteStock.bind(this);
}
updateStateWithData() {
let that = this;
let url = 'api/stocks';
this.setState({
dataArray: [],
});
fetch(url)
.then(function (response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function (dat) {
let numOfCompletedFetch = 0;
let stocks = dat.stocks.map(function (elem) {
var myInit = {
mode: 'cors',
header: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data'
}
};
let url = `https://www.quandl.com/api/v3/datasets/WIKI/${elem.code}/data.json?api_key=<KEY>`
fetch(url, myInit)
.then(function (response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function (data) {
console.log('data', data);
console.log('date', Date.parse(data.dataset_data.start_date));
let dataset = data.dataset_data.data.map(el => el['1']);
let dataArray = that.state.dataArray;
dataArray.push({
data: dataset,
pointStart: Date.parse(data.dataset_data.start_date),
pointInterval: 24 * 3600 * 1000, // one day
name: elem.code
});
that.setState({dataArray});
});
return elem.code
}
);
console.log(stocks);
});
}
componentDidMount() {
let that = this;
this.updateStateWithData();
socket.on('UPDATE', function (msg) {
console.log('update');
that.updateStateWithData();
})
}
handleAddStock(stockId) {
let that = this;
fetch("/api/stocks/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({code: stockId})
})
.then(function (res) {
console.log('completed');
})
.catch(function (res) {
console.log(res)
});
socket.emit('ADD_STOCK', stockId);
}
handleDeleteStock(stockId) {
console.log(stockId);
console.log(this.state.dataArray.findIndex((elem, index) => elem.name === stockId));
let that = this;
let url = `/api/stocks/${stockId}`;
fetch(url,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "DELETE",
})
.then(() => {
console.log('delete stock')
})
.catch(function (res) {
console.log('error delete stock');
console.log(res);
});
socket.emit('DELETE_STOCK', stockId);
}
render() {
let options = this.state.dataArray;
return (
<div className="App row">
<div className="col-md-6 col-md-offset-3">
<div className="App-header text-center">
<h2>Stocklist app with socket.io</h2>
</div>
<Chart options={options}/>
<AddStock handleAddStock={this.handleAddStock}/>
<StocksList dataArray={this.state.dataArray} handleDeleteStock={this.handleDeleteStock}/>
</div>
</div>
);
}
}
export default Main;
<file_sep>/client/components/AddStock.jsx
import React, {Component} from 'react';
class AddStock extends Component {
constructor(props) {
super(props);
this.onAddStock = this.onAddStock.bind(this);
}
onAddStock(e) {
e.preventDefault();
this.props.handleAddStock(this.textInput.value);
this.textInput.value = '';
}
render() {
return (
<div>
<form>
<input type="text" placeholder="Enter stock code" ref={(input) => { this.textInput = input; }}/>
<button type="submit" onClick={this.onAddStock}>Add stock</button>
</form>
</div>
);
}
}
export default AddStock | f417a59312e4d70daba244ee29fd2cbac07645a0 | [
"JavaScript"
] | 3 | JavaScript | redlocust/watchstock-fullstack | c9fb7c535882359a787a82718dc23a421ce31953 | 5c9bbeb8d8e8b2f338ac2519104386229738883c |
refs/heads/master | <file_sep>/*
The one thing that all ray tracers have is a ray class and a computation of what color is seen along a ray.
Let’s think of a ray as a function P(t)=A+tb. Here P is a 3D position along a line in 3D.
A is the ray origin and b is the ray direction. The ray parameter t is a real number (double in the code).
Plug in a different t and P(t) moves the point along the ray.
Add in negative t values and you can go anywhere on the 3D line.
For positive t, you get only the parts in front of A, and this is what is often called a half-line or ray.
*/
#ifndef RAT_H
#define RAT_H
#include "vec3.h"
class ray {
public:
ray() {};
ray(const point3& origin, const vec3& direction)
: orig(origin), dir(direction) {
}
point3 origin() const {return orig; }
vec3 direction() const {return dir; }
point3 at(double t) const {return orig + t*dir;}
public:
point3 orig;
vec3 dir;
};
#endif<file_sep>#ifndef MATERIAL_H
#define MATERIAL_H
#include "ray.h"
#include "vec3.h"
#include "hittable.h"
class material {
public:
virtual bool scatter(const ray& r_in, hit_record& rec, color& attenuation, ray& scattered) const =0;
};
class lambertian : public material {
public:
lambertian(const color& a) : albedo(a) {};
virtual bool scatter(const ray& r_in, hit_record& rec, color& attenuation, ray& scattered) const {
vec3 scatter_direction = rec.normal + random_unit_vector();
scattered = ray( rec.p, scatter_direction );
attenuation = albedo;
return true;
}
public:
color albedo;
};
class metal : public material {
public:
metal(const color& a) : albedo(a), fuzz(1.0) {};
metal(const color& a, double f) : albedo(a), fuzz(f<1 ? f:1) {};
virtual bool scatter(const ray& r_in, hit_record& rec, color& attenuation, ray& scattered) const {
vec3 reflect_direction = reflect( unit_vector(r_in.direction()), rec.normal );
scattered = ray( rec.p, reflect_direction + fuzz*random_in_unit_sphere() );
attenuation = albedo;
return dot(scattered.direction(), rec.normal) > 0;
}
public:
color albedo;
double fuzz;
};
class dielectric : public material {
public:
dielectric(double ri) : ref_idx(ri) {}
virtual bool scatter(const ray& r_in, hit_record& rec, color& attenuation, ray& scattered) const {
attenuation = color(1.0, 1.0, 1.0);
double etai_over_etat = 1.0;
if( rec.front_face ) {
etai_over_etat = 1.0/ref_idx;
} else {
etai_over_etat = ref_idx;
}
vec3 unit_direction = unit_vector(r_in.direction());
double cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0);
double sin_theta = sqrt( 1.0 - cos_theta*cos_theta );
//reflect;
if( etai_over_etat * sin_theta > 1.0 ) {
vec3 reflected = reflect(unit_direction, rec.normal);
scattered = ray(rec.p, reflected);
return true;
}
//schlick
double reflect_prob = schlick(cos_theta, etai_over_etat);
if( random_double() < reflect_prob ) {
vec3 reflected = reflect(unit_direction, rec.normal);
scattered = ray(rec.p, reflected);
return true;
}
//refracted;
vec3 refracted = refract(unit_direction, rec.normal, etai_over_etat);
scattered = ray(rec.p, refracted);
return true;
}
public:
double ref_idx;
};
#endif<file_sep>#ifndef VEC3_H
#define VEC3_H
#include "rtweekend.h"
#include <cmath>
#include <iostream>
class vec3 {
public:
vec3() : e{0, 0, 0} {};
vec3(double e0, double e1, double e2) : e{e0, e1, e2} {};
double x() const {
return e[0];
};
double y() const {
return e[1];
};
double z() const {
return e[2];
}
vec3 operator~() const {
return vec3(vec3(-e[0], -e[1], -e[2]));
}
vec3 operator-() const {
return vec3(vec3(-e[0], -e[1], -e[2]));
}
double operator[](int i) const {
return e[i];
}
double& operator[](int i) {
return e[i];
}
vec3& operator+=(const vec3& v) {
e[0] += v.e[0];
e[1] += v.e[1];
e[2] += v.e[2];
return *this;
}
vec3& operator*=(const double t) {
e[0] *= t;
e[1] *= t;
e[2] *= t;
return *this;
}
vec3& operator/=(const double t) {
return *this *= 1/t;
}
double length() const {
return sqrt(length_squared());
}
double length_squared() const {
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
inline static vec3 random() {
return vec3(random_double(), random_double(), random_double());
}
inline static vec3 random(double min, double max) {
return vec3(random_double(min,max), random_double(min,max), random_double(min,max));
}
public:
double e[3];
};
//alises of vec3
using point3 = vec3; //3D Point
using color = vec3; //RGB
//vec3 Utility Functions;
inline std::ostream& operator<<(std::ostream& out, const vec3& v) {
return out << v.e[0] << ' ' << v.e[1] << ' ' << v.e[2];
}
inline vec3 operator+(const vec3& u, const vec3& v) {
return vec3( u.x()+v.x(), u.y()+v.y(), u.z()+v.z() );
}
inline vec3 operator-(const vec3& u, const vec3& v) {
return vec3( u.x()-v.x(), u.y()-v.y(), u.z()-v.z() );
}
inline vec3 operator*(const vec3& u, const vec3& v) {
return vec3( u.x()*v.x(), u.y()*v.y(), u.z()*v.z() );
}
inline vec3 operator*(double t, const vec3& v) {
return vec3( t*v.x(), t*v.y(), t*v.z() );
}
inline vec3 operator*(const vec3& v, double t) {
return t*v;
}
inline vec3 operator/(const vec3& v, double t) {
return (1/t)*v;
}
inline double dot(const vec3& u, const vec3& v) {
return u.x()*v.x() + u.y()*v.y() + u.z()*v.z() ;
}
inline vec3 cross(const vec3& u, const vec3& v) {
return vec3( u.y()*v.z() - u.z()*v.y(),
u.z()*v.x() - u.x()*v.z() ,
u.x()*v.y() - u.y()*v.x() );
}
inline vec3 unit_vector(vec3 v) {
return v / v.length();
}
inline vec3 random_vector() {
return vec3(random_double(), random_double(), random_double());
}
inline vec3 random_vector( double min, double max ) {
return vec3(random_double(min,max), random_double(min,max), random_double(min,max));
}
//随机取一个单位向量;
vec3 random_unit_vector() {
auto a = random_double(0, 2*pi);
auto z = random_double(-1, 1);
auto r = sqrt(1-z*z);
return vec3(r*cos(a), r*sin(a), z);
}
//在单位球内随机选取1点
vec3 random_in_unit_sphere() {
while( true ) {
auto p = random_vector(-1, 1);
if( p.length_squared() >= 1 ) {
continue;
}
return p;
}
}
//在单位半球内随机选取1点(与法线在同一个半球)
vec3 random_in_hemisphere(const vec3& normal) {
vec3 in_unit_sphere = random_in_unit_sphere();
if( dot(in_unit_sphere, normal) > 0.0 ) {
return in_unit_sphere;
}
return ~in_unit_sphere;
}
vec3 reflect(const vec3& v, const vec3& n) {
return v - 2*dot(v, n)*n;
}
vec3 refract(const vec3& uv, const vec3& n, double etai_over_etat) {
auto cos_theta = dot(~uv, n);
vec3 r_out_parallel = etai_over_etat * (uv + cos_theta*n);
vec3 r_out_perp = -sqrt(1.0 - r_out_parallel.length_squared())*n;
return r_out_parallel + r_out_perp;
}
/*
Schlick Approximation
Now real glass has reflectivity that varies with angle —
look at a window at a steep angle and it becomes a mirror.
There is a big ugly equation for that,
but almost everybody uses a cheap and surprisingly accurate polynomial approximation
by <NAME>
*/
double schlick(double cosine, double ref_idx) {
auto r0 = (1-ref_idx) / (1+ref_idx) ;
r0 = r0*r0;
return r0 + (1-r0)*pow((1 - cosine), 5);
}
// Generate random point inside unit disk
vec3 random_in_unit_disk() {
while(true) {
auto p = vec3( random_double(-1,1), random_double(-1,1), 0 );
if( p.length_squared() >= 1 ) continue;
return p;
}
}
#endif<file_sep>#ifndef HITTABLE_H
#define HITTABLE_H
#include "ray.h"
class material;
struct hit_record {
point3 p; //交点处-坐标;
vec3 normal; //交点处-平面法线;
double t; //交点处-光线t值;
bool front_face;//朝向
shared_ptr<material> material_ptr;
inline void set_face_normal(const ray& r, const vec3& outward_normal) {
front_face = dot( r.direction(), outward_normal ) < 0 ;
normal = front_face ? outward_normal : ~outward_normal ;
}
};
class hittable {
public:
virtual bool hit( const ray& r, double t_min, double t_max, hit_record& rec) const = 0;
};
#endif<file_sep>cmake_minimum_required(VERSION 3.10)
project(pangRayRracing)
set(CMAKE_CXX_STANDARED 17)
add_executable(pangRayRracing main.cpp material.h camera.h hittable.h hittable_list.h vec3.h color.h ray.h sphere.h rtweekend.h )
target_compile_options(pangRayRracing PUBLIC -Wall -Wextra -pedantic -Wshadow -Wreturn-type -fsanitize=undefined)
target_compile_features(pangRayRracing PUBLIC cxx_std_17)
target_link_libraries(pangRayRracing PUBLIC -fsanitize=undefined) | c256203244b06eb6373f06ef168f836f1b080388 | [
"CMake",
"C++"
] | 5 | C++ | KatePang13/pangRayTracing | 30de7c8b559f7000fca1f41299d91c89434d8392 | 53d55d0f9f3fa27afb3c97979c04fea79e538aff |
refs/heads/master | <repo_name>SPSUITD/python-django-project-Angelus760<file_sep>/app/admin.py
from django.contrib import admin
from .models import Message, Channel
admin.site.register(Message)
admin.site.register(Channel)
<file_sep>/templates/channel.html
{% for msg in messages %}
{{ msg.author }} - {{ msg.text }}<br>
{% endfor %}
<form action="{% url 'new_message' channel.title %}" method="POST">
{% csrf_token %}
{{ form.as_ul }}
<p><input type="submit"></p>
</form><file_sep>/app/models.py
from django.db import models
from django import forms
from django.contrib.auth import get_user_model
User_model = get_user_model()
class Channel(models.Model):
title = models.CharField(max_length=100)
class Message(models.Model):
channel = models.ForeignKey(Channel, on_delete=models.CASCADE)
author = models.ForeignKey(User_model, on_delete=models.CASCADE)
text = models.CharField(max_length=500)
pub_date = models.DateTimeField(auto_now_add=True)
class MessageForm(forms.ModelForm):
class Meta:
model = Message
exclude = ('author', 'channel')
<file_sep>/app/views.py
from django.shortcuts import render, redirect
from .models import Message, Channel, MessageForm
def index(request):
channels = Channel.objects.all()
return render(
request,
'index.html', {
'form': MessageForm(),
'channels': channels,
}
)
def channel_view(request, title):
channel = Channel.objects.get(title=title)
messages = Message.objects.filter(channel=channel)
return render(
request,
'channel.html', {
'form': MessageForm(),
'messages': messages,
'channel': channel,
}
)
def new_message(request, title):
if request.method != 'POST':
return redirect('index')
channel = Channel.objects.get(title=title)
form = MessageForm(request.POST)
if form.is_valid():
message = form.save(commit=False)
message.author = request.user
message.channel = channel
message.save()
return redirect('channel', title=channel.title)
<file_sep>/app/urls.py
from .views import index, channel_view, new_message
from django.urls import path
urlpatterns = [
path('', index),
path('<str:title>/', channel_view, name='channel'),
path('new/<str:title>/', new_message, name='new_message')
] | 2b65e53d4226d2da33f2c1606258554d39fff206 | [
"Python",
"HTML"
] | 5 | Python | SPSUITD/python-django-project-Angelus760 | ffbec40da6c0b3c7907ae9d081124a347b7bc1c1 | ca2aa060f5906618287b32fb67f5d125cf26f4de |
refs/heads/master | <repo_name>Sara-Borgstrom/project-music-releases<file_sep>/code/src/Components/Album.js
import React from 'react'
export const Album = (props) => {
return (
<div className="album-container">
<div className="icon-box">
<img src="./icons/heart.svg" alt="Heart icon" className="icon-heart icon" />
<img src="./icons/play.svg" alt="Play icon" className="icon-play icon" />
<img src="./icons/dots.svg" alt="Dots icon" className="icon-dots icon" />
</div>
<a href={props.url} className="album-link">
<img className="album-img" src={props.image} alt="Album" />
<div className="artist-info">
<h1 className="album-title">{props.name}</h1>
</div>
</a>
<div className="artist-box">
{props.children}
</div>
</div>
)
}
<file_sep>/README.md
`PROJECT 9`
# 'New Releases' music site
In this week's project I've used React components to build a page which shows new album and single releases.
# Includes
* JavaScript
* React (.map)
* JSON
* JSX
* CSS
See it: https://music-release-sara-b.netlify.com
<file_sep>/code/src/App.js
import React from 'react'
import data from './data.json'
import { Album } from './Components/Album.js'
import { Artist } from './Components/Artist.js'
console.log(data)
const releases = data.albums.items;
export const App = () => {
return (
<section className="releases">
<header className="release-header">
<h1 className="release-title">New albums & singles</h1>
</header>
<section className="release-container">
{releases.map((album) => {
return (
<Album
key={album.id}
name={album.name}
url={album.external_urls.spotify}
image={album.images[1].url}>
{album.artists.map((artist) => {
return (
<Artist
key={artist.id}
name={artist.name}
url={artist.external_urls.spotify} />
)
})}
</Album>
)
})}
</section>
</section>
)
} | 64d14d7e59af9fa316320f8c03a924e6e4bf44b4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Sara-Borgstrom/project-music-releases | 66c0f2cbe8a80def3c6af733b06220aa9895baac | fa58fb05a9ea5e0e6cb4d9a5949fc3a3033a85e3 |
refs/heads/master | <file_sep>/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fi.reaktor.log4j.emailthrottle;
import jdave.Specification;
import jdave.junit4.JDaveRunner;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.RootLogger;
import org.junit.runner.RunWith;
@RunWith(JDaveRunner.class)
public class ErrorEmailThrottleSpec extends Specification<ErrorEmailThrottle> {
public class EmailThrottleWithDefaultIntervals {
public ErrorEmailThrottle create() {
return new ErrorEmailThrottle();
}
public void doesNotThrottleFatalErrors() {
specify(context.isTriggeringEvent(createLogEvent(Level.FATAL, System.currentTimeMillis())), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
}
public void doesNotThrottleFirstErrorEvent() {
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, System.currentTimeMillis())), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
}
public void lowerThanErrorLevelEventsAreAreNotTriggering() {
specify(context.isTriggeringEvent(createLogEvent(Level.INFO, System.currentTimeMillis())), should.equal(false));
}
public void throttlesSecondAndThirdErrorIfSecondIsUnderOneMinuteApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 500;
long time3 = time2 + 2 * 60 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time3)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
}
public void throttleModeIsDisabledAndEmailSentIfThrottleTimeIsExceededEvenIfLastEventIsNotErrorLevel() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 500;
long time3 = time2 + 61 * 60 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
specify(context.isTriggeringEvent(createLogEvent(Level.WARN, time3)), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
}
public void doesNotThrottleSecondErrorIfItIsOverOneMinuteApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 2 * 60 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(true));
}
public void disablesThrottleModeIfThirdErrorIsMoreThanAnHourApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 500;
long time3 = time2 + 90 * 60 * 1000;
long time4 = time3 + 2 * 60 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time3)), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time4)), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
}
}
public class EmailThrottleWithCustomIntervals {
public ErrorEmailThrottle create() {
return new ErrorEmailThrottle(15 * 1000, 60 * 60 * 1000, 60 * 1000);
}
public void throttlesSecondAndThirdErrorIfSecondIsUnder15SecondsApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 500;
long time3 = time2 + 45 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time3)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
}
public void doesNotThrottleSecondErrorIfItIsOver15SecondsApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 45 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(true));
}
public void disablesThrottleModeIfThirdErrorIsMoreThanAMinuteApart() {
long time1 = System.currentTimeMillis();
long time2 = time1 + 500;
long time3 = time2 + 15 * 60 * 1000;
long time4 = time3 + 2 * 60 * 1000;
context.isTriggeringEvent(createLogEvent(Level.ERROR, time1));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time2)), should.equal(false));
specify(context.isInThrottleMode(), should.equal(true));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time3)), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
specify(context.isTriggeringEvent(createLogEvent(Level.ERROR, time4)), should.equal(true));
specify(context.isInThrottleMode(), should.equal(false));
}
}
private LoggingEvent createLogEvent(Level level, long time) {
return new LoggingEvent("test", new RootLogger(Level.INFO) , time, level, "test msg", null);
}
}
| 12fde092bda6dd2892c40ed8f2a8983345583637 | [
"Java"
] | 1 | Java | jewelfish/log4j-email-throttle | fec7e097149f1b72c1b5f8db92b4ff303e82468e | f60bb37da29e278cfa435e7bb7a07a850a28d133 |
refs/heads/master | <file_sep>alembic==1.5.6
appdirs==1.4.4
APScheduler==3.7.0
attrs==20.3.0
certifi==2020.12.5
chardet==4.0.0
click==7.1.2
colorama==0.4.4
decorator==4.4.2
distlib==0.3.1
filelock==3.0.12
Flask==1.1.2
Flask-Login==0.5.0
Flask-SQLAlchemy==2.4.4
Flask-WTF==0.14.3
idna==2.10
importlib-metadata==3.7.0
importlib-resources==5.1.2
ipython-genutils==0.2.0
itsdangerous==1.1.0
Jinja2==2.11.3
jsonschema==3.2.0
jupyter-core==4.7.1
Mako==1.1.4
MarkupSafe==1.1.1
nbformat==5.1.2
pigar==0.10.0
pipenv==2020.11.15
pyrsistent==0.17.3
python-dateutil==2.8.1
python-dotenv==0.15.0
python-editor==1.0.4
pytz==2021.1
pywin32==300
requests==2.25.1
six==1.15.0
SQLAlchemy==1.3.23
traitlets==4.3.3
typing-extensions==3.7.4.3
tzlocal==2.1
urllib3==1.26.3
virtualenv==20.4.2
virtualenv-clone==0.5.4
Werkzeug==1.0.1
WTForms==2.3.3
zipp==3.4.1
<file_sep>from datetime import datetime
from flask_login import UserMixin
from marshmallow import fields
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from marshmallow_sqlalchemy.fields import Nested
from Backend import db, login_manager, ma
from Backend.constants import available_jobs as available_jobs
@login_manager.user_loader
def user_loader(id):
return Person.query.get(int(id))
class Person(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
fname = db.Column(db.String(30), nullable=False)
lname = db.Column(db.String(30), nullable=False)
location = db.Column(db.String(15), nullable=False)
password = db.Column(db.String(60), nullable=False)
type = db.Column(db.String(20)) # this is the discriminator column
__mapper_args__ = {
'polymorphic_on': type,
}
class User(Person):
id = db.Column(db.Integer, db.ForeignKey('person.id'), primary_key=True)
email = db.Column(db.String(25), unique=True, nullable=False)
phone = db.Column(db.String(11), unique=True, nullable=False)
__mapper_args__ = {
'polymorphic_identity': 'user'
}
def __repr__(self):
return f"User('{self.fname} ', '{self.lname}', '{self.email}', '{self.phone}', '{self.location}')"
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
class Worker(Person):
id = db.Column(db.Integer, db.ForeignKey('person.id'), primary_key=True)
email = db.Column(db.String(25), unique=True, nullable=False)
phone = db.Column(db.String(11), unique=True, nullable=False)
job = db.Column(db.String(20), nullable=False)
description = db.Column(db.Text, nullable=False,
default='Insert your personal description here')
image = db.Column(db.String(20), nullable=False, default='default.jpg')
rate = db.Column(db.Float(2), default=1000.00)
active = db.Column(db.Boolean, nullable=False, default=True)
available = db.Column(db.Boolean, nullable=False, default=True)
__mapper_args__ = {
'polymorphic_identity': 'worker'
}
def __repr__(self):
return f"Worker('{self.fname} ', '{self.lname}', '{self.email}', '{self.phone}', '{self.job}', '{self.location}')"
class WorkerSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Worker
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
address = db.Column(db.String(120), nullable=False)
city = db.Column(db.String(15), nullable=False)
landmark = db.Column(db.String(120), nullable=True)
user = db.relationship('User', backref='user', lazy=True)
def __repr__(self):
return f"Address('{self.user.fname} {self.user.lname} ', '{self.address}', '{self.city}')"
class AddressSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Address
class WorkLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
worker_id = db.Column(db.Integer, db.ForeignKey('worker.id'), nullable=False)
address_id = db.Column(db.Integer, db.ForeignKey('address.id'), nullable=False)
duration = db.Column(db.String(15), nullable=False)
description = db.Column(db.Text, nullable=False)
date = db.Column(db.DateTime, nullable=False)
accepted = db.Column(db.Boolean, nullable=False, default=False)
completed = db.Column(db.Boolean, nullable=False, default=False)
taskee = db.relationship('User', backref='taskee', lazy=True)
tasker = db.relationship('Worker', backref='tasker', lazy=True)
location = db.relationship('Address', backref='location', lazy=True)
def __repr__(self):
return f"Task('{self.taskee}', '{self.tasker} ', '{self.location}', '{self.date}', accepted: '{self.accepted}', completed: '{self.completed}')"
class TaskSchema(SQLAlchemyAutoSchema):
class Meta:
model = WorkLog
taskee = Nested(UserSchema(exclude=['password', 'location', 'type', 'email']))
tasker = Nested(WorkerSchema(exclude=['password', 'location', 'type', 'email']))
location = Nested(AddressSchema)
class Rating(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
worker_id = db.Column(db.Integer, db.ForeignKey('worker.id'), nullable=False)
rating = db.Column(db.Integer, nullable=False)
description = db.Column(db.Text, nullable=False)
rater = db.relationship('User', backref='rater', lazy=True)
worker = db.relationship('Worker', backref='worker', lazy=True)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
class RatingSchema(SQLAlchemyAutoSchema):
class Meta:
model = Rating
rater = Nested(UserSchema(exclude=['password', 'location', 'type', 'email', 'phone']))<file_sep>--
-- File generated with SQLiteStudio v3.2.1 on Sun Feb 14 17:30:54 2021
--
-- Text encoding used: System
--
PRAGMA foreign_keys = off;
BEGIN TRANSACTION;
-- Table: person
CREATE TABLE person (
id INTEGER NOT NULL,
fname VARCHAR (30) NOT NULL,
lname VARCHAR (30) NOT NULL,
location VARCHAR (15) NOT NULL,
password VARCHAR (60) NOT NULL,
type VARCHAR (20),
PRIMARY KEY (
id
)
);
-- Table: user
CREATE TABLE user (
id INTEGER NOT NULL,
email VARCHAR (25) NOT NULL,
phone VARCHAR (11) NOT NULL,
PRIMARY KEY (
id
),
FOREIGN KEY (
id
)
REFERENCES person (id),
UNIQUE (
email
),
UNIQUE (
phone
)
);
-- Table: worker
CREATE TABLE worker (
id INTEGER NOT NULL,
email VARCHAR (25) NOT NULL,
phone VARCHAR (11) NOT NULL,
job VARCHAR (20) NOT NULL,
description TEXT NOT NULL,
image VARCHAR (20) NOT NULL,
rate FLOAT,
active BOOLEAN NOT NULL,
available BOOLEAN NOT NULL,
PRIMARY KEY (
id
),
FOREIGN KEY (
id
)
REFERENCES person (id),
UNIQUE (
email
),
UNIQUE (
phone
),
CHECK (active IN (0, 1) ),
CHECK (available IN (0, 1) )
);
-- Table: address
CREATE TABLE address (
id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
address VARCHAR (120) NOT NULL,
city VARCHAR (15) NOT NULL,
landmark VARCHAR (120),
PRIMARY KEY (
id
),
FOREIGN KEY (
user_id
)
REFERENCES user (id)
);
-- Table: work_log
CREATE TABLE work_log (
id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
worker_id INTEGER NOT NULL,
address_id INTEGER NOT NULL,
duration VARCHAR (15) NOT NULL,
description TEXT NOT NULL,
date DATETIME NOT NULL,
accepted BOOLEAN NOT NULL,
completed BOOLEAN NOT NULL,
PRIMARY KEY (
id
),
FOREIGN KEY (
user_id
)
REFERENCES user (id),
FOREIGN KEY (
worker_id
)
REFERENCES worker (id),
FOREIGN KEY (
address_id
)
REFERENCES address (id),
CHECK (accepted IN (0, 1) ),
CHECK (completed IN (0, 1) )
);
-- Table: rating
CREATE TABLE rating (
id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
worker_id INTEGER NOT NULL,
rating INTEGER NOT NULL,
description TEXT NOT NULL,
date DATETIME NOT NULL,
PRIMARY KEY (
id
),
FOREIGN KEY (
user_id
)
REFERENCES user (id),
FOREIGN KEY (
worker_id
)
REFERENCES worker (id)
);
COMMIT TRANSACTION;
PRAGMA foreign_keys = on;
<file_sep># SDP-Project
Install requirements.txt using pip install -r requirements.txt
In the root directory on command line run python run.py
<file_sep>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_marshmallow import Marshmallow
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
from Backend import routes<file_sep>import os
import secrets
import json
from datetime import datetime
from flask import jsonify, request, redirect, url_for
from flask_login import current_user, login_required, login_user, logout_user
from sqlalchemy.exc import IntegrityError
from Backend import app, bcrypt, db, ma
from Backend.models import Person, User, Worker, Address, UserSchema, WorkerSchema, AddressSchema, WorkLog, TaskSchema
@app.route('/', methods=['GET', 'POST'])
def home():
return jsonify(message= "asfwefwsdfc")
@app.route('/user/login', methods=["POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
email = request.form.get('email')
password = request.form.get('password')
remember = request.form.get('remember')
user = User.query.filter(User.email == email).first()
if user and bcrypt.check_password_hash(user.password, password):
login_user(user, remember=remember)
return jsonify(message = "logged in user")
else:
return jsonify(message = "wrong login credentials")
@app.route('/user/register', methods=["POST"])
def register():
fname = request.form.get('fname')
lname = request.form.get('lname')
location = request.form.get('location')
phone = request.form.get('phone')
email = request.form.get('email')
password = request.form.get('password')
hashpw = bcrypt.generate_password_hash(password).decode('utf-8')
user = User(fname=fname, lname=lname, location=location,
phone=phone, email=email, password=hashpw)
try:
db.session.add(user)
db.session.commit()
return jsonify(message = "registered")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error")
@app.route('/user/updateuserprofile', methods=["POST"])
@login_required
def updateuserprofile():
current_user.fname = request.form.get('fname')
current_user.lname = request.form.get('lname')
current_user.location = request.form.get('location')
current_user.phone = request.form.get('phone')
current_user.email = request.form.get('email')
try:
db.session.commit()
return jsonify(message = "updated user info successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error update")
@app.route('/user/addnewaddress', methods=["POST"])
@login_required
def addnewaddress():
address = request.form.get('address')
city = request.form.get('city')
landmark = request.form.get('landmark')
add1 = Address(address=address, city=city, landmark=landmark, user_id=current_user.id)
db.session.add(add1)
try:
db.session.commit()
return jsonify(message = "added address successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error update")
@app.route('/user/getuseraddresses', methods=["GET"])
@login_required
def getuseraddresses():
addresses = Address.query.filter_by(user=current_user).all()
schema = AddressSchema(many=True)
output = schema.dump(addresses)
return jsonify(addresses = output)
@app.route('/user/getparticularaddress/<int:address_id>', methods=["GET"])
@login_required
def getparticularaddress(address_id):
address = Address.query.get_or_404(address_id)
if address.user != current_user:
abort(403)
schema = AddressSchema()
output = schema.dump(address)
return jsonify(address = output)
@app.route('/user/updateparticularaddress/<int:address_id>', methods=["POST"])
@login_required
def updateparticularaddress(address_id):
address = request.form.get('address')
city = request.form.get('city')
landmark = request.form.get('landmark')
add = Address.query.get_or_404(address_id)
add.address = address
add.city = city
add.landmark = landmark
try:
db.session.commit()
return jsonify(message = "updated address successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error update")
@app.route('/user/deleteparticularaddress/<int:address_id>', methods=["DELETE"])
@login_required
def deleteparticularaddress(address_id):
address = Address.query.get_or_404(address_id)
if address.user != current_user:
abort(403)
db.session.delete(address)
db.session.commit()
return jsonify(message = "deleted address successfully")
@app.route('/user/createtask', methods=["POST"])
@login_required
def createtask():
address = request.form.get('address')
duration = request.form.get('duration')
description = request.form.get('description')
date = datetime.fromtimestamp(int(request.form.get('date'))/1000)
task = WorkLog(address_id=address, user_id=current_user.id, worker_id=1, duration=duration, description=description, date=date)
db.session.add(task)
try:
db.session.commit()
return jsonify(message = "added task successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error update")
@app.route('/user/getusertasks', methods=["GET"])
@login_required
def getusertasks():
tasks = WorkLog.query.filter_by(taskee=current_user).all()
schema = TaskSchema(many=True,)
output = schema.dump(tasks)
return jsonify(tasks = output)
@app.route('/user/gettaskinfo/<int:task_id>', methods=["GET"])
@login_required
def gettaskinfo(task_id):
task = WorkLog.query.get_or_404(task_id)
# check if the taskee is the current user else abort
if task.taskee != current_user:
abort(403)
#instantiate schemas
taskschema = TaskSchema()
#dump them into schema
output = taskschema.dump(task)
return jsonify(task = output)
@app.route('/user/editparticulartask/<int:task_id>', methods=["POST"])
@login_required
def updateparticulartask(task_id):
address = request.form.get('address')
duration = request.form.get('duration')
description = request.form.get('description')
date = request.form.get('date')
task = WorkLog.query.get_or_404(task_id)
task.address = address
task.duration = duration
task.description = description
task.date = date
try:
db.session.commit()
return jsonify(message = "updated task successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error update")
@app.route('/user/accepttask/<int:task_id>', methods=["GET"])
@login_required
def accepttask(task_id):
task = WorkLog.query.get_or_404(task_id)
task.accepted = True
try:
db.session.commit()
return jsonify(message = "updated address successfully")
except IntegrityError:
db.session.rollback()
return jsonify(message = "error")
@app.route('/user/getworkersbyjob/<string:job>/<int:page>', methods=["GET"])
@login_required
def getworkersbyjob(job,page):
workers = Worker.query.filter_by(job=job, active=True, available=True).paginate(per_page=7,page=page)
workerschema = WorkerSchema(many=True, exclude=['password', 'location', 'type', 'email', 'phone', 'active', 'available'])
#dump them into schema
output = workerschema.dump(workers.items)
return jsonify(workers = output)
@app.route('/user/logout', methods=["GET"])
def logout():
logout_user()
return jsonify(message = "user logged out")
@app.route('/user/addworker', methods=["GET"])
def addworker():
passwd = bcrypt.generate_password_hash('password').decode('utf-8')
work = Worker(fname='Daniel', lname='Iheonu', phone='08012345678', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Carpenter')
work1 = Worker(fname='David', lname='Iheonu', phone='08098765432', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Carpenter')
work2 = Worker(fname='Maxwell', lname='Ogalabu', phone='08126897683', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Barber')
work3 = Worker(fname='Temi', lname='Dimowo', phone='08078965412', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Carpenter')
work4 = Worker(fname='Ify', lname='Ogalabu', phone='08198765432', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Gardener')
work5 = Worker(fname='Carey', lname='Ifode', phone='08112345678', email='<EMAIL>', location='Aba', password=<PASSWORD>, job='Gardener')
try:
db.session.add(work)
db.session.add(work1)
db.session.add(work2)
db.session.add(work3)
db.session.add(work4)
db.session.add(work5)
db.session.commit()
return jsonify(message = "workers added")
except IntegrityError:
db.session.rollback()
return jsonify(message = "integrity error")
| 88d44a4ec1b3efb5cfb4a04f4c0f68d2110579d6 | [
"Markdown",
"SQL",
"Python",
"Text"
] | 6 | Text | AnointingMax/SDP-Project | 47c5241e27477d8a38c74e570b5dc197fb640cdc | 1844a224dfee26bdc990884c788b6b0acf398ba5 |
refs/heads/master | <repo_name>SorrGrif/LastQuestWiki<file_sep>/.gradle/2.14.1/taskArtifacts/cache.properties
#Wed Dec 07 09:58:13 EST 2016
<file_sep>/app/src/main/java/comsorrgriflastquestwiki/github/lastquestwiki/FaqItem.java
package comsorrgriflastquestwiki.github.lastquestwiki;
/**
* Created by Reishin on 2016-11-20.
*/
public class FaqItem {
//Getter and setter for the faq fragment
private String question;
private String answer;
public FaqItem(String question, String answer) {
this.question = question;
this.answer = answer;
}
public void setQuestion(String question) {
this.question = question;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
| ecaa1f563361af18255543bf8a6a51febb561003 | [
"Java",
"INI"
] | 2 | INI | SorrGrif/LastQuestWiki | ba23a4d99e0760117ea24e0c89411f626fa37425 | bdd01a49a758bc074b02772e4e9d6fc85fd07652 |
refs/heads/master | <file_sep>package com.pinnegar;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RegexTest {
@Test
public void space_splitter() {
assertThat("1 2 3".split(" ")).containsExactly("1", "2", "3");
}
}
<file_sep>rootProject.name = 'testing-when-why-how'
<file_sep>package com.pinnegar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Person {
public LIVING_STATUS getLivingStatus() {
return livingStatus;
}
public enum LIVING_STATUS {
ALIVE, DEAD
}
private LIVING_STATUS livingStatus = LIVING_STATUS.ALIVE;
private String name;
private List<Person> children = new ArrayList<>();
private Person parent;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person addChildren(Person... children) {
for (Person child : children) {
this.children.add(child);
child.parent = this;
}
return this;
}
public List<Person> getChildren() {
return children;
}
public Person die() {
livingStatus = LIVING_STATUS.DEAD;
parent.children.remove(this);
return this;
}
}
<file_sep>package com.mpinnegar;
public class Outer {
public static void main(String[] args) {
Middle middle = new Middle();
middle.callThroughToInner("my string to pass in");
}
}
<file_sep># p3-blog
All files found in the blog at https://professional-practical-programmer.com/ can be located in this repo.
Each blog entry has its own subdirectory which is a fully functional gradle project. In each entry the gradle wrapper files have been committed.
TO RUN: `git clone` the project. Move into the directory of your choice (each blog has its own directory), then use `./gradlew build` to build the project. It should build on Windows or Linux with no dependencies, not even Gradle! :)
<file_sep>rootProject.name = 'intellij-debugger'
<file_sep>package com.pinnegar;
public class Calculator {
public SubtractingCalculator subtract(int dividend) {
return new SubtractingCalculator(dividend);
}
public class SubtractingCalculator {
private int subtractor;
private SubtractingCalculator(int subtractor) {
this.subtractor = subtractor;
}
public int from(int startingAmount) {
return startingAmount - subtractor;
}
}
public DividingCalculator divide(int dividend) {
return new DividingCalculator(dividend);
}
public class DividingCalculator {
private int dividend;
private DividingCalculator(int dividend) {
this.dividend = dividend;
}
public int by(int divisor) throws Exception {
if (divisor == 0) {
throw new Exception("You tried to divide [" + dividend + "] by zero which is illegal.");
}
return dividend / divisor;
}
}
}
| ddd884f8dc5c3a53fdbb020b3c40a65de24988ec | [
"Markdown",
"Java",
"Gradle"
] | 7 | Java | Jazzepi/p3-blog | 35955ed011e0b35afb81841e6f00f51100cc4566 | 7cb582063e10c49da0b0aa0533bacea682da913f |
refs/heads/master | <file_sep>package com.checkmarx.jenkins.test;
import com.checkmarx.jenkins.Aes;
import com.checkmarx.jenkins.CxCredentials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class PasswordEncryptTest {
private final String EXPECTED_PASSWORD = "<PASSWORD>!";
private final String MESSAGE = "CxSAST Password";
@Mock
CxCredentials credentials;
@BeforeEach
void init() {
final String USERNAME = "my@user";
Mockito.when(credentials.getUsername()).thenReturn(USERNAME);
String encryptedPassword = Aes.encrypt(EXPECTED_PASSWORD, credentials.getUsername());
Mockito.when(credentials.getPassword()).thenReturn(encryptedPassword);
}
@Test
void encryptDecryptPassword_ValidProcess() {
String actualResult = Aes.decrypt(credentials.getPassword(), credentials.getUsername());
assertEquals(EXPECTED_PASSWORD, actualResult, MESSAGE);
}
@Test
void encryptDecryptPassword_InvalidProcess() {
String actualResult = Aes.decrypt(credentials.getPassword(), credentials.getUsername());
assertNotEquals("Pass245!", actualResult, MESSAGE);
}
}
<file_sep>package com.checkmarx.jenkins;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
public enum DOMStatiscs
{
TotalFiles,
GoodFiles,
PartiallyGoodFiles,
BadFiles,
ParsedLoc,
GoodLoc,
BadLoc,
NumberOfDomObjects,
ScanCoverage,
ScanCoverageLoc,
FlowStartTime,
FlowEndTime,
ParseStartTime,
ParseEndTime,
QueryStartTime,
QueryEndTime,
ScanDuration,
ResolverStartTime,
ResolverEndTime,
AbsIntStartTime,
AbsIntEndTime
}
public static List<String> getDOMStatistics(List<String> log, DOMStatiscs type)
{
List<String> listOutput = new ArrayList<>();
String pattern;
switch (type)
{
case TotalFiles:
pattern = "Total files\\s*(?<number>(\\d*))";
break;
case GoodFiles:
pattern = "Good files:\\s*(?<number>(\\d*))";
break;
case PartiallyGoodFiles:
pattern = "Partially good files:\\s*(?<number>(\\d*))";
break;
case BadFiles:
pattern = "Bad files:\\s*(?<number>(\\d*))";
break;
case ParsedLoc:
pattern = "Parsed LOC:\\s*(?<number>(\\d*))";
break;
case GoodLoc:
pattern = "Good LOC:\\s*(?<number>(\\d*))";
break;
case BadLoc:
pattern = "Bad LOC:\\s*(?<number>(\\d*))";
break;
case NumberOfDomObjects:
pattern = "Number of DOM Objects:\\s*(?<number>(\\d*))";
break;
case ScanCoverage:
pattern = "Scan coverage:\\s*(?<number>(\\d.*))";
break;
case ScanCoverageLoc:
pattern = "Scan coverage LOC:\\s*(?<number>(\\d.*))";
break;
case FlowStartTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\(Start\\): Expanding graph from History)";
break;
case FlowEndTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\( End \\): Expanding graph from History)";
break;
case ParseStartTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Unspecified\\] - Engine Phase \\(Start\\): Parsing)";
break;
case ParseEndTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Unspecified\\] - Engine Phase \\( End \\): Parsing)";
break;
case QueryStartTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Unspecified\\] - Engine Phase \\(Start\\): Querying)";
break;
case QueryEndTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Unspecified\\] - Engine Phase \\( End \\): Querying)";
break;
case ScanDuration:
pattern = "(?<=Elapsed Time: )((?:\\d\\.)?[0-9:]{8})";
break;
case ResolverStartTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\(Start\\): Resolver)";
break;
case ResolverEndTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\( End \\): Resolver)";
break;
case AbsIntStartTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\(Start\\): AbsInt Resolver)";
break;
case AbsIntEndTime:
pattern = "((?:\\d\\.)?\\d{2}:\\d{2}:\\d{2})(?=(?:\\.\\d*)? \\[Resolving\\] - Engine Phase \\( End \\): AbsInt Resolver)";
break;
default:
pattern = "";
break;
}
if (!pattern.isEmpty())
{
for (String line : log)
{
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(line);
boolean isMatch = m.find();
if (isMatch)
{
listOutput.add(m.group(1));
}
}
}
return listOutput;
}
public static List<String> getSlowestQueryInfo(List<String> log)
{
List<String> listOutput = new ArrayList<>();
String pattern = "(?<=Query - )[aA-zZ._0-9]+";
if (!pattern.isEmpty())
{
String slowestQueryName = "";
String slowestQueryTime = "";
int slowestQuerySecs = -1;
for (String line : log)
{
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(line);
boolean isMatch = m.find();
if (isMatch)
{
String queryTime = getQueryTime(line);
if (queryTime != null && !queryTime.equals("Failed"))
{
int secs = calcSecFromDateTimeString(queryTime);
if (secs > slowestQuerySecs)
{
slowestQueryName = m.group(0);
slowestQueryTime = queryTime;
slowestQuerySecs = secs;
}
}
}
}
listOutput.add(slowestQueryName);
listOutput.add(slowestQueryTime);
}
return listOutput;
}
public static int calcSecFromDateTimeString(List<String> startRegexList, List<String> endRegexList)
{
if (startRegexList.size() != endRegexList.size()) {
return -1;
}
int totalDiff = 0;
int size = startRegexList.size();
for (int i = 0; i < size; i++) {
totalDiff += calcSecFromDateTimeString(endRegexList.get(i)) - calcSecFromDateTimeString(startRegexList.get(i));
}
return totalDiff;
}
public static int calcSecFromDateTimeString(String text)
{
if (text.contains(".")) {
String[] firstParts = text.split(":");
String[] secondParts = firstParts[0].split(".");
return (Integer.parseInt(secondParts[0]) * 24 * 60 * 60) + (Integer.parseInt(secondParts[1]) * 60 * 60) + (Integer.parseInt(firstParts[1]) * 60) + Integer.parseInt(firstParts[2]);
}
String[] firstParts = text.split(":");
return (Integer.parseInt(firstParts[0]) * 60 * 60) + (Integer.parseInt(firstParts[1]) * 60) + Integer.parseInt(firstParts[2]);
}
public static String secAsTimeString(int sec)
{
int days = (int)Math.floor(sec / 86400);
int hours = (int)Math.floor((sec - (days * 86400)) / 3600);
int minutes = (int)Math.floor((sec - (days * 86400) - (hours * 3600)) / 60);
int seconds = sec - (days * 86400) - (hours * 3600) - (minutes * 60);
String str = "";
if (days > 0 && days < 10){
str = String.format("%s0%d days, ", str, days);
}
if (days > 9) {
str = String.format("%s%d days, ", str, days);
}
if (hours < 10) {
str = String.format("%s0%d:", str, hours);
}
if (hours > 9) {
str = String.format("%s%d:", str, hours);
}
if (minutes < 10) {
str = String.format("%s0%d:", str, minutes);
}
if (minutes > 9) {
str = String.format("%s%d:", str, minutes);
}
if (seconds < 10) {
str = String.format("%s0%d", str, seconds);
}
if (seconds > 9) {
str = String.format("%s%d", str, seconds);
}
return str;
}
private static String getQueryTime(String line)
{
Pattern p = Pattern.compile("(?<=Duration = )[0-9:]+");
Matcher m = p.matcher(line);
boolean isMatch = m.find();
if (isMatch) {
if (!verifyIfQueryFailed(line)) {
return m.group(0);
}
else {
return "Failed";
}
}
else {
return null;
}
}
private static boolean verifyIfQueryFailed(String line)
{
Pattern p = Pattern.compile("Failed!");
Matcher m = p.matcher(line);
boolean isMatch = m.find();
if (isMatch) {
return true;
}
else {
return false;
}
}
}
| 532db57af351f3003da2583d90bd10e24335cbd8 | [
"Java"
] | 2 | Java | LuisVentuzelos/checkmarx-plugin | 99000c12e254a48191ca74b0ea52e3ad192a8b6c | 009eb9b3b19579475793f4fce3d2cc5c6e080217 |
refs/heads/master | <repo_name>Aendys/Projects-in-C-PlusPlus<file_sep>/README.md
# Projects-in-C-PlusPlus
My projects in C++
<file_sep>/main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
const int maxPokusu=5;
int vyplnenePismeno (char, string, string&);
int main ()
{
string nazev;
char zadanePismeno;
int spatneOdpovedi=0;
string slovo;
string slova[] =
{
"programovani",
"konstanta",
"sibenice",
};
srand(time(NULL));
int n=rand()% 3;
slovo=slova[n];
string nezname(slovo.length(),'*');
cout << "\n\nVitejte ve hre Sibenice";
cout << "\n\nKazde pismeno hledaneho slova je zobrazeno hvezdickou";
cout << "\n\nMate " << maxPokusu << " pokusu.";
cout << "\n---------------------------------------------------------";
while (spatneOdpovedi < maxPokusu)
{
cout << "\n\n" << nezname;
cout << "\n\nHadej pismeno: ";
cin >> zadanePismeno;
if (vyplnenePismeno(zadanePismeno, slovo, nezname)==0)
{
cout << endl << "Toto pismeno zde neni!" << endl;
spatneOdpovedi++;
int zbyvajiciPokusy = maxPokusu - spatneOdpovedi;
if (zbyvajiciPokusy == 0){
cout << "+-------+" << endl;
cout << "| |" << endl;
cout << "| O" << endl;
cout << "| /|\\" << endl;
cout << "| / \\" << endl;
cout << "| " << endl;
cout << "===========" << endl;
cout << "\nSmula, byl jsi povesen!" << endl;
cout << "Slovo bylo: " << slovo << endl;
}
else if (zbyvajiciPokusy == 1){
cout << "+-------+ " << endl;
cout << "| | " << endl;
cout << "| O " << endl;
cout << "| /|\\" << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "===========" << endl;
}
else if (zbyvajiciPokusy == 2){
cout << "+-------+ " << endl;
cout << "| | " << endl;
cout << "| O " << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "===========" << endl;
}
else if (zbyvajiciPokusy == 3){
cout << "+-------+ " << endl;
cout << "| | " << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "| " << endl;
cout << "===========" << endl;
}
else if (zbyvajiciPokusy == 4){
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
cout << " " << endl;
cout << "===========" << endl;
}
}
else
{
cout << endl << "Uhodl jsi pismeno!" << endl;
}
cout << "Mate " << maxPokusu - spatneOdpovedi;
cout << " pokusu." << endl;
if (slovo==nezname)
{
cout << slovo << endl;
cout << "Gratuluji, vyhral jsi!";
break;
}
}
if (spatneOdpovedi == maxPokusu){
cout << "\nProhral jsi!" << endl;
cout << "Slovo bylo: " << slovo << endl;
}
cin.ignore();
cin.get();
return 0;
}
int vyplnenePismeno (char hadat, string tajneSlovo, string &hadaneSlovo)
{
int i;
int nalezeno=0;
int delka=tajneSlovo.length();
for (i = 0; i< delka; i++)
{
if (hadat == hadaneSlovo[i])
return 0;
if (hadat == tajneSlovo[i])
{
hadaneSlovo[i] = hadat;
nalezeno++;
}
}
return nalezeno;
}
| 1d4be60c980eaf86187d80ea76e959772bec12b5 | [
"Markdown",
"C++"
] | 2 | Markdown | Aendys/Projects-in-C-PlusPlus | 9b89a59c7d3c8d702495e1068a74075a30c3dcf6 | cec2c985e3bb810fe355d86d6890fbf312564cf5 |
refs/heads/master | <repo_name>yomiramontalvo/LIM010-data-lovers<file_sep>/README.md
# Data Lovers
## Índice
- [Índice](#índice)
- [Título](#titulo)
- [Introducción](#introduccion)
- [Resumen del Proyecto](#resumen-del-proyecto)
- [Investigación UX](#imagen-del-proyecto-final)
- [Usuario y objetivo en Relación al Producto](#usuario-y-objetivo-en-relacion-al-producto)
- [Problema y Necesidades que resuelve](#problema-y-necesidades-que-resuelve)
- [Resumen del Feedback](#resumen-del-feedback)
- [Imagen y link del prototipo en Figma](#imagen-y-link-del-prototipo-en-Figma)
## Título
# **Latin Data**
## Introducción
En pleno siglo XXI la información acerca de datos e indicadores de páginas Web y/o aplicaciones no cuenta con el valor necesario.
Conforme a ello se realizó un estudio en el cual se observó que existen escasos medios que brindan información de datos e indicadores. El Banco Mundial cumple con esta función, sin embargo su trasfondo tiene como objetivo combatir la pobreza extrema ayudando a países que necesiten concretar proyectos para beneficiar a un conjunto de personas.
Sin embargo, se entiende que el usuario requiere información más precisar, por ello se propuso como solución conectar y hacer accesible el ingreso a ciertos datos de países Latinoamericanos no solo para analizar y recopilar información sino también para estar al tanto de la realidad en la que se encuentran estos país, para afianzar la información se unió un conjunto de noticias relacionadas con los temas, deseando así una experiencia confiable y rápida de ingresar.
## Resumen del Proyecto
El proyecto “Latin Data” busca facilitar el acceso a datos e indicadores de países Latinoamericanos con la finalidad de hacer más eficiente la búsquedad del usuario.
El ingreso a esta plataforma se realizará a través del usuario y contraseña “<PASSWORD>”.
### Problema que resuelve
Diariamente se requieren de datos para conocimiento, análisis y toma de decisiones, lo cual usualmente son buscados en Google u otras plataformas. Sin embargo los datos encontrados no siempre pueden ser filtrados, seleccionados y ordenados lo que hace más complicada la obtención de esta información, por ello se desarrolla la plataforma “Latin Data” con la finalidad de facilitar el acceso a datos que incluyen indicadores demográficos, económicos y comerciales de los países Latinoamericanos como Perú, México, Chile y Brasil.
Observando esta situación se planificó el proyecto "Latin Data" que se desarrolla ante la problemática de inaccesibilidad inmediata y rápida de datos que incluyen indicadores de ciertos países Latinoamericanos como lo son Perú, México, Chile y Brasil.
## Investigación UX
### **Necesidades:**
1. Visualización de datos estadísticos de fuente confiable, de forma ordenada ascendentemente o descendentemente según año y tipo de indicador, filtrado de resultados según año además visualizar una tendencia promedio del indicador para un determinado país.
2. El producto debe funcionar para todos los posibles casos, es decir, que aplique para cualquier País seleccionado y cualquier indicador seleccionado.
3. Debe ser de fácil acceso para todos, se debe poder retroceder o avanzar.
4. Debe tener un diseño agradable, que organice correctamente la información.
### Usuario y objetivo en Relación al Producto
Este proyecto está orientado a estudiantes, analistas, ejecutivos, autoridades públicas y/o profesionales de cualquier especialidad, que requieran de datos de buena calidad para fijar niveles de referencia, identificar medidas públicas y privadas eficaces, determinar objetivos y metas, supervisar avances y evaluar efectos. Además, la información representa una herramienta fundamental para una buena gestión, puesto que es un medio para que las personas evalúen la labor del gobierno y puedan participar directamente en el proceso de desarrollo.
### Diseño del Prototipo
Prototipo en baja fidelidad ( Web )




Prototipo en baja fidelidad ( Movil )


## Imagen y link del prototipo en Figma (Prototipo inicial)
Prototipo en alta fidelidad
## **Login**


## **Pantalla "Quiénes Somos"**


## **Pantalla activada al seleccionar un país**

## **Pantalla activada al seleccionar un tipo de indicador**

## **Pantalla activada al seleccionar un indicador**

A través del siguiente Link se podrá obtener el figma de las Historias de Usuario planteadas. https://www.figma.com/file/eEgDuL4cbCJMbdN7TrvhrTPi/Latin-Data?node-id=0%3A1
## Resumen del Feedback inicial

## Prueba de Usabilidad

Con el siguiente enlace puede visualizar la matriz de pruebas:
https://docs.google.com/spreadsheets/d/1x4xFn8iCa2HZpBJ5Z7UODlxk2kj6z2DP91m5YthLaqk/edit?usp=sharing
## Imagen final del Proyecto
Prototipo final en Alta Fidelidad
## **Login**


## **Pantalla "Quiénes Somos"**


## **Pantalla activada al seleccionar un país**

## **Pantalla activada al seleccionar un tipo de indicador**

## **Pantalla activada al seleccionar un indicador**

A través del siguiente Link se podrá obtener el figma de las Historias de Usuario planteadas. https://www.figma.com/file/JVEtXX4GBWx9CTADyo68f6/Latin-Data-(Copy)?node-id=103%3A238
<file_sep>/src/main.js
/* Graficos */
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.load('current', { 'packages': ['table'] });
/* Manejo del DOM */
/* Acá va tu código */
const screenLogin = document.getElementById('boton-login');
const screenSelectCountry = document.getElementById('screen-select-country');
const screenpresentationPER = document.getElementById('presentationper');
const screenpresentationCHL = document.getElementById('presentationchl');
const screenpresentationMEX = document.getElementById('presentationmex');
const screenpresentationBRA = document.getElementById('presentationbra');
const screencountry = document.getElementById('screencountry');
const screenchart = document.getElementById('chart');
const screenResult = document.getElementById('screenresult');
const screenNot = document.getElementById('not');
const footer = document.getElementById('footer');
const Screenquienessomos = document.getElementById('quienessomos');
/* Login */
const EnterLogin = document.getElementById('enterlogin');
const user = document.getElementById('user');
const password = document.getElementById('password');
const enter = document.getElementById('password');
/* Seleccionar paises */
const elementUlCountry = document.getElementById('pais');
/* Data de indicadores por pais */
const hideallscreens = () => {
screenLogin.classList.remove('show');
screenSelectCountry.classList.remove('show');
screencountry.classList.remove('show');
screenchart.classList.remove('show');
screenpresentationPER.classList.remove('show');
screenpresentationMEX.classList.remove('show');
screenpresentationCHL.classList.remove('show');
screenpresentationBRA.classList.remove('show');
screenResult.classList.remove('show');
screenNot.classList.remove('show');
screenLogin.classList.add('hide');
screenSelectCountry.classList.add('hide');
screencountry.classList.add('hide');
screenchart.classList.add('hide');
screenpresentationPER.classList.add('hide');
screenpresentationMEX.classList.add('hide');
screenpresentationCHL.classList.add('hide');
screenpresentationBRA.classList.add('hide');
screenResult.classList.add('hide');
screenNot.classList.add('hide');
};
const showscreenenterLogin = () => {
hideallscreens();
screenSelectCountry.classList.add('show');
document.getElementById('body').classList.add('bodySelectCountry');
document.getElementById('body').classList.remove('body-login');
document.getElementById('head').classList.remove('hide');
screenNot.classList.remove('hide');
screenNot.classList.add('show');
footer.classList.remove('hide');
footer.classList.add('show');
};
const showscreenLogin = () => {
hideallscreens();
screenLogin.classList.add('show');
};
/* const showscreenSelectCountry = () => {
hideallscreens();
screenSelectCountry.classList.add('show');
}; */
const showscreencountry = () => {
hideallscreens();
};
const showscreenchart = () => {
hideallscreens();
screenchart.classList.add('show');
};
const showscreenempleo = () => {
screenempleo.classList.add('show');
screenpresentationPER.classList.remove('show');
screenpresentationPER.classList.add('hide');
};
const showscreenpresentationPER = () => {
hideallscreens();
screenSelectCountry.classList.add('show');
screenpresentationPER.classList.add('show');
};
const showscreenResult = () => {
hideallscreens();
screencountry.classList.add('show');
screenSelectCountry.classList.add('show');
screenResult.classList.add('show');
};
enter.addEventListener('keyup', (event) => {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById('enterlogin').click();
}
});
/* LOGIN */
EnterLogin.addEventListener('click', () => {
let userresult = user.value;
let passwordresult = password.value;
if (userresult === '1' && passwordresult === '1') {
showscreenenterLogin();
} else {
user.value = '';
password.value = '';
document.getElementById('mistakelogin').innerHTML = 'Usuario o contraseña incorrectos';
}
});
Screenquienessomos.addEventListener('click', () => {
showscreenenterLogin();
});
/* Funcion que pinta la lista de indicadores en HTML dinamicamente*/
let paintingList = (data, id) => {
let string = '';
data.forEach((elem, indi) => {
string += `<li id=${elem.indicatorName}><a id=${elem.indicatorCode} href="#">${elem.indicatorName}</a></li>`;
});
document.getElementById(id).innerHTML = string;
};
/* Clickear un país y obtener ID, que puede ser 'PER', 'CHL', 'BRA', 'MEX' para obtener sus indicadores */
let pais = '';
let tipoIndicador = '';
document.body.addEventListener('click', (event) => {
console.log(event.target.tagName);
if (event.target.tagName !== 'INPUT') {
if (event.target.tagName === 'LI') {
if (tipoIndicador !== '') {
document.getElementById('listsl').innerHTML = '';
document.getElementById('listhd').innerHTML = '';
document.getElementById('listsg').innerHTML = '';
document.getElementById('listse').innerHTML = '';
document.getElementById('listsp').innerHTML = '';
document.getElementById('listic').innerHTML = '';
document.getElementById('listsh').innerHTML = '';
document.getElementById('listpro').innerHTML = '';
document.getElementById('listms').innerHTML = '';
}
tipoIndicador = '';
pais = event.target.id;
pais = pais.toUpperCase();
hideallscreens();
document.getElementById('cont').classList.remove('newcont');
document.getElementById('cont').classList.add('cont');
if (pais === 'PER') {
screenpresentationPER.classList.add('show');
}
if (pais === 'CHL') {
screenpresentationCHL.classList.add('show');
}
if (pais === 'MEX') {
screenpresentationMEX.classList.add('show');
}
if (pais === 'BRA') {
screenpresentationBRA.classList.add('show');
}
screenSelectCountry.classList.add('show');
screencountry.classList.add('show');
} else if (event.target.tagName === 'A') {
tipoIndicador = event.target.id;
console.log(tipoIndicador);
} if (pais !== '') {
console.log(pais);
const indicadoresPorPaisyTipo = createdatanew(WORLDBANK, pais, tipoIndicador.toUpperCase());
console.log(indicadoresPorPaisyTipo);
if (tipoIndicador.length === 2 || tipoIndicador.length === 3) {
const idElementoLi = `list${tipoIndicador}`;
console.log(idElementoLi);
paintingList(indicadoresPorPaisyTipo, idElementoLi);
} else if (tipoIndicador.length > 3) {
console.log(tipoIndicador);
const idElementoLi = tipoIndicador;
const dataDeCodigoIndicador = createdatanew(WORLDBANK, pais, idElementoLi);
const createDataForTablas = dataDeCodigoIndicador[0].data;
console.log(createDataForTablas);
const indicatorName = dataDeCodigoIndicador[0].indicatorName;
console.log(indicatorName);
const newdata = CreateArray(createDataForTablas);
console.log(newdata);
document.getElementById('tabledivorderasc').innerHTML = '';
document.getElementById('prom').innerHTML = '';
showscreenResult();
createGrafic(newdata, indicatorName);
drawBasic2(dataInGrafic(newdata, newdata[0][0], newdata[newdata.length - 1][0]));
drawTable(dataInTable(newdata, newdata[0][0], newdata[newdata.length - 1][0]));
document.getElementById('prom').innerHTML = `El porcentaje promedio es: ${prom(newdata, newdata[0][0], newdata[newdata.length - 1][0])}`;
/* document.getElementById('cont').classList.remove('cont');
document.getElementById('cont').classList.add('newcont');*/
showscreenResult();
screenchart.classList.add('show');
}
}
}
});
let createGrafic = (newdata, indicatorName) => {
document.getElementById('indicatorname').innerHTML = indicatorName;
let multirange = document.getElementById('multirange');
multirange.innerHTML = `<div class='multi-range' data-lbound='${newdata[0][0]}' data-ubound='${newdata[newdata.length - 1][0]}' id="rango">
<hr/>
<input type='range' id="lbound" min='${newdata[0][0]}' max='${newdata[newdata.length - 2][0]}' step='1' value='${newdata[0][0]}'
oninput='this.parentNode.dataset.lbound=this.value'
/>
<input type='range' id="ubound" min='${newdata[1][0]}' max='${newdata[newdata.length - 1][0]}' step='1' value='${newdata[newdata.length - 1][0]}'
oninput='this.parentNode.dataset.ubound=this.value'
/>
</div>`;
const rangoInput = document.getElementById('rango');
rangoInput.addEventListener('change', (event) => {
let min;
let max;
let lboun = 0;
let uboun = 0;
if (event.target.id === 'lbound') {
lboun++;
min = event.target.value;
console.log(min);
} else {
uboun++;
max = event.target.value;
}
if (lboun === 0) {
min = document.getElementById('lbound').value;
}
if (uboun === 0) {
max = document.getElementById('ubound').value;
}
if (min > max) {
let minnew = min;
min = max;
max = minnew;
}
document.getElementById('prom').innerHTML = '';
document.getElementById('prom').innerHTML = `El porcentaje promedio es: ${prom(newdata, min, max)}`;
drawBasic2(dataInGrafic(newdata, min, max)); drawTable(dataInTable(newdata, min, max)); drawTableorder(dataInTableOrder(newdata, min, max));
});
document.getElementById('cont').classList.remove('cont');
document.getElementById('cont').classList.add('newcont');
showscreenResult();
screenchart.classList.add('show');
screencountry.classList.add('show');
};
let drawBasic2 = (datafilter) => {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', '% o escala');
data.addRows(datafilter);
var options = {
hAxis: {
title: 'Año'
},
vAxis: {
title: '% de indicador'
}
};
var chartnormal = new google.visualization.LineChart(document.getElementById('chart'));
chartnormal.draw(data, options);
};
let drawTable = (datafilter) => {
var data = new google.visualization.DataTable();
data.addColumn('number', 'año');
data.addColumn('number', '% indicador');
data.addRows(datafilter);
var table = new google.visualization.Table(document.getElementById('tablediv'));
table.draw(data, {
showRowNumber: false,
width: '58%',
height: '50%'
});
};
let drawTableorder = (inmatrizorder) => {
var data = new google.visualization.DataTable();
data.addColumn('number', 'año');
data.addColumn('number', '% indicador');
data.addRows(inmatrizorder);
var table = new google.visualization.Table(document.getElementById('tabledivorderasc'));
table.draw(data, {
showRowNumber: false,
width: '58%',
height: '50%'
});
};<file_sep>/src/index.html
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Lovers</title>
<link rel="stylesheet" href="style.css" />
</head>
<body id="body" class="body-login">
<!--HEADER-->
<header id="head" class="hide">
<section class="order">
<div id="quienessomos" class="head"><a href="#">Latin Data</a></div>
<img class="logo-head" src="img/Logo.png" alt="imagen logotipo"/>
</section>
<section id="screen-select-country" class="hide">
<div class="selectcountry"><h>Seleccionar país</h></div>
<div id="countries" class="hide">
<ul id="pais">
<li id="per">Perú</li>
<li id="chl">Chile</li>
<li id="mex">México</li>
<li id="bra">Brasil</li>
</ul>
</div>
</section>
</header>
<!---ScreenLogin-->
<section id="boton-login" class="master-login">
<section class="background-login">
<div class="all-logo">
<img class="logo" src="img/Logo.png" alt = "logo del banco mundial"/>
<div id="login">Latin Data</div>
</div>
<form>
<section class="register">
<h2 class="user">Usuario</h2>
<input class="writeuser" type="text" id="user">
</section>
<section class="register">
<h2 class="user">Contraseña</h2>
<input class="writeuser" type="password" id="password">
</section>
<p id="mistakelogin" class="error"></p>
<section class="buttonentry">
<input class="buttonlogin" type="button" value="INGRESAR" id="enterlogin">
</section>
<!-- <a href="">¿Olvidaste Contraseña?</a></br>
<a href="">¿No tienes una cuenta?<strong> Registrate</strong></a><br/></a><br/>-->
</form>
</section>
</section>
<!---ScreenNoticias-->
<section id="not" class="hide">
<section id="banner" class="bank">
<div class="contenedor">
<div class="contenedor-bm">
<h1> Banco Mundial</h1>
<p class="info-bm"> Los datos y las investigaciones sirven para establecer prioridades,
intercambiar conocimientos acerca de las medidas que funcionan y medir los avances conseguidos.</p>
<a href="https://www.bancomundial.org/">Leer más</a>
</div>
</div>
</section>
<section id="info" >
<h2 class="titu">NOTICIAS</h2>
<div class="info-colum info-colum1">
<div class="info-descrip">
<h3 class="decrip-titu">El empleo, núcleo del desarrollo:</h3>
<p class="text">Transformar economías y sociedades mediante puestos de trabajo sostenibles</p>
<a class="link"
href="https://www.bancomundial.org/es/results/2018/02/13/jobs-at-the-core-of-development">Más</a>
</div>
</div>
<div class="info-colum info-colum2">
<div class="info-descrip">
<h3 class="decrip-titu">Fin a la violencia en América Latina:</h3>
<p class="text">Una mirada a la prevención desde la infancia hasta la edad adulta</p>
<a class="link"
href="https://www.bancomundial.org/es/results/2018/05/17/fin-a-la-violencia-en-america-latina-una-mirada-a-la-prevencion-desde-la-infancia-hasta-la-edad-adulta">Más</a>
</div>
</div>
<div class="info-colum info-colum3">
<div class="info-descrip">
<h3 class="decrip-titu">Combate a la desnutrición en Perú: </h3>
<p class="text">Mejoras en la demanda, oferta y administración de servicios de salud y nutrición en tres
regiones.</p>
<a class="link"
href="https://www.bancomundial.org/es/results/2018/04/03/stronger-open-trade-policies-enables-economic-growth-for-all">Más</a>
</div>
</div>
<div class="info-colum info-colum4">
<div class="info-descrip">
<h3 class="decrip-titu">Mejorar los sistemas de información del agua y el saneamiento: </h3>
<p class="text">En lugares rurales de América Latina y el Caribe</p>
<a class="link"
href="https://www.bancomundial.org/es/results/2017/04/04/improving-rural-water-sanitation-information-systems-latinamerica">Más</a>
</div>
</div>
</section>
<section id="whos" >
<div>
<div class="mision">
<h2>Nuestra misión </h2><br>
<h3>Organizar la información de países Latinoamericanos para que todos puedan acceder a ella, entenderla y usarla</h3>
</div>
<div id="dat">
<h1 class="dato">Empieza la busqueda</h1>
<h2 class="datos">Elige el país que desees su información</h2>
</div>
<div class="bloque">
<div id="peru" class="pais">Perú </div>
<div id="chile" class="pais">Chile</div>
<div id="brasil" class="pais">Brasil</div>
<div id="mexico" class="pais">Mexico</div>
</div>
</div>
</section>
</section>
<!---ScreenNoticias-->
<main id="main">
<div id="cont" class="cont">
<div id="presentationper" class="sli hide">
<section class="contselect" >
<h>Conoce el flujo de los Indicadores de Perú al seleccionar un indicador</h>
</section>
<slider>
<slide><div class="contentancla"><a href="https://peru21.pe/peru/promperu-peru-recibe-cuatro-premios-world-travel-awards-sudamerica-2019-490140" target="_blank" class="ancla">Perú recibe cuatro premios en los World Travel Awards Sudamérica 2019</a></div>
</slide>
<slide><div class="contentancla"><a href="https://peru21.pe/lima/igualdad-genero-unesco-explica-conceptos-claves-debatir-informado-67830" target="_blank" class="ancla">¿Sabes qué es la igualdad de género? Unesco explica conceptos claves para debatir bien informado</a></div>
</slide>
<slide><div class="contentancla"><a href="https://elpais.com/cultura/2019/06/28/actualidad/1561675399_810135.html" target="_blank" class="ancla"> “Mi más grande influencia culinaria es mi madre”</a></div>
</slide>
<slide><div class="contentancla"><a href="https://www.zankyou.com.pe/p/dia-de-la-mujer-imperdibles-historias-de-peruanas-del-siglo-xxi-que-nos-inspiran" target="_blank" class="ancla">Día de la Mujer: imperdibles historias de peruanas del siglo XXI que nos inspiran</a></div>
</slide>
</slider>
</div>
<div id="presentationchl" class="sli hide">
<section class="contselect" >
<p>Conoce el flujo de los Indicadores de Chile al seleccionar un indicador</p>
</section>
<slider>
<slide><div class="contentancla"><a href="https://peru21.pe/peru/promperu-peru-recibe-cuatro-premios-world-travel-awards-sudamerica-2019-490140" target="_blank" class="ancla">Perú recibe cuatro premios en los World Travel Awards Sudamérica 2019</a></div>
</slide>
<slide><div class="contentancla"><a href="https://peru21.pe/lima/igualdad-genero-unesco-explica-conceptos-claves-debatir-informado-67830" target="_blank" class="ancla">¿Sabes qué es la igualdad de género? Unesco explica conceptos claves para debatir bien informado</a></div>
</slide>
<slide><div class="contentancla"><a href="https://elpais.com/cultura/2019/06/28/actualidad/1561675399_810135.html" target="_blank" class="ancla"> “Mi más grande influencia culinaria es mi madre”</a></div>
</slide>
<slide><div class="contentancla"><a href="https://www.zankyou.com.pe/p/dia-de-la-mujer-imperdibles-historias-de-peruanas-del-siglo-xxi-que-nos-inspiran" target="_blank" class="ancla">Día de la Mujer: imperdibles historias de peruanas del siglo XXI que nos inspiran</a></div>
</slide>
</slider>
</div>
<div id="presentationmex" class="sli hide">
<section class="contselect" >
<p>Conoce el flujo de los Indicadores de México al seleccionar un indicador</p>
</section>
<slider>
<slide><div class="contentancla"><a href="https://peru21.pe/peru/promperu-peru-recibe-cuatro-premios-world-travel-awards-sudamerica-2019-490140" target="_blank" class="ancla">Perú recibe cuatro premios en los World Travel Awards Sudamérica 2019</a></div>
</slide>
<slide><div class="contentancla"><a href="https://peru21.pe/lima/igualdad-genero-unesco-explica-conceptos-claves-debatir-informado-67830" target="_blank" class="ancla">¿Sabes qué es la igualdad de género? Unesco explica conceptos claves para debatir bien informado</a></div>
</slide>
<slide><div class="contentancla"><a href="https://elpais.com/cultura/2019/06/28/actualidad/1561675399_810135.html" target="_blank" class="ancla"> “Mi más grande influencia culinaria es mi madre”</a></div>
</slide>
<slide><div class="contentancla"><a href="https://www.zankyou.com.pe/p/dia-de-la-mujer-imperdibles-historias-de-peruanas-del-siglo-xxi-que-nos-inspiran" target="_blank" class="ancla">D<NAME> la Mujer: imperdibles historias de peruanas del siglo XXI que nos inspiran</a></div>
</slide>
</slider>
</div>
<div id="presentationbra" class="sli hide">
<section class="contselect" >
<p>Conoce el flujo de los Indicadores de Brasil al seleccionar un indicador</p>
</section>
<slider>
<slide><div class="contentancla"><a href="https://peru21.pe/peru/promperu-peru-recibe-cuatro-premios-world-travel-awards-sudamerica-2019-490140" target="_blank" class="ancla">Perú recibe cuatro premios en los World Travel Awards Sudamérica 2019</a></div>
</slide>
<slide><div class="contentancla"><a href="https://peru21.pe/lima/igualdad-genero-unesco-explica-conceptos-claves-debatir-informado-67830" target="_blank" class="ancla">¿Sabes qué es la igualdad de género? Unesco explica conceptos claves para debatir bien informado</a></div>
</slide>
<slide><div class="contentancla"><a href="https://elpais.com/cultura/2019/06/28/actualidad/1561675399_810135.html" target="_blank" class="ancla"> “Mi más grande influencia culinaria es mi madre”</a></div>
</slide>
<slide><div class="contentancla"><a href="https://www.zankyou.com.pe/p/dia-de-la-mujer-imperdibles-historias-de-peruanas-del-siglo-xxi-que-nos-inspiran" target="_blank" class="ancla"><NAME>: imperdibles historias de peruanas del siglo XXI que nos inspiran</a></div>
</slide>
</slider>
</div>
<section id="screencountry" class="hide">
<section class="buttonindicator">
<a class="titleindicators">Indicadores</a>
</section>
<div class="mainmenu">
<div class="menu">
<ul id="list-all-indicators">
<li><a class="title-type-indicator" id="sl" href="#">Empleo</a>
<ul id="listsl">
</ul>
</li>
<li><a class="title-type-indicator" id="hd" href="#">Desarrollo Social</a>
<ul id="listhd">
</ul></li>
<li><a class="title-type-indicator" id="sg" href="#">Género</a>
<ul id="listsg">
</ul></li>
<li><a class="title-type-indicator" id="se" href="#">Educación</a>
<ul id="listse">
</ul></li>
<li><a class="title-type-indicator" id="sp" href="#">Población</a>
<ul id="listsp">
</ul></li>
<li><a class="title-type-indicator" id="ic" href="#">Sector Privado</a>
<ul id="listic">
</ul></li>
<li><a class="title-type-indicator" id="sh" href="#">Salud</a>
<ul id="listsh">
</ul></li>
<li><a class="title-type-indicator" id="pro" href="#">Protección Social</a>
<ul id="listpro">
</ul></li>
<li><a class="title-type-indicator" id="ms" href="#">Sector Público</a>
<ul id="listms">
</ul></li>
</ul>
</div>
</div>
</section>
<section id="screenresult" class="hide">
<div class="indicatorname" ><h id="indicatorname"></h></div><br>
<div id="multirange" class="multirange"></div>
<div id="chart"></div><br>
<div class="tableyprom">
<div id="prom" class="prom"></div><br>
<div id="tablediv" class="tablediv"></div><br>
<div class="prom">Ordenar datos según:</div><br>
<div id="ordertable" class="hide">
<ul>
<li id="asc">De menos a más</li>
<li id="desc">De más a menos</li>
</ul>
</div><br>
</div>
<div id="tabledivorderasc"></div>
<div id="orderchartdiv"></div>
</section>
</div>
<!-- </section>-->
</main>
<footer id="footer" class="footer hide">
<a class="foot" href="https://github.com/thanet0109">© Fiorella</a>&<a class="foot"
href="https://github.com/yomiramontalvo">Yomira</a>
</footer>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="./data/worldbank/worldbank.js"></script>
<script src="data.js"></script>
<script src="main.js"></script>
</body>
</html> | d6f7dddb342f941393ecc5786109ceaf684c8685 | [
"Markdown",
"JavaScript",
"HTML"
] | 3 | Markdown | yomiramontalvo/LIM010-data-lovers | 036b92e9d138b5b9c3475dd851287cacca547c4c | 6b22899ff06ddefc2b3225cf19c4e09179b1ed0d |
refs/heads/master | <file_sep>
module.exports = {
run: function(creep){
//checks if creep has energy to work
if(creep.memory.working && creep.carry.energy == 0) {
creep.memory.working = false;
}
if(!creep.memory.working && creep.carry.energy == creep.carryCapacity) {
creep.memory.working = true;
}
//if creep has energy then fill structures that require energy
if (creep.memory.working){
//looks for structures with less than full energy
var project = creep.pos.findClosestByPath(FIND_MY_STRUCTURES, {
filter: (s) => s.energy < s.energyCapacity});
creep.say("I'm working on " + project);
if(project == undefined){
project = creep.room.controller;
if( creep.upgradeController(project) == ERR_NOT_IN_RANGE){
creep.moveTo(project,{visualizePathStyle: {stroke: '#ffffff'}});
}
}
// transfers energy to building
else if (creep.transfer(project, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(project,{visualizePathStyle: {stroke: '#ffffff'}});
}
}else{
//if creep has no energy it gets energy from storage
var source = creep.pos.findClosestByPath(FIND_STRUCTURES, {
filter: (s) => s.structureType == STRUCTURE_STORAGE
&& s.store[RESOURCE_ENERGY] > 0});;
//if storage is empty get energy from mining energy node
if(source == null){
source = creep.pos.findClosestByPath(FIND_SOURCES);
}
creep.say("I'm mining");
if (creep.withdraw(source, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){
creep.moveTo(source,{visualizePathStyle: {stroke: '#ffffff'}});
}else if(creep.harvest(source) == ERR_NOT_IN_RANGE){
creep.moveTo(source,{visualizePathStyle: {stroke: '#ffffff'}});
}
}
}
};
<file_sep>module.exports = {
run: function(creep){
//determines if the creep is full of energy to do work
if(creep.memory.working && creep.carry.energy == 0) {
creep.memory.working = false;
}
if(!creep.memory.working && creep.carry.energy == creep.carryCapacity) {
creep.memory.working = true;
}
//if creep has energy to work work on construction sites
if (creep.memory.working){
//looks for the closest construction project
var project = creep.pos.findClosestByPath(FIND_CONSTRUCTION_SITES);
if(project == undefined){
project = creep.room.controller;
if( creep.upgradeController(project) == ERR_NOT_IN_RANGE){
creep.moveTo(project,{visualizePathStyle: {stroke: '#ffffff'}});
}
}else if (creep.build(project) == ERR_NOT_IN_RANGE) {
creep.moveTo(project, {visualizePathStyle: {stroke: '#ffffff'}});
}
}else{
//If energy is empty then get energy from storage
var source = creep.pos.findClosestByPath(FIND_STRUCTURES, {
filter: (s) => s.structureType == STRUCTURE_STORAGE
&& s.store[RESOURCE_ENERGY] > 0});;
//if no energy in storage then mine from a energy node
if(source == null){
source = creep.pos.findClosestByPath(FIND_SOURCES);
}
creep.say("I'm mining");
if (creep.withdraw(source, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){
creep.moveTo(source);
}else if(creep.harvest(source) == ERR_NOT_IN_RANGE){
creep.moveTo(source);
}
}
}
};
| 7705ddd1faa7e3a10df31652f7bb3c8058023e70 | [
"JavaScript"
] | 2 | JavaScript | xNyri/screepsCode | 1a83e58084a7ce677a9a78cec5ed98c3bb8ac45a | 79f21dcac03a5be4e7c47d451502b25a31fa7ace |
refs/heads/master | <repo_name>GrayNeko/Test<file_sep>/helpdesk.rb
puts "Vul de naam van de klant in"
naam = gets.chomp
puts "Wat is de datum?"
datum = gets.chomp
puts "Wat is de modem van de klant?"
modem = gets.chomp
puts "Klantnaam: #{naam} Datum: #{datum} Modem van klant: #{modem}"
puts "Met welk abonnement heeft de klant een probleem(internet/bellen/televisie)?"
probleem = gets.chomp
if probleem == "internet" then
puts "Kunt u browsen naar www.nu.nl(ja/nee)?"
browsen = gets.chomp
puts "Reageert de pagina snel als u f5 heeft ingedrukt(ja/nee)?"
laden = gets.chomp
puts "Browsen naar nu.nl lukt." if browsen == "ja"
puts "Browsen naar nu.nl lukt niet." if browsen == "nee"
puts "Internet laad snel." if laden == "ja"
puts "Internet laad niet snel." if laden == "nee"
end
if probleem == "bellen" then
puts "Hoort u een kiestoon(ja/nee)?"
kiestoon = gets.chomp
puts "Kunt u gebeld worden(ja/nee)?"
gebeldworden = gets.chomp
puts "Kunt u bellen met uw mobiel(ja/nee)?"
mobiel = gets.chomp
puts "U kunt wel bellen." if kiestoon == "ja"
puts "U kunt niet bellen." if kiestoon == "nee"
puts "U kunt wel gebeld worden." if gebeldworden == "ja"
puts "U kunt niet gebeld worden." if gebeldworden == "nee"
puts "U kunt wel bellen met uw mobiel." if mobiel == "ja"
puts "U kunt niet bellen met uw mobiel." if mobiel == "nee"
end
if probleem == "televisie" then
puts "Hoeveel tv's heeft u?"
aantalTV = gets.chomp.to_i
if aantalTV > 1
puts "Is de splitter goed aangesloten(ja/nee)?"
splitter = gets.chomp
end
puts "Is uw settopbox goed aangesloten?(ja/nee)"
settopbox = gets.chomp
puts "Worden de zenders gevonden(ja/nee)?"
zenders = gets.chomp
puts "De splitter is goed aangesloten." if splitter == "ja"
puts "De splitter is niet goed aangesloten." if splitter == "nee"
puts "Uw settopbox doet het wel." if settopbox == "ja"
puts "Uw settopbox doet het niet." if settopbox == "nee"
puts "Uw aansluiting is goed." if zenders == "ja"
puts "Uw aansluiting is niet goed." if zenders == "nee"
end<file_sep>/README.md
# Test
this was made for a test
| 33b87e1583e4a13fd4771485a354fe91c952e27c | [
"Markdown",
"Ruby"
] | 2 | Ruby | GrayNeko/Test | a2839fc37e92edb49de9fde6f7a91ca343ecc2ab | 2922937ed90773b9adf731e7872b0b84acbc4865 |
refs/heads/main | <repo_name>jadeSales/Projeto_BateriaEletronica<file_sep>/script.js
// document.body = pega qualquer ação da body toda
// addEventListener = interpreta eventos/clicks que ocorrem na página (clics, digitação)
// keyup = tecla pressiona-solta / keydown = tecla pressionada
document.body.addEventListener('keyup', (event)=>{
playSound(event.code.toLowerCase()); // funcao tocarMusica
});
//pega elemento button do html e add o evento ao clicar
document.querySelector('.composer button').addEventListener('click', () => {
let song = document.querySelector('#input').value; //variavel que pega o "valor" que foi digitado
if(song !== '') { // se variavel song for diferente de vazio ou seja, tiver coisas digitadas
let songArray = song.split(''); // var songArray pega a sequencia digitada e cria uma lista/array
playComposition(songArray); //função que possui a array
}
});
function playSound(sound) {
let audioElement = document.querySelector(`#s_${sound}`);
let keyElement = document.querySelector(`div[data-key="${sound}"]`);
if(audioElement) {
audioElement.currentTime = 0; // faz o som tocar novamente sem pausa
audioElement.play();
}
if(keyElement) {
keyElement.classList.add('active'); // pega classe do css e ativa a estilização
setTimeout(()=>{ //faz a ação acontecer conforme um tempo determinado
keyElement.classList.remove('active'); // pega a classe do css que estava ativa e remove
}, 300); // em 300 milésimos
}
}
function playComposition(songArray) {
//fazer o loop esperar e acontecer com tempo determinado
let wait = 0;
for(let songItem of songArray) { //loop/repetição var songItem possui cada item da array
setTimeout(() => {
playSound(`key${songItem}`); //ao apertar o botao, toca o que foi digitado
}, wait);
wait += 250;
}
}<file_sep>/README.md
# Projeto_BateriaEletronica
Projeto construido seguindo o passo a passo das aulas de JavaScript.
O projeto é uma bateria eletrônica, que ao apertar algumas teclas específicas, toca os sons de cada parte de uma bateria.
Também é possível digitar as letras e montar uma composição.
No CSS, acrescentei imagem de fundo e a propriedade box-shadow.
| a50b76aae2535a1117b24b3314f04f6d39026a1b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jadeSales/Projeto_BateriaEletronica | 1b8044b9777fa42658c11dfd75268c2b8e31633c | 6fe674d05f7e163909856a53eb582dd8fd8c407f |
refs/heads/master | <repo_name>AleksandarDmitrovic/Minesweeper<file_sep>/src/components/Cell.js
import randomColor from '../helpers/randomColor';
import '../styling/Cell.css';
export default function Cell(props) {
const { data, flagCell, revealCell } = props;
const cellstyle = {
background: data.revealed
? data.value === "X"
? randomColor()
: reaveledChexPattern(data.x, data.y)
: chexPattern(data.x, data.y),
color: numColorCode(data.value)
}
const onClickReveal = (event) => {
if (data.flagged) {
return;
}
console.log(event.type);
revealCell(data.x, data.y);
};
const onContextMenuFlag = (event) => {
event.preventDefault();
flagCell(data.x, data.y)
};
return (
<div
onContextMenu={(event) => onContextMenuFlag(event)}
onClick={(event) => onClickReveal(event)}
style={cellstyle}
className="cell"
>
{data.flagged && !data.revealed ? (
"🚩"
) : data.revealed && data.value !== 0 ? (
data.value === "X" ? (
"💣"
) : (
data.value
)
) : (
""
)}
</ div>
)
};
const reaveledChexPattern = (x, y) => {
if (x % 2 === 0 && y % 2 === 0) {
return "#e5c29f";
} else if (x % 2 === 0 && y % 2 !== 0) {
return "#d7b899";
} else if (x % 2 !== 0 && y % 2 === 0) {
return "#d7b899";
} else {
return "#e5c29f";
}
};
const chexPattern = (x, y) => {
if (x % 2 === 0 && y % 2 === 0) {
return "#aad751";
} else if (x % 2 === 0 && y % 2 !== 0) {
return "#a2d249";
} else if (x % 2 !== 0 && y % 2 === 0) {
return "#a2d249";
} else {
return "#aad751";
}
};
const numColorCode = (num) => {
if (num === 1) {
return "#1976d2";
} else if (num === 2) {
return "#388d3c";
} else if (num === 3) {
return "#d33030";
} else if (num === 4) {
return "#7c21a2";
} else if (num === 5) {
return "#f70c0c";
} else {
return "#ff0000";
}
};<file_sep>/src/components/Board.js
import { useEffect, useState } from "react"
import createBoard from "../helpers/createBoard";
import Cell from "./Cell";
import revealed from "../helpers/reveal";
import Modal from "./Modal";
import Timer from "./Timer";
export default function Board() {
const [grid, setGrid] = useState([]);
const [nonMineCount, setNonMineCount] = useState(0);
const [mineLocations, setMineLocations] = useState([]);
const [gameOver, setGameOver] = useState(false);
// ComponentDidMount
useEffect(() => {
freshBoard();
}, [])
//Creating a board
const freshBoard = () => {
const newBoard = createBoard(16, 16, 40);
setNonMineCount(16 * 16 - 40);
setMineLocations(newBoard.mineLocation);
setGrid(newBoard.board);
};
// Restart Game
const restartGame = () => {
freshBoard();
setGameOver(false);
};
// Reveal Cell
const revealCell = (x, y) => {
// Reveal once only
if (grid[x][y].revealed || gameOver) {
return;
}
let newGrid = JSON.parse(JSON.stringify(grid));
if (newGrid[x][y].value === "X") {
for (let i = 0; i < mineLocations.length; i++) {
newGrid[mineLocations[i][0]][mineLocations[i][1]].revealed = true;
}
setGrid(newGrid);
setGameOver(true);
} else {
let newRevealedBoard = revealed(newGrid, x, y, nonMineCount)
setGrid(newRevealedBoard.arr);
setNonMineCount(newRevealedBoard.newNonMinesCount)
if (newRevealedBoard.newNonMinesCount === 0) {
setGameOver(true);
}
}
}
const flagCell = (x, y) => {
let newBoardValues = JSON.parse(JSON.stringify(grid));
newBoardValues[x][y].flagged = !newBoardValues[x][y].flagged;
setGrid(newBoardValues);
}
return (
<div>
<Timer gameOver={gameOver} />
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', position: "relative" }}>
{gameOver && <Modal restartGame={restartGame} />}
{grid.map((row, index1) => {
return (
<div style={{ display: "flex" }} key={index1}>
{row.map((cell, index2) => {
return (
<Cell
data={cell}
flagCell={flagCell}
revealCell={revealCell}
key={index2}
/>
)
})}
</div>
)
})}
</div>
</div>
)
} | c135f8c04a2a1c3688148d4f91fefc25b3e1abe4 | [
"JavaScript"
] | 2 | JavaScript | AleksandarDmitrovic/Minesweeper | d318c532dae28ae9b911c40a1ee6baee3d5d3e46 | cc4d096fb22fd5224e36b0b33f94bf58757f919f |
refs/heads/master | <file_sep>import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { MongoRepository, ObjectID } from 'typeorm';
import { UserInput } from './user.input';
import * as uuid from 'uuid';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: MongoRepository<User>,
) {}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async findOne(userID: string): Promise<User> {
Logger.log('run findOne');
return await this.userRepository.findOne({ _id: userID });
}
async create(input: UserInput): Promise<any> {
Logger.log('run create account');
const user = new User();
user._id = uuid.v4();
user.username = input.username;
user.password = <PASSWORD>;
let rs;
try {
rs = await this.userRepository.save(user);
} catch (error) {
Logger.error(error.code, `mess =>: ${error.errmsg}`);
throw new HttpException(
`${
error.code === 11000
? user.username + ' already exists'
: 'bad request'
}`,
HttpStatus.BAD_REQUEST,
);
}
return rs;
}
}
<file_sep>import {
Entity,
Column,
ObjectIdColumn,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity()
export class User {
@ObjectIdColumn({ unique: true })
_id: string;
@Column({ unique: true })
username: string;
@Column()
password: string;
}
| 6fbcde8be877b2af769f9532271bb739fcfc3604 | [
"TypeScript"
] | 2 | TypeScript | AnhHoTrungDev/test-deploy-nest | ba4b061a4d3c02396e7f48e2b43b71eb6eac1f54 | b73065c0b0dbdc5d9126061a2d8a05a4c855218b |
refs/heads/main | <file_sep>import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
// 2.25
Scanner scan = new Scanner(System.in);
System.out.println("Check if number is divisible by 3");
System.out.println("======================================");
System.out.println("Enter a number: ");
int n = scan.nextInt();
if(n % 3 == 0 ) {
System.out.println("This is divisible by 3");
} else {
System.out.println("not divisible by 3");
}
//2.26
System.out.println("Check if number tripled is a multiple of number doubled");
System.out.println("======================================");
System.out.println("Enter number to be tripled");
int n1 = scan.nextInt();
System.out.println("Enter number to be doubled");
int b = scan.nextInt();
int x = n1 *3;
int y = b*2;
if(x % y == 0) {
System.out.println("is a multiple");
} else {
System.out.println("isnt a multiple");
}
//2.28
System.out.println("Determine the diameter, circumference, and area dependent on a circles radius");
System.out.println("======================================");
System.out.println("Enter a radius");
int r = scan.nextInt();
scan.close();
double diameter = 2*r;
double circumference = 2* Math.PI* r;
double area = Math.PI* (r*r);
System.out.printf("Diameter: " + "%f%n", diameter);
System.out.printf("Circumference: " +"%f%n", circumference);
System.out.printf("Area: " +"%f%n", area);
}
}
| b78dc91ca4e91bcba3110ed83fd66fc55bf988ec | [
"Java"
] | 1 | Java | kayronmacon/Chapter2Questions | 274aaeab106f4b2ad783f5062567b3540206225e | cde458f012e6510ddbf4fc34fe5d03f764f2073b |
refs/heads/v4.0 | <repo_name>crocodic-studio/laravel-model<file_sep>/src/Core/ModelAbstract.php
<?php
/**
* Created by PhpStorm.
* User: User
* Date: 2/25/2020
* Time: 10:11 PM
*/
namespace Crocodic\LaravelModel\Core;
abstract class ModelAbstract
{
public function setConnection()
{
return null;
}
public function setTable()
{
return null;
}
public function setPrimaryKey()
{
return null;
}
}<file_sep>/src/Helpers/BuilderMacro.php
<?php
namespace Crocodic\LaravelModel\Helpers;
use Illuminate\Database\Query\Builder;
class BuilderMacro
{
public static function registerMacro()
{
Builder::macro("addSelectTable", function($table, $prefix = null, $exceptColumns = []) {
$fields = Helper::getFields($table);
foreach($fields as $field) {
if(count($exceptColumns) && in_array($field,$exceptColumns)) continue;
$prefix = ($prefix) ? $prefix : $table;
$this->addSelect($table.".".$field." as ".$prefix."_".$field);
}
return $this;
});
Builder::macro("withTable", function($table, $selectionPrefix = null, $exceptColumns = [], $first = null, $operator = "=", $second = null) {
/** @var \Crocodic\LaravelModel\Core\Builder $this */
if(is_array($table)) {
foreach($table as $tbl) {
$first = ($first) ? $first : $tbl.".id";
$second = ($second) ? $second : $this->from."_id";
$this->leftJoin($tbl,$first,$operator,$second);
$this->addSelectTable($tbl, $selectionPrefix, $exceptColumns);
}
} else {
$first = ($first) ? $first : $table.".id";
$second = ($second) ? $second : $table."_id";
$this->leftJoin($table, $first, $operator, $second);
$this->addSelectTable($table, $selectionPrefix, $exceptColumns);
}
return $this;
});
Builder::macro("like", function($column, $keyword) {
/** @var \Crocodic\LaravelModel\Core\Builder $this */
if(substr($keyword,0,1) != "%" && substr($keyword,-1,1) != "%") {
$keyword = "%".$keyword."%";
}
$this->where($column, "like", "%".$keyword."%");
});
}
}<file_sep>/src/LaravelModelServiceProvider.php
<?php
namespace Crocodic\LaravelModel;
use Crocodic\LaravelModel\Commands\MakeModel;
use Crocodic\LaravelModel\Core\LaravelModelTemporary;
use Crocodic\LaravelModel\Helpers\BuilderMacro;
use Crocodic\LaravelModel\Helpers\Helper;
use Illuminate\Database\Connection;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\DatabaseTransactionsManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Database\Schema\Grammars\PostgresGrammar;
use Illuminate\Database\Schema\Grammars\SqlServerGrammar;
use Illuminate\Support\ServiceProvider;
class LaravelModelServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
Builder::macro('with', function($table, $first, $foreignKey) {
$result = $this->getConnection()
->leftJoin($table, $first, "=", $foreignKey);
$fields = Helper::getFields($table);
foreach($fields as $field) {
$result->addSelect($table.".".$field." as ".$table."_".$field);
}
return $result;
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('LaravelModel', function () {
return true;
});
$this->commands([ MakeModel::class ]);
$this->app->singleton('LaravelModelTemporary',LaravelModelTemporary::class);
BuilderMacro::registerMacro();
}
}
<file_sep>/src/Core/ModelSetter.php
<?php
/**
* Created by PhpStorm.
* User: User
* Date: 3/18/2020
* Time: 12:17 AM
*/
namespace Crocodic\LaravelModel\Core;
trait ModelSetter
{
/**
* ModelSetter constructor.
* @param null $row
*/
public function __construct($row = null)
{
if($row) {
foreach($row as $key=>$value) {
$this->{$key} = $value;
}
}
}
public function set($column, $value) {
$this->{$column} = $value;
}
/**
* @return string|string[]
* @throws \ReflectionException
*/
private function getTableFromClass(): string
{
return str_replace("_model","", $this->convertPascalCaseToKebabCase( (new \ReflectionClass($this))->getShortName() ));
}
private function getDefaultPrimaryKey()
{
return "id";
}
private function convertPascalCaseToKebabCase($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
/**
* @param $result
* @return static[]
*/
private static function listSetter($result) {
$final = [];
foreach($result as $item) {
$model = new static();
foreach($item as $key=>$val) {
$model->set($key,$val);
}
$final[] = $model;
}
return $final;
}
/**
* @param $result
* @return static
*/
private static function objectSetter($result) {
$model = new static();
if($result) {
foreach($result as $key=>$val) {
$model->set($key,$val);
}
}
return $model;
}
public function __toString()
{
return $this->id;
}
}<file_sep>/src/Core/Model.php
<?php
/**
* Created by PhpStorm.
* User: User
* Date: 2/14/2020
* Time: 1:28 PM
*/
namespace Crocodic\LaravelModel\Core;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
class Model extends ModelAbstract
{
use ModelSetter;
public function __construct($row = null)
{
if(!is_null($row)) {
foreach($row as $key=>$value) {
$this->{$key} = $value;
}
}
}
public static function getTable()
{
$static = new static;
return $static->setTable() ? $static->setTable() : $static->getTableFromClass();
}
public static function getPrimaryKey()
{
$static = new static;
return $static->setPrimaryKey() ? $static->setPrimaryKey() : $static->getDefaultPrimaryKey();
}
public static function getConnection()
{
$static = new static;
return $static->setConnection() ? $static->setConnection() : config("database.default", "mysql");
}
/**
* Get last record id
* @return mixed
*/
public static function lastId() {
return app('db')->table(static::getTable())->max(static::getPrimaryKey());
}
/**
* A one-to-many relationship
* @param string $modelName Parent model class name
* @param string|null $foreignKey
* @param string|null $localKey
* @param callable|null $condition Add condition with Builder Query
* @return mixed
*/
public function hasMany(string $modelName, string $foreignKey = null, string $localKey = null, callable $condition = null) {
$childModel = new $modelName();
$parentModel = new static();
$foreignKey = ($foreignKey) ? $foreignKey : $parentModel::getTable()."_".$parentModel::getPrimaryKey();
$localKey = ($localKey) ? $localKey : $parentModel::getPrimaryKey();
$localKey = $this->$localKey;
$childQuery = $childModel::where($foreignKey, "=", $localKey);
if(isset($condition) && is_callable($condition)) $childQuery = call_user_func($condition, $childQuery);
return $childQuery->get();
}
/**
* A one-to-one relationship
* @param string $modelName
* @param string|null $foreignKey
* @param string|null $localKey
* @return static
*/
public function belongsTo(string $modelName, string $foreignKey = null, string $localKey = null) {
$childModel = new $modelName();
$parentModel = new static();
$foreignKey = ($foreignKey) ? $foreignKey : $parentModel::getTable()."_".$parentModel::getPrimaryKey();
$localKey = ($localKey) ? $localKey : $parentModel::getPrimaryKey();
$localKey = $this->$localKey;
return new static($childModel::where($foreignKey, "=", $localKey)->first());
}
/**
* @return \Crocodic\LaravelModel\Core\Builder
*/
public static function table()
{
return app('db')->table(static::getTable());
}
/**
* @param int $limit
* @param callable|null $query
* @return LengthAwarePaginator
*/
public static function paginate(int $limit, callable $query = null): LengthAwarePaginator
{
$data = static::table();
if(!is_null($query) && is_callable($query)) {
$data = call_user_func($query, $data);
}
return $data->paginate($limit);
}
/**
* @param $foreignTable
* @param $foreignTablePrimary
* @param $foreignColumn
* @return Builder
*/
public static function join($foreignTable, $foreignTablePrimary, $foreignColumn)
{
return static::table()->join($foreignTable, $foreignTablePrimary, $foreignColumn);
}
/**
* @param $foreignTable
* @param $foreignTablePrimary
* @param $foreignColumn
* @return Builder
*/
public static function leftJoin($foreignTable, $foreignTablePrimary, $foreignColumn)
{
return static::table()->leftJoin($foreignTable, $foreignTablePrimary, $foreignColumn);
}
/**
* @param $foreignTable
* @param $foreignTablePrimary
* @param $foreignColumn
* @return Builder
*/
public static function rightJoin($foreignTable, $foreignTablePrimary, $foreignColumn)
{
return static::table()->rightJoin($foreignTable, $foreignTablePrimary, $foreignColumn);
}
/**
* @param $column1
* @param $operator
* @param $column2
* @return Builder
*/
public static function where($column1, $operator, $column2)
{
return static::table()->where($column1, $operator, $column2);
}
/**
* @param string $column
* @param array $arrayData
* @return Builder
*/
public static function whereIn(string $column, array $arrayData)
{
return static::table()->whereIn($column, $arrayData);
}
/**
* Find all data by speicific column and value, also you can specify sorting option
* @param array|string $column
* @param string|null $value
* @param string $sorting_column
* @param string $sorting_dir
* @return Collection
*/
public static function findAllBy($column, $value = null, $sorting_column = "id", $sorting_dir = "desc") {
if(is_array($column)) {
$result = app('db')->table(static::getTable());
foreach($column as $key=>$value) {
$result->where($key, $value);
}
$result = $result->orderBy($sorting_column, $sorting_dir)->get();
} else {
$result = app('db')->table(static::getTable())->where($column, $value)->orderBy($sorting_column, $sorting_dir)->get();
}
return $result;
}
/**
* Count the all data
* @return integer
*/
public static function count() {
$total = app("LaravelModelTemporary")->get(static::class, "count", static::getTable());
if(!isset($total)) {
$total = app('db')->table(static::getTable())->count();
app("LaravelModelTemporary")->put(static::class, "count", static::getTable());
}
return $total;
}
/**
* Count the data by specific column and value
* @param array|string $column
* @param string|null $value
* @return integer
*/
public static function countBy($column, $value = null) {
if(is_array($column)) {
$result = app('db')->table(static::getTable());
foreach($column as $key=>$value) {
$result->where($key, $value);
}
$result = $result->count();
} else {
$result = app('db')->table(static::getTable())
->where($column, $value)
->count();
}
return $result;
}
/**
* Find all data with descending sorting
* @param $column
* @return Collection
*/
public static function findAllDesc($column = "id") {
return app('db')->table(static::getTable())->orderBy($column,"desc")->get();
}
/**
* Find all the data with ascending sorting
* @param string $column
* @return Collection
*/
public static function findAllAsc($column = "id") {
return app('db')->table(static::getTable())->orderBy($column,"asc")->get();
}
/**
* Find all the data without sorting by default
* @param callable|null $query Query Builder
* @return Collection
*/
public static function findAll(callable $query = null) {
if(is_callable($query)) {
$result = call_user_func($query, static::table());
$result = $result->get();
} else {
$result = static::table()->get();
}
return $result;
}
/**
* Get all latest data
* @return Collection
*/
public static function latest() {
return app('db')->table(static::getTable())->orderBy(static::getPrimaryKey(),"desc")->get();
}
/**
* Get all oldest data
* @return Collection
*/
public static function oldest() {
return app('db')->table(static::getTable())->orderBy(static::getPrimaryKey(),"asc")->get();
}
/**
* Convert model output to array output
* @return array
*/
public function toArray() {
$result = [];
foreach($this as $key=>$val) {
$result[$key] = $val;
}
return $result;
}
/**
* Find a data by primary key condition with Model output
* @param $id
* @return static
*/
public static function findById($id) {
$row = app("LaravelModelTemporary")->get(static::class, "findById", $id);
if(!$row) {
$row = app('db')->table(static::getTable())
->where(static::getPrimaryKey(),$id)
->first();
app("LaravelModelTemporary")->put(static::class, "findById", $id, $row);
}
return static::objectSetter($row);
}
/**
* Find a data by primary key condition with Model output
* @param $id
* @return static
*/
public static function find($id) {
return static::findById($id);
}
/**
* Find a data by specific column and value with Model output
* @param array|string $column
* @param string|null $value
* @return static
*/
public static function findBy($column, $value = null) {
if(is_array($column)) {
$row = app('db')->table(static::getTable())
->where($column)
->first();
} else {
$row = app('db')->table(static::getTable())
->where($column,$value)
->first();
}
return static::objectSetter($row);
}
/**
* Save many data
* @param Model[] $data
*/
public static function bulkInsert(array $data) {
$insertData = [];
foreach($data as $row) {
/** @var Model $row */
$dataArray = $row->toArray();
unset($dataArray[static::getPrimaryKey()]);
if(isset($dataArray['created_at']) && empty($dataArray['created_at'])) {
$dataArray['created_at'] = date('Y-m-d H:i:s');
}
$insertData[] = $dataArray;
}
app('db')->table(static::getTable())->insertOrIgnore($insertData);
}
public function save() {
$data = [];
foreach($this as $key=>$val) {
if(!in_array($key,[static::getPrimaryKey()])) {
if(isset($this->{$key})) {
$data[$key] = $val;
}
}
}
unset($data['table'], $data['connection'], $data['primary_key']);
if($this->{static::getPrimaryKey()}) {
if(isset($data['created_at'])) {
unset($data['created_at']);
}
app('db')->table(static::getTable())->where(static::getPrimaryKey(), $this->{static::getPrimaryKey()})->update($data);
$id = $this->{static::getPrimaryKey()};
} else {
if(property_exists($this,'created_at')) {
$data['created_at'] = date('Y-m-d H:i:s');
}
$id = app('db')->table(static::getTable())->insertGetId($data);
}
$this->{static::getPrimaryKey()} = $id;
return ($id)?true:false;
}
/**
* Delete the data by specific primary key condition
* @param $id
*/
public static function deleteById($id) {
app('db')->table(static::getTable())->where(static::getPrimaryKey(),$id)->delete();
}
/**
* Delete the data by specific column and value
* @param string|array $column
* @param null $value
*/
public static function deleteBy($column, $value = null) {
if(is_array($column)) {
$result = app('db')->table(static::getTable());
foreach($column as $key=>$value) {
$result->where($key, $value);
}
$result->delete();
} else {
if(!$value) {
throw new \InvalidArgumentException("Missing argument 2 value");
}
app('db')->table(static::getTable())->where($column,$value)->delete();
}
}
/**
* Delete all data from table
*/
public static function deleteAll()
{
app('db')->table(static::getTable())->delete();
}
/**
* Delete the data selected
*/
public function delete() {
app('db')->table(static::getTable())->where(static::getPrimaryKey(), $this->{static::getPrimaryKey()})->delete();
}
}<file_sep>/src/Core/LaravelModelTemporary.php
<?php
namespace Crocodic\LaravelModel\Core;
class LaravelModelTemporary
{
private $data;
public function put($repoClassName, $repoMethodName, $repoId, $data)
{
$this->data[$repoClassName][$repoMethodName][$repoId] = $data;
}
public function get($repoClassName, $repoMethodName, $repoId)
{
return @$this->data[$repoClassName][$repoMethodName][$repoId];
}
}<file_sep>/src/Core/Builder.php
<?php
namespace Crocodic\LaravelModel\Core;
/**
* Class Builder
* @package Crocodic\LaravelModel\Core
* @method Builder addSelectTable(string $table, string $prefix = null, array $exceptColumns = [])
* @method Builder withTable(string $table, string $selectPrefix = null, array $exceptColumns = [], string $first = null, string $operator = null, string $second = null)
* @method Builder like(string $column, string $keyword)
*/
abstract class Builder extends \Illuminate\Database\Query\Builder
{
}<file_sep>/src/Helpers/Helper.php
<?php
namespace Crocodic\LaravelModel\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class Helper
{
public static function getFields(string $table)
{
$modelName = "\App\Models\\".Str::studly($table)."Model";
$modelClass = new $modelName();
return array_keys(get_object_vars($modelClass));
}
public static function findPrimaryKey($table, $connection = null)
{
$connection = $connection?:config("database.default");
$pk = DB::connection($connection)->getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
if(!$pk) {
return null;
}
return $pk->getColumns()[0];
}
public static function appPath($path)
{
if(!function_exists("app_path")) {
return app()->path() . ($path ? DIRECTORY_SEPARATOR . $path : $path);
} else {
return app_path($path);
}
}
} | 4fa4874d666de2634ca9d4cc9dabbdcbead415b5 | [
"PHP"
] | 8 | PHP | crocodic-studio/laravel-model | 351322842f924228848d5ede101b5494791836d6 | 2a98f70ce5d5068c5add4fc79d48c2ecb8409bb8 |
refs/heads/master | <file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${JSON_SOURCED:-}" = "true" ]] && return 0
## constants ####################################
JSON_SOURCED=true
## properties ###################################
## functions ####################################
function keys {
# writes comma delimited list to stdout
local p=${1:-}
local sep=${2:-,}
[[ "$p" = "-" ]] && p=`cat` ||:
printf "$p" | jq -er 'keys | map(.[:2]) | join(",")'
}
<file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${OBFUSCATE_SOURCED:-}" = "true" ]] && return 0
## constants ####################################
OBFUSCATE_SOURCED=true
SALT=A5d
## functions ####################################
function sig {
# obfuscates a given value by md5 encode
v="${1:-}${SALT}"
printf "$v" | md5sum | cut -d' ' -f1
}
export -f sig
function enc {
# uses gpg to encrypt a given value
printf ""
}
<file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${LOG_SOURCED:-}" = "true" ]] && return 0
shopt -s expand_aliases
{ >&3 ;} 2>/dev/null || exec 3>/dev/null
{ >&4 ;} 2>/dev/null || exec 4>/dev/null
## constants ####################################
LOG_SOURCED=true
JOURNALD_SOCK=/run/systemd/journal/socket
## properties ###################################
journald=false
## functions ####################################
function log_open {
# allocate resources required for logging operations
local journald=${journald:-}
local mask=`severity ${PRIORITY:-info}`
alias mock=":"
if echo "${SYSLOG:-}" | grep -iE "^true$" &>/dev/null; then
# if syslog has been explicity requested, check if we are
# using journald by determing of journald socket is available
if [[ -S $JOURNALD_SOCK ]]; then
journald=true
fi
else
# disable syslog function if not explicity required
alias syslog="read; :"
fi
for level in debug info warning error; do
# iterate though levels and disable those that
# fall below current mask
if [[ `severity $level` -gt "$mask" ]]; then
alias $level=mock
fi
done
}
export -f log_open
function log_close {
# deallocate log resources
exec 3>&-
exec 4>&-
}
export -f log_close
function severity {
local name=${1}
local value=-1
{
if echo $name | grep -i debug ; then
value=7
elif echo $name | grep -i info ; then
value=6
elif echo $name | grep -i warn ; then
value=4
elif echo $name | grep -i err ; then
value=3
fi
} &>/dev/null
echo $value
}
export -f severity
function debug { logs "debug" "$@" ;}
function info { logs "info" "$@" ;}
function warning { logs "warning" "$@" ;}
function error { logs "error" "$@" ;}
function logs {
local level=${1}
local message=${2}
local sevnum=`severity $level`
local trace=`caller 1 | sed -E 's/^.+?\s([_a-z0-9]+)\s([-/.a-z0-9]+)$/\2#\1/I'`
local payload
if [[ "${2:-}" = "-" ]]; then
message="`cat -`"
elif [[ "${3:-}" = "-" ]]; then
payload=( "`cat -`" )
if [[ -n "${payload:-}" ]]; then
set -- $level "$message" "${payload[@]:-}"
else return 0
fi
fi
printf '%s\n' \
"timestamp=`date +%s%N | cut -b1-13`" \
"level=$level" \
"priority=$sevnum" \
"message=$message" \
"message_id=`uuidgen`" \
"trace=$trace" \
"_pid=$$" \
"${@:3}" \
| jq -crs --raw-input '
split("\n")[:-1] | map(
split("=")
| {(.[0]): .[1]}
| with_entries( .key |= ascii_upcase )
)
| add
' \
| tee /dev/fd/3 \
| syslog $level
}
export -f debug info warning error logs
function syslog {
# forward logs to the available system log daemon; if
# journald is available, it will takes precedence over
# rsyslog/syslog
local level=${1}
local journald=${journald:-}
local payload
# read payload from stdin; this will be a json payload and
# will block if not available
read payload
if echo "$journald" | grep -iE "^true$" &>/dev/null; then
# if journald flag has been set as true, we write to journald
# udp socket
printf "$payload" | jq -re '
to_entries[] | "\( .key )=\( .value )
' | nc -Uu -w1 $JOURNALD_SOCK
else
# otherwise, write json payload to linux logger, which will
# take care of details of interacting with syslogd
printf "$payload" | logger -p $level
fi
}
export -f syslog
## main #########################################
log_open && alias log_open=":"
<file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${ARG_SOURCED:-}" = "true" ]] && return 0
## constants ####################################
ARG_SOURCED=true
## properties ###################################
## functions ####################################
function arg {
# Enforces rules around assignment when working
# with positional arguments
# `arg unsigned`
printf "${@:-\0}" \
| sed -E '/^-/!q1;s/-//' && cat \
||:
}
<file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${ISTRUE_SOURCED:-}" = "true" ]] && return 0
## constants ####################################
ISTRUE_SOURCED=true
## properties ###################################
## functions ####################################
function istrue {
# Canonical evaluation of boolean true
value={$1}
printf '%s' $value | grep -Ei '^true$' &>/dev/null
}
<file_sep>#!/bin/bash
set -euo pipefail
! set -o errtrace 2>/dev/null
[[ "${VALIDATE_SOURCED:-}" = "true" ]] && return 0
## constants ####################################
VALIDATE_SOURCED=true
## properties ###################################
## functions ####################################
function validate {
# runs validation checks against a set of
# givn arguments for a specific use type
type=${1}
args=${@:2}
flag="-z"
[[ "$type" = "file" ]] && flag="! -e"
for a in $args; do
if test $flag "${!a:-}"; then
error "Failed validation" "name=$a" "type=$type"
exit 3
fi
done
}
| bd10f1180656457b2bb624d09fa40850d7e222e9 | [
"Shell"
] | 6 | Shell | callowaylc/sh | d0589e4f681fd2a3c07f7cd5eb1acd1be97a5184 | b473f469c5f908f445fd09dfaa42e5a7f26914b1 |
refs/heads/master | <repo_name>rsarkar-github/Quantum-Computing-Projects<file_sep>/QISKIT/example_simulator.py
# Import the QISKit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# Add a Measure gate to see the state.
qc.measure(q, c)
# See a list of available local simulators
print("Local backends: ", available_backends({'local': True}))
# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, "local_qasm_simulator")
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))
<file_sep>/QISKIT/Qconfig_20_qubit.py
APItoken = '<KEY>' \
'<KEY>'
config = {
'url': 'https://q-console-api.mybluemix.net/api',
'hub': 'ibmq',
'group': 'qc-ware',
'project': 'default'
}
<file_sep>/QISKIT/example_chip.py
# Import the QISKit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, register
import Qconfig
# Set your API Token.
# You can get it from https://quantumexperience.ng.bluemix.net/qx/account,
# looking for "Personal Access Token" section.
QX_TOKEN = Qconfig.APItoken
QX_URL = Qconfig.config["url"]
# Authenticate with the IBM Q API in order to use online devices.
# You need the API Token and the QX URL.
register(QX_TOKEN, QX_URL)
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# Add a Measure gate to see the state.
qc.measure(q, c)
# Compile and run the Quantum Program on a real device backend
job_exp = execute(qc, 'ibmqx5', shots=1024, max_credits=10)
result = job_exp.result()
# Show the results
print(result)
print(result.get_data())
<file_sep>/QISKIT/TDA/tda1.py
# The simplicial complex is as follows:
# Vertices: 0, 1, 2
# Simplicial complex: {{0}, {1}, {2}, {0, 1}}
# Import the QISKit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, register
import Qconfig
# Set your API Token
QX_TOKEN = Qconfig.APItoken
QX_URL = Qconfig.config["url"]
# Authenticate with the IBM Q API in order to use online devices.
register(QX_TOKEN, QX_URL)
# Create a Quantum Circuit with 5 qubits
q = QuantumRegister(5)
c = ClassicalRegister(5)
qc = QuantumCircuit(q, c)
# Build the circuit
qc.x(q[2])
qc.x(q[1])
qc.cx(q[1], q[3])
qc.measure(q[3], c[3])
qc.cx(q[2], q[4])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
qc.measure(q[4], c[4])
# Compile and run the Quantum circuit
shots = 1024
backend_options = ["local_qasm_simulator", "ibmqx4", "ibmqx5"]
use_backend = backend_options[1]
job_sim = execute(qc, use_backend, shots=shots)
sim_result = job_sim.result()
# Analyze the results
print("simulation: ", sim_result)
counts = sim_result.get_counts(qc)
keys = counts.keys()
cnt = 0
for item in keys:
if item[0] == "0":
cnt += counts[item]
prob = cnt / shots
print("Probability of getting eigenvalue 0 = ", prob)
# Calculation of Betti numbers
<file_sep>/QISKIT/TDA/Qconfig.py
APItoken = '53f9c56e933dd83664f28ff7ed4dce37d86e5a1269f03b6d70644ae0d' \
'9433bdf9076a26370fe32ee9188cd1e78fc69a2a063bb7d575c3641838d83de28069dd3'
config = {
'url': 'https://quantumexperience.ng.bluemix.net/api',
'hub': None,
'group': None,
'project': None
}
<file_sep>/README.md
# Quantum-Computing-Projects
Single repository for quantum computing projects of various kinds
<file_sep>/QISKIT/TDA/tda1_20_qubit.py
# The simplicial complex is as follows:
# Vertices: 0, 1, 2
# Simplicial complex: {{0}, {1}, {2}, {0, 1}}
# Import the QISKit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, register
import Qconfig_20_qubit as Qconfig
# Set your API Token.
QX_TOKEN = Qconfig.APItoken
QX_URL = Qconfig.config["url"]
QX_HUB = Qconfig.config["hub"]
QX_GROUP = Qconfig.config["group"]
QX_PROJECT = Qconfig.config["project"]
# Authenticate with the IBM Q API in order to use online devices.
register(QX_TOKEN, QX_URL, hub=QX_HUB, group=QX_GROUP, project=QX_PROJECT)
# Create a Quantum Circuit with 5 qubits
q = QuantumRegister(5)
c = ClassicalRegister(5)
qc = QuantumCircuit(q, c)
# Build the circuit
qc.x(q[2])
qc.x(q[1])
qc.cx(q[1], q[0])
qc.measure(q[3], c[3])
# qc.cx(q[2], q[4])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
qc.measure(q[4], c[4])
# Compile and run the Quantum circuit
shots = 1024
backend_options = ["local_qasm_simulator", "ibmq_20_tokyo"]
use_backend = backend_options[1]
job_sim = execute(qc, use_backend, shots=shots)
sim_result = job_sim.result()
# Analyze the results
counts = sim_result.get_counts(qc)
print("simulation: ", sim_result)
print("counts: ", counts)
keys = counts.keys()
cnt = 0
for item in keys:
if item[0] == "0":
cnt += counts[item]
prob = cnt / shots
print("Probability of getting eigenvalue 0 = ", prob)
# Calculation of Betti numbers
| 033613b5d92e54a93dfada974efcaf7d3649d062 | [
"Markdown",
"Python"
] | 7 | Python | rsarkar-github/Quantum-Computing-Projects | 966c0465f98dca0091f09826e12eb57277faf3c0 | 9552b16cde8e8581c6d148c582387e0d1b1e6017 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace app_ex
{
public partial class MainPage : ContentPage
{
string errorMessage = null;
public MainPage()
{
InitializeComponent();
}
void limpiar()
{
txtusuario.Text = string.Empty;
txtclave.Text = string.Empty;
}
private async void bntIngreso_Clicked(object sender, EventArgs e)
{
string usuario = txtusuario.Text;
string clave = txtclave.Text;
if (txtusuario.Text == "estudiante2020" && txtclave.Text == "<PASSWORD>")
{
await DisplayAlert("Acceso Correcto", errorMessage, "OK");
}
else
{
await DisplayAlert("Usuario o Contraseña Incorrecta", errorMessage, "OK");
await Navigation.PushAsync(new MainPage());
limpiar();
}
}
}
}
| 84fd37eb2715696f6c6290918096f11b0d378538 | [
"C#"
] | 1 | C# | RicardoTipan/app-ex | c5597965eac06c400edf1bb38783c49ad6dbea19 | bf88a9035f565980eb9496a97683996de289dee7 |
refs/heads/master | <file_sep>from __future__ import annotations
import copy
import math
import itertools
from typing import Tuple, Generator, List
def read_moons() -> Generator[List[int], None, None]:
with open("input.txt") as file:
for line in file.readlines():
_, x, _, y, _, z = line.replace("=", " ").replace(",", " ").replace(">", " ").split()
yield list(map(int, (x, y, z)))
class Moon:
def __init__(self, coordinates: List[int], name) -> None:
self.coordinates: list = coordinates
self.velocity: list = [0, 0, 0]
self.name: str = name
def update_gravity(self, other: Moon) -> None:
for index, (coord, coord_other) in enumerate(zip(self.coordinates, other.coordinates)):
if coord == coord_other:
val: int = 0
elif coord < coord_other:
val: int = 1
else:
val: int = -1
self.velocity[index] += val
def move(self) -> None:
for index, vel in enumerate(self.velocity):
self.coordinates[index] += vel
@property
def potential_energy(self) -> int:
energy: int = sum(map(abs, self.coordinates))
return energy
@property
def kinetic_energy(self) -> int:
energy: int = sum(map(abs, self.velocity))
return energy
@property
def total_energy(self) -> int:
total_energy: int = self.potential_energy * self.kinetic_energy
return total_energy
def identical_coord_and_velocity(self, other: Moon, index: int):
res: bool = True if self.coordinates[index] == other.coordinates[index] \
and self.velocity[index] == other.velocity[index] else False
return res
def lowest_common_multiple(a: int, b: int) -> int:
lcm: int = a * b // math.gcd(a, b)
return lcm
def simulate_moons(initial_coordinates: Generator[List[int], None, None], steps: int):
moon_names: Tuple[str, ...] = "Io", "Europa", "Ganymede", "Callisto"
moons: List[Moon] = list(Moon(coordinates, name) for coordinates, name in zip(initial_coordinates, moon_names))
initial_moons = copy.deepcopy(moons)
interactions = list(itertools.permutations(moons, 2))
x_index, y_index, z_index = 0, 0, 0
for total_index in itertools.count():
if total_index == steps - 1:
total_energy: int = sum(m.total_energy for m in moons)
if all((moon.identical_coord_and_velocity(initial_moon, 0) for moon, initial_moon in zip(moons, initial_moons))):
if not x_index:
x_index = total_index
if all((moon.identical_coord_and_velocity(initial_moon, 1) for moon, initial_moon in zip(moons, initial_moons))):
if not x_index:
y_index = total_index
if all((moon.identical_coord_and_velocity(initial_moon, 2) for moon, initial_moon in zip(moons, initial_moons))):
if not x_index:
z_index = total_index
if x_index and y_index and z_index:
step_index_identical = lowest_common_multiple(x_index, lowest_common_multiple(y_index, z_index))
break
for inter in interactions:
inter[0].update_gravity(inter[1])
for m in moons:
m.move()
return total_energy, step_index_identical
if __name__ == "__main__":
part_1, part_2 = simulate_moons(read_moons(), steps=1000)
print("PART1:", part_1)
print("PART2:", part_2)
<file_sep>from collections import Counter
from typing import Callable, Generator
def get_adjacent_digits_identical(num: str) -> list:
adjacent_digit: list = [num[index + 1] for index in range(5) if num[index] == num[index + 1]]
return adjacent_digit
def are_digits_increasing(num: str) -> bool:
status: bool = all(num[index - 1] <= num[index] for index, _ in enumerate(num) if index > 0)
return status
def part_2_condition(num: str):
adjacents: list = get_adjacent_digits_identical(num)
quantity: Counter = Counter(num)
status: bool = True if any(quantity[adj] == 2 for adj in adjacents) else False
return status
def assert_conditions_and_get_quantity(start: int, stop: int, cond_1: Callable, cond_2: Callable) -> int:
passwords: Generator = (num for num in range(start, stop + 1) if cond_1(str(num)) and cond_2(str(num)))
quantity: int = len(list(passwords))
return quantity
if __name__ == "__main__":
start: int = 248345
stop: int = 746315
part_1 = assert_conditions_and_get_quantity(start, stop, get_adjacent_digits_identical, are_digits_increasing)
print(f"PART 1: {part_1}")
part_2 = assert_conditions_and_get_quantity(start, stop, part_2_condition, are_digits_increasing)
print(f"PART 2: {part_2}")
<file_sep>import collections
import itertools
from typing import List, Optional, Coroutine
def get_program() -> dict:
with open("input.txt") as file:
program: dict = {index: int(num) for index, num in enumerate(file.read().split(","))}
return program
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
return score
def intcode_computer(program: dict, initial_input_value: int) -> List[int]:
mapping_rel: dict = {
1: 3,
2: 3,
3: 1,
4: 1,
7: 3,
8: 3,
9: 1
}
index, relative_base = 0, 0
opcode, color_num, dir_num = None, None, None
while opcode != 99:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
param_read_write_index: Optional[int] = mapping_rel.get(opcode)
parameters: dict = {}
for instruction_index, digit_index in enumerate(range(-3, -6, -1)):
mode_par: int = int(instruction_value[digit_index]) if len(instruction_value) >= abs(digit_index) else 0
rel_index: int = instruction_index + 1
if mode_par == 0:
parameters[rel_index] = program.get(program.get(index + rel_index, 0), 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: program.get(index + x, 0)
elif mode_par == 1:
parameters[rel_index] = program.get(index + rel_index, 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: index + x
elif mode_par == 2:
parameters[rel_index] = program.get(program.get(index + rel_index, 0) + relative_base, 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: program.get(index + x, 0) + relative_base
if opcode in [1, 2]:
write_value: int = get_score(opcode, parameters[1], parameters[2])
write_address: int = write_read_index(3)
program[write_address] = write_value
index += 4
elif opcode == 3:
if initial_input_value is not None:
write_value: int = initial_input_value
initial_input_value = None
else:
write_value: int = yield color_num, dir_num
color_num = None
dir_num = None
write_address: int = write_read_index(1)
index += 2
program[write_address] = write_value
elif opcode == 4:
output_value: int = program.get(write_read_index(1), 0)
index += 2
if color_num is None:
color_num = output_value
elif dir_num is None:
dir_num = output_value
elif opcode == 5:
index = parameters[2] if parameters[1] != 0 else index + 3
elif opcode == 6:
index = parameters[2] if parameters[1] == 0 else index + 3
elif opcode == 7:
val: int = 1 if parameters[1] < parameters[2] else 0
program[write_read_index(3)] = val
index += 4
elif opcode == 8:
val: int = 1 if parameters[1] == parameters[2] else 0
program[write_read_index(3)] = val
index += 4
elif opcode == 9:
relative_base += program.get(write_read_index(1), 0)
index += 2
return
def get_painted_fields(program: dict, initial_input_value: int) -> dict:
painted_fields: dict = {}
intcode_coro: Coroutine = intcode_computer(program, initial_input_value)
color_standing = None
current_coords = 0, 0
dirs = collections.deque(((0, 1), (-1, 0), (0, -1), (1, 0)))
while True:
try:
color_painted, rotation = intcode_coro.send(color_standing)
painted_fields[current_coords] = color_painted
rotate_val: int = 1 if rotation == 1 else -1
dirs.rotate(rotate_val)
current_coords = tuple(map(sum, zip(current_coords, dirs[0])))
color_standing: int = 1 if painted_fields.get(current_coords) == 1 else 0
except StopIteration:
break
return painted_fields
def draw_message(painted_fields: dict) -> None:
(min_x, min_y), (max_x, max_y) = (map(func, zip(*painted_fields.keys())) for func in (min, max))
for y, x in itertools.product(range(max_y, min_y - 1, -1), range(min_x, max_x)):
sign: str = "#" if painted_fields.get((x, y)) == 1 else "."
end_line: str = "\n" if x == max_x - 1 else ""
print(sign, end=end_line)
if __name__ == "__main__":
painted_starting_black: dict = get_painted_fields(get_program(), initial_input_value=0)
print("PART1:", len(painted_starting_black))
painted_starting_white: dict = get_painted_fields(get_program(), initial_input_value=1)
draw_message(painted_starting_white)
<file_sep>from typing import List, Generator, Optional
def get_program() -> dict:
with open("input.txt") as file:
program: dict = {index: int(num) for index, num in enumerate(file.read().split(","))}
return program
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
return score
def intcode_computer(program: dict, input_value: int) -> List[int]:
mapping_rel: dict = {
1: 3,
2: 3,
3: 1,
4: 1,
7: 3,
8: 3,
9: 1
}
index: int = 0
relative_base: int = 0
opcode = None
while opcode != 99:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
param_read_write_index: Optional[int] = mapping_rel.get(opcode)
parameters: dict = {}
for instruction_index, digit_index in enumerate(range(-3, -6, -1)):
mode_par: int = int(instruction_value[digit_index]) if len(instruction_value) >= abs(digit_index) else 0
rel_index: int = instruction_index + 1
if mode_par == 0:
parameters[rel_index] = program.get(program.get(index + rel_index, 0), 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: program.get(index + x, 0)
elif mode_par == 1:
parameters[rel_index] = program.get(index + rel_index, 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: index + x
elif mode_par == 2:
parameters[rel_index] = program.get(program.get(index + rel_index, 0) + relative_base, 0)
if rel_index == param_read_write_index:
write_read_index = lambda x: program.get(index + x, 0) + relative_base
if opcode in [1, 2]:
write_value: int = get_score(opcode, parameters[1], parameters[2])
write_address: int = write_read_index(3)
program[write_address] = write_value
index += 4
elif opcode == 3:
write_value: int = input_value
write_address: int = write_read_index(1)
index += 2
program[write_address] = write_value
elif opcode == 4:
output_value: int = program.get(write_read_index(1), 0)
index += 2
yield output_value
elif opcode == 5:
index = parameters[2] if parameters[1] != 0 else index + 3
elif opcode == 6:
index = parameters[2] if parameters[1] == 0 else index + 3
elif opcode == 7:
val: int = 1 if parameters[1] < parameters[2] else 0
program[write_read_index(3)] = val
index += 4
elif opcode == 8:
val: int = 1 if parameters[1] == parameters[2] else 0
program[write_read_index(3)] = val
index += 4
elif opcode == 9:
relative_base += program.get(write_read_index(1), 0)
index += 2
return
def get_diagnostic_code(program: dict, input_value: int) -> List[int]:
generated_codes_gen: Generator = intcode_computer(program, input_value)
output_codes: List[int] = []
for code in generated_codes_gen:
try:
output_codes.append(code)
except StopIteration:
break
return output_codes
if __name__ == "__main__":
part_1: List[int] = get_diagnostic_code(get_program(), input_value=1)
print("PART1:", part_1)
part_2: List[int] = get_diagnostic_code(get_program(), input_value=2)
print("PART2:", part_2)
<file_sep>import itertools
from typing import List, Generator
def get_program() -> List[int]:
with open("input.txt") as file:
program: List[int] = [int(num) for num in file.read().split(",")]
return program
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
return score
def get_diagnostic_code_part_1(program: List[int], phase_combination, initial_input) -> int:
func = process_program_part_1
input_value: int = initial_input
for phase in phase_combination:
generated_codes: Generator = func(program, input_value, phase)
for code in generated_codes:
try:
assert code == 0
except AssertionError:
diagnostic_code: int = code
break
next_code = next(generated_codes)
if next_code == 'opcode_99':
input_value = diagnostic_code
else:
raise ValueError(f"Diagnostic_code={diagnostic_code}, next_code={next_code}")
return diagnostic_code
def get_max_signal(initial_input: int):
signals: list = []
for comb in itertools.permutations('01234'):
phase_combination: list = list(map(int, list(comb)))
signals.append(get_diagnostic_code_part_1(get_program(), phase_combination, initial_input))
max_signal: int = max(signals)
return max_signal
def process_program_part_1(program: List[int], input_value: int, phase: int) -> List[int]:
index: int = 0
input_intruction_index = 0
while True:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
if opcode == 99:
yield 'opcode_99'
mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index])
if len(instruction_value) >= abs(digit_index) else 0
for digit_index in range(-3, -6, -1))
assert all(par in (0, 1) for par in (mode_par_1, mode_par_2, mode_par_3)), \
f"{mode_par_1}, {mode_par_2}, {mode_par_3}"
if opcode not in [3, 4]:
input_1, input_2 = (program[index + instruction_index + 1] if par == 1
else program[program[index + instruction_index + 1]]
for instruction_index, par in enumerate((mode_par_1, mode_par_2)))
if opcode in [1, 2, 3]:
if opcode in [1, 2]:
write_value: int = get_score(opcode, input_1, input_2)
write_address: int = program[index + 3]
index += 4
else:
input_intruction_index += 1
if input_intruction_index == 1:
write_value: int = phase
elif input_intruction_index == 2:
write_value: int = input_value
else:
raise ValueError("Opcode 3 possible only in two instructions")
write_address: int = program[index + 1]
index += 2
program[write_address] = write_value
elif opcode == 4:
yield_value: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]]
yield yield_value
index += 2
elif opcode == 5:
if input_1 != 0:
index = input_2
else:
index += 3
elif opcode == 6:
if input_1 == 0:
index = input_2
else:
index += 3
elif opcode in (7, 8):
third_param = program[index + 3]
if opcode == 7 and input_1 < input_2:
val: int = 1
elif opcode == 8 and input_1 == input_2:
val: int = 1
else:
val: int = 0
program[third_param] = val
index += 4
else:
raise ValueError(f"Opcode={opcode} is not in (1, 2, 3, 4, 5, 6, 7, 8 99)")
if __name__ == "__main__":
samples_1 = (
([3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0], [4, 3, 2, 1, 0]),
([3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23, 101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0],
[0, 1, 2, 3, 4]),
([3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33, 1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31,
31, 4, 31, 99, 0, 0, 0], [1, 0, 4, 3, 2])
)
for index, (sample_program, phase_comp) in enumerate(samples_1):
sample_result: int = get_diagnostic_code_part_1(sample_program, phase_comp, initial_input=0)
print(f"PART 1 SAMPLE {index + 1}:", sample_result)
part_1_result: int = get_max_signal(initial_input=0)
print("PART1:", part_1_result)
<file_sep>from typing import List, Generator
def get_program() -> List[int]:
with open("input.txt") as file:
program: List[int] = [int(num) for num in file.read().split(",")]
return program
def process_program_part_1(program: List[int], input_value: int) -> List[int]:
index: int = 0
while True:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
if opcode == 99:
yield 'opcode_99'
mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index])
if len(instruction_value) >= abs(digit_index) else 0
for digit_index in range(-3, -6, -1))
assert all(par in (0, 1) for par in (mode_par_1, mode_par_2, mode_par_3)), \
f"{mode_par_1}, {mode_par_2}, {mode_par_3}"
if opcode in [1, 2, 3]:
if opcode in [1, 2]:
input_1, input_2 = (program[index + instruction_index + 1] if par == 1
else program[program[index + instruction_index + 1]]
for instruction_index, par in enumerate((mode_par_1, mode_par_2)))
write_value: int = get_score(opcode, input_1, input_2)
write_address: int = program[index + 3]
index += 4
else:
write_value: int = input_value
write_address: int = program[index + 1]
index += 2
program[write_address] = write_value
elif opcode == 4:
yield_value: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]]
yield yield_value
index += 2
else:
raise ValueError(f"Opcode={opcode} is not in (1, 2, 3, 4, 99)")
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
return score
def get_diagnostic_code(program: List[int], input_value: int, part: int) -> int:
func = process_program_part_1 if part == 1 else process_program_part_2
generated_codes: Generator = func(program, input_value)
for code in generated_codes:
try:
assert code == 0
except AssertionError:
diagnostic_code: int = code
break
next_code = next(generated_codes)
if next_code == 'opcode_99':
return diagnostic_code
else:
raise ValueError(f"Diagnostic_code={diagnostic_code}, next_code={next_code}")
def process_program_part_2(program: List[int], input_value: int) -> List[int]:
index: int = 0
while True:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
if opcode == 99:
yield 'opcode_99'
mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index])
if len(instruction_value) >= abs(digit_index) else 0
for digit_index in range(-3, -6, -1))
assert all(par in (0, 1) for par in (mode_par_1, mode_par_2, mode_par_3)), \
f"{mode_par_1}, {mode_par_2}, {mode_par_3}"
input_1, input_2 = (program[index + instruction_index + 1] if par == 1
else program[program[index + instruction_index + 1]]
for instruction_index, par in enumerate((mode_par_1, mode_par_2)))
if opcode in [1, 2, 3]:
if opcode in [1, 2]:
write_value: int = get_score(opcode, input_1, input_2)
write_address: int = program[index + 3]
index += 4
else:
write_value: int = input_value
write_address: int = program[index + 1]
index += 2
program[write_address] = write_value
elif opcode == 4:
yield_value: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]]
yield yield_value
index += 2
elif opcode == 5:
if input_1 != 0:
index = input_2
else:
index += 3
elif opcode == 6:
if input_1 == 0:
index = input_2
else:
index += 3
elif opcode in (7, 8):
third_param = program[index + 3]
if opcode == 7 and input_1 < input_2:
val: int = 1
elif opcode == 8 and input_1 == input_2:
val: int = 1
else:
val: int = 0
program[third_param] = val
index += 4
else:
raise ValueError(f"Opcode={opcode} is not in (1, 2, 3, 4, 5, 6, 7, 8 99)")
if __name__ == "__main__":
part_1_result: int = get_diagnostic_code(get_program(), input_value=1, part=1)
print("PART1:", part_1_result)
part_2_result: int = get_diagnostic_code(get_program(), input_value=5, part=2)
print("PART2:", part_2_result)
<file_sep>from collections import defaultdict
from typing import Generator
def read_file(name: str) -> Generator[str, None, None]:
with open(name) as file:
yield from file.readlines()
def get_center_and_border(orbits_exp: Generator) -> dict:
center_borders: defaultdict = defaultdict(list)
for orb in orbits_exp:
splitted: list = orb.strip().split(")")
center_borders[splitted[0]].append(splitted[1])
return center_borders
def produce_orbits_part1(orbits: dict, start: str) -> dict:
level: dict = defaultdict(list)
level[0].append(start)
index: int = 0
while not all(val == [] for val in orbits.values()):
for level_center in level[index]:
for level_border in (border for center, border in orbits.items() if center == level_center):
for lvl in level_border:
level[index + 1].append(lvl)
if orbits[level_center]:
del orbits[level_center]
index += 1
return level
def count_orbits(file_name: str) -> int:
data: dict = get_center_and_border(read_file(file_name))
mapped_orbits: dict = produce_orbits_part1(data, start="COM")
number_indirect: int = 0
for index, centers in mapped_orbits.items():
number_indirect += index * len(centers)
return number_indirect
def get_border_and_center(orbits_exp: Generator) -> dict:
center_borders: dict = {}
for orb in orbits_exp:
splitted: list = orb.strip().split(")")
center_borders[splitted[1]] = splitted[0]
return center_borders
def produce_orbits_part2(orbits: dict, start: str) -> list:
parents: list = []
current_border: str = start
while True:
try:
current_center = orbits[current_border]
except KeyError:
break
parents.append(current_center)
current_border = current_center
return parents
def get_path_len(file_name: str) -> int:
data: dict = get_border_and_center(read_file(file_name))
parents_you: list = produce_orbits_part2(data, start="YOU")
parents_san: list = produce_orbits_part2(data, start="SAN")
for center in parents_you:
if center in parents_san:
change_orbit: int = center
break
else:
raise ValueError(f"Common orbit not found for: {parents_san}, {parents_you}")
path_len = sum(parents.index(change_orbit) for parents in (parents_you, parents_san))
return path_len
if __name__ == "__main__":
sample_result_part1: int = count_orbits("sample_input.txt")
print("SAMPLE RESULT PART 1:", sample_result_part1)
part_1_result: int = count_orbits("input.txt")
print("PART1:", part_1_result)
sample_result_part2: int = get_path_len("sample_input_2.txt")
print("SAMPLE RESULT PART 2:", sample_result_part2)
part_2_result: int = get_path_len("input.txt")
print("PART2:", part_2_result)
<file_sep>import collections
import itertools
def read_map(file_name: str) -> dict:
space_map: dict = {}
with open(file_name) as file:
for y, line in enumerate(file.readlines()):
for x, sign in enumerate(line):
space_map[(x, y)] = sign
return space_map
def find_best_asteroid(space_map: dict):
final_coords = None
final_value = 0
for (x, y), obj in space_map.items():
if obj == "#":
coeffs: dict = get_coeffs(space_map, x, y)
quantity = sum(len(val) for val in coeffs.values())
if quantity > final_value:
final_value = quantity
final_coords = x, y
return final_coords, final_value
def get_coeffs(space_map: dict, base_x: int, base_y: int):
categories: tuple = "above_right", "above_left", "below", "horizontal", "vertical_up"
coeffs: dict = {cat: collections.defaultdict(list) for cat in categories}
for (x, y), obj in space_map.items():
if obj == "#":
x_offset: int = x - base_x
y_offset: int = y - base_y
if y_offset == 0:
pos = "horizontal"
if x_offset > 0:
div: float = 1
elif x_offset < 0:
div: float = -1
else:
continue
else:
div: float = x_offset / y_offset
if y > base_y:
pos: str = "below"
elif x_offset > 0:
pos: str = "above_right"
elif x_offset < 0:
pos: str = "above_left"
else:
pos: str = "vertical_up"
coeffs[pos][div].append((x, y))
return coeffs
def distance_between_points(base_x: int, base_y: int, x: int, y: int) -> float:
distance: float = ((x - base_x) ** 2 + (-y + base_y) ** 2) ** (1 / 2)
return distance
def get_200th_destroyed_asteroid(space_map: dict, base_x: int, base_y: int) -> tuple:
raw_coeffs = get_coeffs(space_map, base_x, base_y)
sorted_coeffs = {cat: collections.OrderedDict(sorted(raw_coeffs[cat].items(), key=lambda t: -t[0]))
for cat in ("above_right", "below", "above_left")}
order = raw_coeffs["vertical_up"],\
sorted_coeffs["above_right"],\
{1: raw_coeffs["horizontal"][1]}, \
sorted_coeffs["below"],\
{1: raw_coeffs["horizontal"][-1]},\
sorted_coeffs["above_left"]
index: int = 1
for part in itertools.cycle(itertools.chain(order)):
if index == 200:
break
for coeff, coords in part.items():
if coords:
points_distance: list = [distance_between_points(base_x, base_y, x, y) for x, y in coords]
nearest_asteroid_index: int = points_distance.index(min(points_distance))
if index == 200:
asteroid_200_coords: tuple = coords[nearest_asteroid_index]
break
coords.pop(nearest_asteroid_index)
index += 1
return asteroid_200_coords
if __name__ == "__main__":
sp_map: dict = read_map("input.txt")
part_1_coords, part_1_value = find_best_asteroid(sp_map)
print("PART1:", part_1_value)
part_2_coords: tuple = get_200th_destroyed_asteroid(sp_map, *part_1_coords)
part_2_res: int = part_2_coords[0] * 100 + part_2_coords[1]
print("PART2:", part_2_res)
<file_sep>from typing import List, Generator
def get_wires_moves() -> List[Generator[str, None, None]]:
wires_moves: list = []
with open("input.txt") as file:
for line in file.readlines():
single_wire_move: Generator = (move for move in line.split(","))
wires_moves.append(single_wire_move)
return wires_moves
def convert_letter_to_direction(wire_moves: List[Generator]) -> Generator[range, None, None]:
for move in wire_moves:
x: int = 0
y: int = 0
direction: str = move[0]
value: int = int(move[1:])
step: int = 1 if direction in ("R", "U") else -1
coords_single_move: tuple = (step, 0) if direction in ("R", "L") else (0, step)
line_move_values: Generator = (coords_single_move for _ in range(1, value + 1))
yield from line_move_values
def produce_wires_points(wires_paths: list):
wires_points: List[set, set] = [set(), set()]
for wire_index, wire in enumerate(wires_paths):
x = y = 0
for step_index, (step_x, step_y) in enumerate(convert_letter_to_direction(wire)):
x += step_x
y += step_y
wires_points[wire_index].add((step_index + 1, x, y))
return wires_points
def get_intersection(wires_points: List[set]) -> set:
first_wire_without_index, second_wire_without_index = (set(point[1:] for point in wire) for wire in wires_points)
intersection_points: set = first_wire_without_index.intersection(second_wire_without_index)
return intersection_points
def count_min_manhattan_distance(wires_points: List[set]) -> int:
intersection_points: set = get_intersection(wires_points)
distances: list = [sum(abs(coord) for coord in coordinates) for coordinates in intersection_points]
min_manhattan_distance: int = min(distances)
return min_manhattan_distance
def get_closest_distance(wires_paths: list) -> int:
wires_points: List[set] = produce_wires_points(wires_paths)
min_dist_int = count_min_manhattan_distance(wires_points)
return min_dist_int
def find_fewest_steps(wires_paths) -> int:
wires_points: List[set] = produce_wires_points(wires_paths)
intersection_points: set = get_intersection(wires_points)
first_wire, second_wire = [list(points) for points in wires_points]
wires_without_indexes = [list(point[1:] for point in wire) for wire in wires_points]
intersection_points_indexes = []
for point in intersection_points:
first_wire_point, second_wire_point = (wire_without_index.index(point)
for wire_without_index in wires_without_indexes)
intersection_points_indexes.append((first_wire_point, second_wire_point))
steps: list = []
for first_index, second_index in intersection_points_indexes:
first_step = first_wire[first_index][0]
second_step = second_wire[second_index][0]
total_step = first_step + second_step
steps.append(total_step)
fewest_steps: int = min(steps)
return fewest_steps
if __name__ == "__main__":
sample_paths: List[List] = [
['R8,U5,L5,D3', 'U7,R6,D4,L4'],
['R75,D30,R83,U83,L12,D49,R71,U7,L72', 'U62,R66,U55,R34,D71,R55,D58,R83'],
['R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51', 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7']
]
for index, sample in enumerate(sample_paths):
wire_moves: List[Generator] = [(move for move in line.split(",")) for line in sample]
dist: int = get_closest_distance(wire_moves)
print(f'PART1 Sample {index + 1} min distance={dist}')
part_1_dist: int = get_closest_distance(get_wires_moves())
print(f'PART1={part_1_dist}')
for index, sample in enumerate(sample_paths):
wire_moves: List[Generator] = [(move for move in line.split(",")) for line in sample]
dist: int = find_fewest_steps(wire_moves)
print(f'PART2 Sample {index + 1} min distance={dist}')
part_2: int = find_fewest_steps(get_wires_moves())
print(f'PART2={part_2}')
<file_sep>from typing import Generator, Callable
def get_mass_from_file():
with open("input.txt") as file:
yield from file.readlines()
def calculate_single_fuel(mass: int) -> int:
fuel_quantity: int = mass // 3 - 2
return fuel_quantity
def calculate_single_module_with_fuel(initial_fuel: int) -> int:
module_mass: int = calculate_single_fuel(initial_fuel)
left_mass: int = module_mass
while calculate_single_fuel(left_mass) > 0:
left_mass = calculate_single_fuel(left_mass)
module_mass += left_mass
return module_mass
def count_total(calculator: Callable[[int], int]) -> int:
fuels: Generator = (calculator(int(mass)) for mass in get_mass_from_file())
total: int = sum(fuels)
return total
if __name__ == "__main__":
sample: tuple = 12, 14, 1969, 100756
sample_res_part1: list = [calculate_single_fuel(mass) for mass in sample]
print("SAMPLE PART 1:", sample_res_part1)
total_fuel_part1: int = count_total(calculate_single_fuel)
print("PART 1:", total_fuel_part1)
sample_res_part2: list = [calculate_single_module_with_fuel(mass) for mass in sample]
print("SAMPLE PART 2:", sample_res_part2)
total_fuel_part2: int = count_total(calculate_single_module_with_fuel)
print("PART 2:", total_fuel_part2)
<file_sep>import itertools
from typing import List
def get_programs() -> List[int]:
with open("input.txt") as file:
program: List[int] = [int(num) for num in file.read().split(",")]
return program
def process_program(program: List[int]) -> List[int]:
index: int = 0
for index in range(0, len(program), 4):
opcode = program[index]
if opcode == 99:
break
input_1_index, input_2_index, output_index = program[index + 1: index + 4]
input_1, input_2 = program[input_1_index], program[input_2_index]
score: int = get_score(opcode, input_1, input_2)
program[output_index] = score
return program
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
else:
raise ValueError(f"Opcode={opcode} is not in (1, 2, 99)")
return score
def get_program_first_value(program: List[int]) -> int:
first_value: int = program[0]
return first_value
def get_result_first_value_19690720() -> int:
final_noun: int
final_verb: int
for noun, verb in itertools.product(range(100), range(100)):
program = get_programs()
program[1], program[2] = noun, verb
first_value: int = get_program_first_value(process_program(program))
if first_value == 19690720:
final_noun, final_verb = noun, verb
break
result: int = 100 * final_noun + final_verb
return result
if __name__ == "__main__":
sample_programs: List[List[int]] = [
[1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50],
[1, 0, 0, 0, 99],
[2, 3, 0, 3, 99],
[2, 4, 4, 5, 99, 0],
[1, 1, 1, 4, 99, 5, 6, 0, 99]
]
sample_results: tuple = tuple(get_program_first_value(process_program(sample)) for sample in sample_programs)
print("SAMPLE RESULTS:", sample_results)
part_1_result: int = get_program_first_value(process_program(get_programs()))
print("PART1:", part_1_result)
part_2_result: int = get_result_first_value_19690720()
print("PART2:", part_2_result)
<file_sep>import itertools
from typing import List, Coroutine, Union
def get_program() -> List[int]:
with open("input.txt") as file:
program: List[int] = [int(num) for num in file.read().split(",")]
return program
def get_score(opcode: int, input_1: int, input_2: int) -> int:
score: int
if opcode == 1:
score = input_1 + input_2
elif opcode == 2:
score = input_1 * input_2
return score
def process_amplifier(program: List[int], phase: int, initial_input_value: int) -> List[int]:
index: int = 0
diagnostic_code: None = None
while diagnostic_code is None:
instruction_value: str = str(program[index])
opcode: int = int(instruction_value[-2:])
mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index])
if len(instruction_value) >= abs(digit_index) else 0
for digit_index in range(-3, -6, -1))
if opcode not in [3, 4, 99]:
par_1, par_2 = (program[index + instruction_index + 1] if par == 1
else program[program[index + instruction_index + 1]]
for instruction_index, par in enumerate((mode_par_1, mode_par_2)))
if opcode in [1, 2]:
program[program[index + 3]] = get_score(opcode, par_1, par_2)
index += 4
elif opcode == 3:
if phase is not None:
input_signal: int = phase
phase = None
elif initial_input_value is not None:
input_signal: int = initial_input_value
initial_input_value = None
else:
input_signal: int = yield output_signal
program[program[index + 1]] = input_signal
index += 2
elif opcode == 4:
output_signal: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]]
index += 2
elif opcode == 5:
index = par_2 if par_1 != 0 else index + 3
elif opcode == 6:
index = par_2 if par_1 == 0 else index + 3
elif opcode == 7:
program[program[index + 3]] = 1 if par_1 < par_2 else 0
index += 4
elif opcode == 8:
program[program[index + 3]] = 1 if par_1 == par_2 else 0
index += 4
elif opcode == 99:
diagnostic_code: int = output_signal
else:
raise ValueError(f"Opcode={opcode} is not in {(*range(1, 9), 99)})")
return diagnostic_code
def get_diagnostic_code_part_2(program: List[int], phase_combination, initial_input) -> int:
# INITIALIZE AMPLIFIERS
amplifiers: list = []
for amp_index in range(5):
amp: Coroutine = process_amplifier(program, phase_combination[amp_index], initial_input)
amplifiers.append(amp)
initial_input: int = next(amp)
# PROCESS PROGRAMS
code: int = initial_input
diagnostic_code: Union[None, int] = None
for amp in itertools.cycle(amplifiers):
try:
code = amp.send(code)
except StopIteration as e:
if amplifiers.index(amp) == 4:
diagnostic_code = e.value
break
else:
code = e.value
return diagnostic_code
def get_max_signal(program: list, initial_input: int):
max_signal: int = max((get_diagnostic_code_part_2(program, tuple(map(int, list(comb))), initial_input))
for comb in itertools.permutations('56789'))
return max_signal
if __name__ == "__main__":
part_2: int = get_max_signal(program=get_program(), initial_input=0)
print("PART2:", part_2)
<file_sep>import collections
import itertools
from typing import Generator
def read_image_data() -> Generator[int, None, None]:
with open("input.txt") as file:
yield from (int(num) for num in file.read())
def part_1(num_gen: Generator, width: int, height: int):
fewest_0_val_counter: collections.Counter = {0: 100}
while True:
try:
occurrences = collections.Counter(next(num_gen) for _ in range(width * height))
except RuntimeError:
break
if occurrences[0] < fewest_0_val_counter[0]:
fewest_0_val_counter = occurrences
result = fewest_0_val_counter[1] * fewest_0_val_counter[2]
return result
def part_2_decode_image(num_gen: Generator, width: int, height: int) -> dict:
layer_size: int = width * height
decoded_image: dict = {index: 2 for index in range(layer_size)}
for index, num in zip(itertools.cycle(range(layer_size)), num_gen):
if decoded_image.get(index) not in (0, 1):
decoded_image[index] = num
return decoded_image
def message_printer(decoded_image: dict, width_img: int) -> None:
for index, num in decoded_image.items():
end = "" if (index + 1) % width_img != 0 else "\n"
print(num if num == 1 else ".", end=end)
if __name__ == "__main__":
width: int = 25
height: int = 6
part_1_res = part_1(read_image_data(), width, height)
print("PART1:", part_1_res)
part_2_decoded_image = part_2_decode_image(read_image_data(), width, height)
print("PART2:")
message_printer(part_2_decoded_image, width)
| ea7a3267c3057f29ec0519c93d9d25bf2f5fc7ac | [
"Python"
] | 13 | Python | Naatoo/advent-of-code-2019 | e382379bc0233b9728b7780345cd8c59457c77cf | 96dde860a7c68cabd2996e1ae67eb0d1efc19020 |
refs/heads/master | <file_sep>import logo from "./logo.svg";
import "./App.css";
import "bootstrap/dist/css/bootstrap.css";
function App() {
const name = "리액트";
return (
<div className="App-header">
<div className="container App">
<div className="row">
<div className="col-md-6">
{name === "리액트" ? <h1>Hello</h1> : <h1>Bye</h1>}
</div>
<div className="col-md-6">
<h1>{name}</h1>
</div>
<div className="col-md-12">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</header>
</div>
</div>
</div>
</div>
);
}
export default App;
| 9ac49b748cb2a4f3e795993ed5dea31b4fe92548 | [
"JavaScript"
] | 1 | JavaScript | gootaehyun/ReactStudy | 52ae6686fef742b853d9caf923a86aef09a10ff1 | cf91b0a3f34a6c13ab35a80291074b029f882d8b |
refs/heads/master | <file_sep>from flask import Flask, render_template, request
app = Flask(__name__, template_folder='view')
@app.route("/")
def index() :
html = render_template('index.html')
return html
# get : 파라미터 데이터를 주소에 붙혀서 보낸다. 주소에 직접 붙혀서 보내기
# 때문에 전체 용량이 적다. 이 때문에 속도가 빠르다.
# 영문,숫자,특수문자 일부만 가능하며 전체 주소가 255글자 이상을
# 넘지 못한다는 단점을 가지고 있다.
# post : 파라미터 데이터를 요청 정보 내부에 숨겨서 보낸다.
# 부가 정보가 추가로 들어가기 때문에 전체 용량이 get보다 많으며
# 이 때문에 속도가 느리다.
# 모든 문자를 전달할 수 있으며 길이에 제한이 없다.
# 사용자에게 입력받는 데이터 => post, 그 외 => get
@app.route('/second', methods=['GET', 'POST'])
def second() :
data3 = request.values.get('data2')
# 요청 방식으로 분기한다.
if request.method == 'POST' :
# 파라미터 데이터를 추출한다.
data1 = request.form['data1']
data2 = request.form.get('data2')
return f'data1 : {data1}, data2 : {data2}, data3 : {data3}'
elif request.method == 'GET' :
# 파라미터 데이터를 추출한다.
data1 = request.args['data1']
data2 = request.args.get('data2')
return f'data1 : {data1}, data2 : {data2}, data3 : {data3}'
return 'Hello World'
app.run(host='0.0.0.0', port=80)<file_sep>from flask import Flask, render_template, request
app2 = Flask(__name__, template_folder='view')
@app2.route("/")
def index() :
html = render_template('index.html')
return html
@app2.route('/two', methods=['GET','POST'])
#get 은 url에 데이터를 붙여서 보내고 post는 body값에 데이터를 넣어서 보냄
def two():
data3 = request.values.get('data2') #get, post 둘다 가능
#요청 방식으로 분기
if request.method == 'POST' :
data1 = request.form['data1']
data2 = request.form.get('data2')
return f'data1 : {data1}, data2 :{data2}, data3 :{data3}'
elif request.method == 'GET' :
data1 = request.args['data1']
data2 = request.args.get('data2') #없을 때 오류가 나나 안나냐
return 'data1 : {0}, data2 : {1}, data3 : {2}'.format(data1,data2,data3)
return 'Hello World'<file_sep># Flask 모듈을 포함한다.
from flask import Flask, render_template
# Flask 객체를 생성한다.(매개 변수 : 아무 문자열)
# template_folder : 사용할 템플릿 html이 들어 있는 폴더를 지정한다.
app = Flask(__name__, template_folder='view')
# app.route : 클라이언트가 요청했을 때 호출될 함수를 등록
@app.route("/")
def index() :
# 클라이언트 브라우저에게 전달할 문자열을 반환한다.
# return 'Hello World'
# return '<h1>Hello World</h1><br/><h3>flask</h3>'
# 클라이언트 브라우저에게 전달할 문자열을 html 파일로 부터 읽어와
# 생성한다.
html = render_template('index.html')
return html
#app.run()
# 서버 가동
# host='0.0.0.0' : 모든 디바이스에서 접속 가능하도록 설정
# port=80 : 포트 번호를 80번으로 설정
app.run(host='0.0.0.0', port=80, debug=True)
# SET FLASK_APP=main.py
# flask run
<file_sep>from flask import Blueprint, render_template
blue200 = Blueprint('blue200', __name__, template_folder='view/sub2')
@blue200.route('/test4')
def test4() :
html = render_template('sub2/test4.html')
return html
<file_sep>"""View Instagram user follower count from Instagram public api"""
import requests
def getfollowedby(url):
"""View Instagram user follower count"""
link = 'https://www.instagram.com/%s/?__a=1'
tag = link % (url)
user = requests.get(tag)
print(user.json())
follower = (user.json()['graphql']['user']['edge_followed_by']['count'])
#return (user.json()['graphql']['user']['edge_owner_to_timeline_media']['edges'][0]['node']['thumbnail_src'])
lst_thumbnail = []
for i in range(10):
lst_thumbnail.append(user.json()['graphql']['user']['edge_owner_to_timeline_media']['edges'][i]['node']['thumbnail_src'])
return (follower, lst_thumbnail)
def getname(url):
"""Split the URL from the username"""
return url.replace("https://", "").replace("www.", "").replace("instagram.com/", "").replace("/", "")
<file_sep>from flask import Blueprint, render_template, request
blue100 = Blueprint('blue1', __name__, template_folder='templates/sub1')
# blue100 = Blueprint('blue1', __name__, url_prefix='/blue1', template_folder='templates/sub1')
@blue100.route('/test3')
def test3() :
html = render_template('test2.html')
return html<file_sep>-- 1. 부서별 직원 수를 구하시오.
-- 부서를 추출하고, 각 부서의 인원수를 계산하는 것
SELECT D.DEPT_NAME
, (SELECT COUNT(*)
FROM DEPT_EMP DE
WHERE DE.TO_DATE = '9999-01-01'
AND DE.DEPT_NO=D.DEPT_NO)
FROM DEPARTMENTS D;
-- 부서와 인원 테이블을 조인해서 데이터를 구성하고 부서명으로 그룹화 한 뒤 인원을 계산
SELECT D.DEPT_NAME, COUNT(*)
FROM DEPARTMENTS D
INNER JOIN DEPT_EMP DE ON DE.DEPT_NO=D.DEPT_NO
WHERE DE.TO_DATE = '9999-01-01'
GROUP BY D.DEPT_NAME;
-- 문자열로 그룹화 하는 것보다는 정형화된 코드로 그룹화하는 것이 좋다.
SELECT DEPT_NAME, CNT
FROM DEPARTMENTS D
INNER JOIN (
SELECT DEPT_NO, COUNT(*) CNT
FROM DEPT_EMP
WHERE TO_DATE='9999-01-01'
GROUP BY DEPT_NO
) DS ON D.DEPT_NO = DS.DEPT_NO
ORDER BY D.DEPT_NO;
-- 2. 각 부서에서 가장 오래 근무한 직원을 출력하시오.
SELECT DEPT_NAME
, (SELECT FIRST_NAME
FROM DEPT_EMP DE
INNER JOIN EMPLOYEES E ON E.EMP_NO = DE.EMP_NO
WHERE DE.TO_DATE = '9999-01-01'
AND DE.DEPT_NO=D.DEPT_NO
ORDER BY FROM_DATE
LIMIT 1) EMPLOYEE
FROM DEPARTMENTS D;
-- 3. 가장 오래된 직원 10명이 근무했던 처음과 마지막 부서를 출력하시오.
SELECT EM.*
, (SELECT DEPT_NAME
FROM DEPT_EMP DEE, DEPARTMENTS DE
WHERE DEE.DEPT_NO=DE.DEPT_NO
AND DEE.EMP_NO = EM.EMP_NO
ORDER BY FROM_DATE LIMIT 1) FIRST_DEPT
, (SELECT DEPT_NAME
FROM DEPT_EMP DEE, DEPARTMENTS DE
WHERE DEE.DEPT_NO=DE.DEPT_NO
AND DEE.EMP_NO = EM.EMP_NO
ORDER BY FROM_DATE DESC LIMIT 1) LAST_DEPT
FROM EMPLOYEES EM
ORDER BY HIRE_DATE
LIMIT 10;
-- 4. 각 부서에서 급여를 가장 많이 받는 직원 리스트를 구하시오.
SELECT DEPT_NAME
, (SELECT FIRST_NAME
FROM DEPT_EMP DE
INNER JOIN EMPLOYEES E ON E.EMP_NO = DE.EMP_NO
INNER JOIN SALARIES S ON S.EMP_NO = DE.EMP_NO
WHERE DE.TO_DATE = '9999-01-01'
AND DE.DEPT_NO = D.DEPT_NO
ORDER BY SALARY DESC
LIMIT 1) EMPLOYEE
FROM DEPARTMENTS D;
-- 5. 전체 평균보다 많이 받는 직원 수를 계산하시오.
SELECT COUNT(*) -- 107706
FROM SALARIES S
WHERE S.TO_DATE = '9999-01-01'
AND SALARY >= (SELECT AVG(SALARY)
FROM SALARIES
WHERE TO_DATE = '9999-01-01');
-- 6. 퇴직한 직원 정보를 구하시오.
SELECT *
FROM EMPLOYEES E
WHERE NOT EXISTS(SELECT 1 FROM DEPT_EMP DE
WHERE DE.TO_DATE = '9999-01-01'
AND E.EMP_NO=DE.EMP_NO);
SELECT *
FROM EMPLOYEES E
WHERE EMP_NO NOT IN (SELECT DISTINCT EMP_NO
FROM DEPT_EMP DE
WHERE DE.TO_DATE = '9999-01-01');
<file_sep>import sqlite3
print('sqlite3.version',sqlite3.version)
print('sqlite3.sqlite_version', sqlite3.sqlite_version)
# DB 생성 & Autocommit
# 본인 DB 파일 경로
conn = sqlite3.connect('database_new.db')
# DB생성(메모리)
# conn = sqlite3.connect(':memory:')
# Cursor 연결
c = conn.cursor()
print('Cursor Type : ', type(c))
# 테이블 생성(Datatype : TEXT NUMERIC INTEGER REAL BLOB)
c.execute(
'''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
email TEXT,
phone TEXT,
website TEXT,
regdate TEXT)
''') # id INTEGER PRIMARY KEY AUTOINCREMENT, 안겹치게 자동증가 시킴, 대소문자 구분 x
import datetime
#삽입 날짜 생성
now = datetime.datetime.now()
print('now', now)
nowDatetime = now.strftime('%Y-%m-%D %H:%M:%S')
print('nowDatetime', nowDatetime)
sql = '''INSERT INTO users (username, email, phone, website, regdate) VALUES ('Kim', '<EMAIL>', '010-0000-0000', 'Kim.com', ?)'''
#데이터 삽입
c.execute(sql, (nowDatetime,))
sql1 = """ INSERT INTO users
(username, email, phone, website, regdate)
VALUES (?, ?, ?, ?, ?)"""
c.execute(sql1, ('Park', '<EMAIL>',
'010-1111-1111', 'Park.com',
nowDatetime))
# c.execute('''DELETE FROM users WHERE id=6''')
# c.execute('''DELETE FROM users WHERE id=7''')
# c.execute('''DELETE FROM users WHERE id=8''')
# c.execute('''DELETE FROM users WHERE id=9''')
# c.execute('''DELETE FROM users WHERE id=10''')
#
#Many 삽입(튜플, 리스트)
userList = (
('Lee', '<EMAIL>', '010-2222-2222', 'Lee.com', nowDatetime),
('Cho', '<EMAIL>', '010-3333-3333', 'Cho.com', nowDatetime),
('Yoo', '<EMAIL>', '010-4444-4444', 'Yoo.com', nowDatetime)
)
c.executemany("INSERT INTO users(username, email, phone, website, regdate) VALUES (?, ?, ?, ?, ?)", userList)
conn.commit()
# c.execute('''INSERT INTO users
# (id, username, email, phone, website, regdate) VALUES (?, ?, ? ,? ,? ,?),
# (2, 'Park', '<EMAIL>', '010-1111-1111', 'Park.com', nowDatetime)
# ''')
conn.close()<file_sep>from flask import Flask, render_template
# Flask 객체를 생성한다.
app = Flask(__name__, template_folder='view')
# 주소만 입력했을 경우 호출되는 함수
@app.route("/")
def index() :
html = render_template('index.html')
return html
# second를 요청했을 때 호출되는 함수
@app.route('/second')
def second() :
html = render_template('second.html')
return html
# third를 요청했을 때 호출되는 함수
@app.route('/third')
def third() :
html = render_template('third.html')
return html
# 서버 가동
app.run(host='0.0.0.0', port=80)
<file_sep># 1. 화면에 "Hello World!"를 출력하세요.
print('"Hello World!"')
# 2. 화면에 "I don't like C language"를 출력하세요.
print('"I don\'t like C language"')
# 3. print 함수를 사용하여 3.1415의 값을 출력하세요.
# 단, 소수점 아래는 첫 번째 자리까지만 표시되도록 하세요.
pi = 3.1415
print('%.1f' % pi)
# 4. 문자열 '720'를 정수형으로 변환하세요. 정수 100을 문자열 '100'으로 변환하세요.
a = '720'
print(int(a), type(int(a)))
a = 100
str(100)
# 5. 2와 4 숫자를 변수에 넣고, 두 변수를 더한 값, 곱한 값, 나눈 값을 출력하세요.
a , b = (2,4)
print(a+b,a*b,a/b)
# 6. 사용자로부터 두 개의 숫자를 입력받은 후 두 개의 숫자를 더한 값, 곱한 값을 각각 출력하는 프로그램을 작성하세요
a = input()
b = input()
print(int(a)+int(b),int(a)*int(b))
print(int(a)+int(b),int(a)*int(b))
# 7. 'niceman', 'google.com' 문자열을 연속해서 출력할때 구분자를 @으로 변경하여 출력하세요.
a = 'niceman'
b = 'google.com'
print(a,b,sep='@')
#8. str = 'Niceboy' 이 변수를 이용해서 아래와 같은 결과가 나오도록 슬라이싱하여 출력하세요.
'''
Nic
Niceboy
Nicebo
Niceboy
ie
bo
iceb
yobeciN
Ncby
'''
str = 'Niceboy'
l = list(str)
l.reverse()
print(str[:3],str[:],str[:-1],str[:],str[1:2]+str[3:4],str[4:6],str[1:5],''.join(l),str[::2],sep="\n")
print(''.join(l),str[::-1],sep="\n")
<file_sep>import pymysql
conn = pymysql.connect(host = 'localhost',
port = 3306,
user = 'root',
passwd = '<PASSWORD>',
db = 'pyMysql_db',
charset = 'utf8')
curs = conn.cursor() # 튜플커서
sql = 'select * from member'
curs.execute(sql)
rows = curs.fetchall()
print(rows)
print(rows[0])
for row in rows:
print(row)
print('-' *50)
rows = curs.fetchall()
print(rows) #커서가 내려감
curs.execute(sql)
row = curs.fetchone()
print(row)
curs.execute(sql)
row = curs.fetchmany(3)
print(row)
curs = conn.cursor(pymysql.cursors.DictCursor)
curs.execute(sql)
rows = curs.fetchall()
for row in rows:
print(type(row), row['userid'], row['name'], row['pwd'])
conn.close()<file_sep>USE employees;
USE mysql;
select * from employees;
select * from titles;
select * from employees.titles;
select * from titles;
select first_name from employees;
select first_name, last_name, gender From employees;
select first_name as f_name, last_name as l_name, gender as '성별' from employees;
show databases;
use employees;
show table status;
show tables;
describe employees;
select first_name as 이름, gender 성별, hire_date '회사입사일' from employees;
select CONCAT(first_name, " ", last_name) as fullname, gender as 성별 from employees;
use sqldb;
select * from usertbl;
select * from usertbl where name like '김%';
select userid, name, birthyear, height from usertbl where birthyear >= 1970 and height >=182;
select userid, name, birthyear, height from usertbl where birthyear >= 1970 or height >=182;
select name, height from usertbl where height >=180 and height <= 183;
select name, height from usertbl where height between 180 and 183;
select name, addr from usertbl where addr='경남' or addr ='전남' or addr='경북';
select name, addr from usertbl where addr in ('경남','전남','경북');
select name, height from usertbl where name like '김%';
select name, hegith from usertbl where name like '_종신';
select name, height from usertbl where name >= '가' and name < '나';
select name, height from usertbl where height > (select height from usertbl where name = '김경호');
select name, height from usertbl where height in (177,182);
select name, height from usertbl where name in ('임재범','김경호');
select name, height from usertbl where name in (select name from usertbl where name in ('임재범','김경호'));
select name, height, addr from usertbl where height >= all
(select height from usertbl where addr = '경남');
select name, height, addr from usertbl where height >= any
(select height from usertbl where addr = '경남');
select name, height, addr from usertbl where height >=
(select min(height) from usertbl where addr = '경남');
select name, height, addr from usertbl where height >=
(select max(height) from usertbl where addr = '경남');
select name, height from usertbl where height in
(select height from usertbl where addr = '경남');
select name, mdate from usertbl order by mdate desc;
use employees;
select concat(first_name, ' ',last_name) as 이름, gender as 성별 from employees order by 1;
use sqldb;
select addr from usertbl;
select distinct addr from usertbl;
select addr from usertbl group by addr;
select distinct addr, height from usertbl order by addr;
select addr, height from usertbl group by addr, height order by 1,2;
create table buytbl2 (select userid, prodname from buytbl where 1 = 0);
select * from buytbl2;
create table buytbl3 (select userid, prodname from buytbl);
select * from buytbl3;
select userid, amount from buytbl order by userid;
select userid, sum(amount) from buytbl group by userid;
select count(*) from usertbl;
select count(userid) from usertbl;
select count(mobile1) from usertbl;
select avg(amount) as '평균 구매 개수' from buytbl;
select name, max(height), min(height) from usertbl;
select name, height from usertbl where height = (select max(height) from usertbl) or height = (select min(height) from usertbl);
select count(*) from usertbl;
select count(mobile1) as '휴대폰 있는 사용자' from usertbl;
select userid as 사용자, sum(price*amount) as 총구매액 from buytbl group by userid;
select userid as 사용자, sum(price*amount) as 총구매액 from buytbl
where price >0 and amount > 0 -- where 절에 집계 쓰지 않는다
group by userid
having sum(price*amount) > 1000;
create table testtbl1(id int, userName char(3), age int);
insert into testtbl1 values (1,'홍길동',25);
insert into testtbl1(id, username) values (2,'설민석');
insert into testtbl1(username,age, id) values ('홍길동',25,3);
select * from testtbl1;
select @@autocommit;
set autocommit = true;
alter table testtbl1 auto_increment = 100;
insert into testtbl1 values( null,'찬미',10);
select * from testtbl1;
create table testtbl2(id int, fname char(30), lname char(30));
insert into testtbl2(id, fname, lname) select emp_no, first_name, last_name from employees.employees;
select * from testtbl2;
use sqldb;
create table bigtbl1 (select * from employees.employees);
create table bigtbl2 (select * from employees.employees);
create table bigtbl3 (select * from employees.employees);
delete from bigtbl1;
drop table bigtbl2;
truncate table bigtbl3;
set @myVar1 = 5;
set @myVar2 = 4;
set @myVar3 = 2;
set @myVar4 = '가수이름==> ';
select @myVar1, @myVar2, @myVar3;
-- cast as
use sqldb;
select cast(avg(amount) as signed integer)
as '평균 구매 개수' from buytbl;
select cast('2020-12-12' as date) as date;
select cast(-12.5 as signed integer);
select cast(12.5 as unsigned integer);
select cast(123 as char(5));
select rpad(cast(123 as char(5)),5,'0'); -- 전체 자리에 맞춰서 나머지를 채움
select lpad(cast(123 as char(5)),5,'0'); -- 전체 자리에 맞춰서 나머지를 채움
select concat_ws('/', 'a', 'b', 'c');
select concat('100','200');
select concat(100,'200');
select '100' + '200';
select 1 > '2mega';
select if (100>200, '참이다', '거짓이다');
select case 10
when 1 then 'asdf'
when 5 then 'asdc'
when 10 then '십'
else '모름'
end;
select format(123456.123456, 14);
select insert('abcdefghi',3,4,'@@@@'),insert('abcdefghi',3,2,'@@@@');
select lower('abcdEFGH'), upper('abcdEFGH');
select left('abcdefghi',3), right('abcdefghi',3);
select trim(' 이것이 ');
select replace('이것이 mysql이다','이것이','This is');
select repeat('살려줘',3);
select reverse('mysql');
select concat('이것이', space(10), 'asdf이다');
select substring('대한민국만세',3,2);
select rand(), rand() * (6-1), rand()*(6-1)+1; -- 0에서 1사이
select now();<file_sep>-- 1. 부서별 부서장 정보를 출력하시오.
SELECT DEPT_NAME, FIRST_NAME, LAST_NAME, SALARY
FROM DEPT_MANAGER DM
INNER JOIN DEPARTMENTS DEP ON DEP.DEPT_NO=DM.DEPT_NO
INNER JOIN EMPLOYEES EMP ON EMP.EMP_NO=DM.EMP_NO
INNER JOIN SALARIES SAL ON SAL.EMP_NO=DM.EMP_NO AND SAL.TO_DATE = DM.TO_DATE
WHERE DM.TO_DATE='9999-01-01'
ORDER BY DEPT_NAME;
-- 2. 부서별 정보(부서장, 부서별 급여 평균)을 출력하시오.
SELECT DEPT_NAME, FIRST_NAME, LAST_NAME, AVG_SALARY
FROM DEPT_MANAGER DM
INNER JOIN DEPARTMENTS DEP ON DEP.DEPT_NO=DM.DEPT_NO
INNER JOIN EMPLOYEES EMP ON EMP.EMP_NO=DM.EMP_NO
INNER JOIN (
SELECT DEPT_NO, AVG(SALARY) AVG_SALARY
FROM DEPT_EMP DE
INNER JOIN SALARIES SAL ON SAL.EMP_NO=DE.EMP_NO
WHERE DE.TO_DATE='9999-01-01' AND SAL.TO_DATE='9999-01-01'
GROUP BY DEPT_NO
) DS ON DS.DEPT_NO=DM.DEPT_NO
WHERE DM.TO_DATE='9999-01-01'
ORDER BY DEPT_NAME;
-- 3. 부서별 직원 리스트를 출력하되 부서장이면 표시를 하고,
-- 각 부서에서 가장 먼저 나오게 출력하시오.
SELECT DEPT_NAME, FIRST_NAME, LAST_NAME,
IF(DM.EMP_NO IS NULL, NULL, 'MANAGER') POSITION
FROM DEPT_EMP DE
INNER JOIN DEPARTMENTS DEP ON DEP.DEPT_NO=DE.DEPT_NO
INNER JOIN EMPLOYEES EMP ON EMP.EMP_NO=DE.EMP_NO
LEFT OUTER JOIN DEPT_MANAGER DM ON DM.EMP_NO=DE.EMP_NO AND DM.TO_DATE='9999-01-01'
WHERE DE.TO_DATE='9999-01-01'
ORDER BY DEPT_NAME, DM.EMP_NO DESC, FIRST_NAME, LAST_NAME;
-- 4. 1999 년의 월별 신입 사원수를 출력하시오
SELECT MONTH(HIRE_DATE), COUNT(*)
FROM EMPLOYEES
WHERE YEAR(HIRE_DATE)=1999
GROUP BY MONTH(HIRE_DATE);
-- 5. 1999 년의 월별 신입 사원수를 피봇으로 출력하시오
-- (M1 ~ M12까지 컬럼으로 출력)
SELECT YR
,SUM(CASE WHEN MM=1 THEN CNT ELSE 0 END) M1
, SUM(CASE WHEN MM=2 THEN CNT ELSE 0 END) M2
, SUM(CASE WHEN MM=3 THEN CNT ELSE 0 END) M3
, SUM(CASE WHEN MM=4 THEN CNT ELSE 0 END) M4
, SUM(CASE WHEN MM=5 THEN CNT ELSE 0 END) M5
, SUM(CASE WHEN MM=6 THEN CNT ELSE 0 END) M6
, SUM(CASE WHEN MM=7 THEN CNT ELSE 0 END) M7
, SUM(CASE WHEN MM=8 THEN CNT ELSE 0 END) M8
, SUM(CASE WHEN MM=9 THEN CNT ELSE 0 END) M9
, SUM(CASE WHEN MM=10 THEN CNT ELSE 0 END) M10
, SUM(CASE WHEN MM=11 THEN CNT ELSE 0 END) M11
, SUM(CASE WHEN MM=12 THEN CNT ELSE 0 END) M12
FROM (
SELECT YEAR(HIRE_DATE) YR
, MONTH(HIRE_DATE) MM
, COUNT(*) CNT
FROM EMPLOYEES
-- WHERE YEAR(HIRE_DATE) in (1998, 1999)
GROUP BY YEAR(HIRE_DATE), MONTH(HIRE_DATE)
) DS
group by yr;
SELECT YEAR(HIRE_DATE) YR
, MONTH(HIRE_DATE) MM
, COUNT(*) CNT
FROM EMPLOYEES
WHERE YEAR(HIRE_DATE) in (1998, 1999)
GROUP BY YEAR(HIRE_DATE), MONTH(HIRE_DATE);
<file_sep>from flask import Flask, render_template, request
app = Flask(__name__, template_folder='view')
@app.route('/')
def index() :
test_dic = {
'a1' : 100,
'a2' : '문자열'
}
test_list = (10, 20, 30, 40, 50)
html = render_template('index.html',
data_dic=test_dic,
data_list=test_list)
return html
app.run(host='127.0.0.1', port=80)
<file_sep>from flask import Flask, render_template, request
app = Flask(__name__, template_folder='view')
@app.before_first_request #이벤트 5개
def before_first_request(): #db 오픈
print('before_first_request, 앱 기동하고 맨처음 요청만 응답')
@app.before_request
def before_request():
print('before_request, 모든 요청에대해 응답, view함수')
@app.after_request
def after_request(response):
print('after_request,매 요청 처리되고 나서, 브라우저에 응답하기 전 실행')
return(response)
@app.teardown_request #db 클로즈
def teardown_request(exception):
print('teardown_request,브라우저에 응답한 다음 실행')
return exception
@app.teardown_appcontext
def teardown_appcontext(exception):
print('teardown_appcontext, 요청이 완전히 끝나고 app_context 블록안에서 사용된 객체를 제거할 때 사용')
return exception
# @app.route('/', methods=['GET','POST'])
# def helloword():
# # return "Hello World"
# return render_template('one.html', name='홍길동')
@app.route('/') # GET 생략 하이퍼 링크는 get 방식, summit이 들어가는게 post
def one():
html = render_template('one.html')
return html
@app.route('/two', methods=['GET','POST'])
def two():
#요청 방식
print(f'요청방식 : {request.method}')
# print('요청방식 : {0}'.format(request.method))
# if request.method == 'POST' :
html = render_template('two.html')
return html
@app.route('/three')
def three():
html = render_template('three.html')
return html
# @app.route('/<name>') #파라미터 넘기기 : 라우팅
# def index(name):
# return render_template('index.html', name=name)
@app.route('/sleep')
def NoSleep():
return "<h1>주무시지 마시오</h1>"<file_sep>-- 1. 부서별 부서장 정보를 출력하시오.
use employees;
select dept_name, first_name, last_name
from dept_manager dm
inner join departments dep on dep.dept_no = dm.dept_no
inner join employees emp on emp.emp_no = dm.emp_no
WHERE dm.TO_DATE = '9999-01-01'
group by dm.dept_no;
-- 2. 부서별 정보(부서장, 부서별 급여 평균)을 출력하시오.
select dept_name, first_name, last_name, avg
from dept_manager dm
inner join departments dep on dep.dept_no = dm.dept_no
inner join employees e on e.emp_no = dm.emp_no
inner join (
select d.dept_no , avg(s.salary) avg
from salaries s
inner join dept_emp d on s.emp_no = d.emp_no
WHERE D.TO_DATE = '9999-01-01' and S.TO_DATE = '9999-01-01'
group by d.dept_no) A on dm.dept_no = A.dept_no
WHERE Dm.TO_DATE = '9999-01-01' ;
-- 3. 부서별 직원 리스트를 출력하되 부서장이면 표시를 하고,
-- 각 부서에서 가장 먼저 나오게 출력하시오.
select dept_name, first_name, last_name
,if(dm.emp_no is null, null, 'manager') position
from dept_emp de
inner join departments dep on dep.dept_no = de.dept_no
inner join employees emp on emp.emp_no = de.emp_no
left outer join dept_manager dm on dm.emp_no = de.emp_no
WHERE de.TO_DATE = '9999-01-01'
order by dept_name, dm.emp_no desc;
-- 4. 1999 년의 월별 신입 사원수를 출력하시오
select month(from_date),count(from_date);
select year(hire_date)
from employees
where year(hire_date) in (1998, 1999)
group by month(hire_date)
order by month(hire_date);
-- 5. 1999 년의 월별 신입 사원수를 피봇으로 출력하시오
-- (M1 ~ M12까지 컬럼으로 출력)
select year(hire_date),
sum(if(month(hire_date) in (1), 1,0)) as 'M1',
sum(if(month(hire_date) in (2), 1,0)) as 'M2',
sum(if(month(hire_date) in (3), 1,0)) as 'M3',
sum(if(month(hire_date) in (4), 1,0)) as 'M4',
sum(if(month(hire_date) in (5), 1,0)) as 'M5',
sum(if(month(hire_date) in (6), 1,0)) as 'M6',
sum(if(month(hire_date) in (7), 1,0)) as 'M7',
sum(if(month(hire_date) in (8), 1,0)) as 'M8',
sum(if(month(hire_date) in (9), 1,0)) as 'M9',
sum(if(month(hire_date) in (10), 1,0)) as 'M10',
sum(if(month(hire_date) in (11), 1,0)) as 'M11',
sum(if(month(hire_date) in (12), 1,0)) as 'M12'
from employees
where year(hire_date) in (1998, 1999)
group by year(hire_date);
SELECT YEAR(HIRE_DATE) YR
, MONTH(HIRE_DATE) MM
, COUNT(*) CNT
FROM EMPLOYEES
WHERE YEAR(HIRE_DATE) in (1998, 1999)
GROUP BY YEAR(HIRE_DATE), MONTH(HIRE_DATE);<file_sep>from pymongo import MongoClient
import datetime
client = MongoClient('mongodb://127.0.0.1:27017/')
db = client.python_db
def insert():
title = input('제목 : ')
writer = input('작성자 : ')
contents = input('내용 : ')
db.blog.insert_one({
'title': title,
'contents': contents,
'writer': writer,
'wdate': datetime.datetime.now().strftime('%Y-%m-%d, %H:%M:%S')
})
print('-' * 50)
def select():
rows = db.blog.find()
for row in rows:
print(row['title'], row['contents'], row['writer'], row['wdate'])
print('-'*50)
def update():
from_title = input('원본제목 : ')
to_title = input('수정제목 : ')
db.blog.update_one({'title': from_title},{'$set':{'title':to_title}})
print('-' * 50)
def delete():
title = input('삭제제목 :')
db.blog.delete_one({'title': title})
print('-' * 50)
while 1:
sel = input('1.목록 2.추가 3.수정 4.삭제 0.종료')
if sel == '1':
select()
elif sel == '2':
insert()
elif sel == '3':
update()
elif sel == '4':
delete()
elif sel == '0':
break
<file_sep># 함수 < 클래스 < 모듈 < 패키지
# def 함수명(입력 인수) :
# <수행할 문장 1>
# <수행할 문장 2>
# 여러개 한꺼번에 return이 가능하다
def sum_mul(n1, n2):
return n1 + n2, n1 * n2
print(sum_mul(3, 5))
result = sum_mul(3, 5) # 튜플로 받기
x, y = sum_mul(3, 5) # 각각 받기
print(type(result))
print(' 합은 {}, 곱은 {} 입니다.'.format(result[0], result[1]))
def say_myself(name, old, man=True): # 미리 기본 값 주기, 기본 값을 주면 안넘겨줘도 된다
print('나의 이름은 %s 입니다.' % name) # 기본 값은 뒤로
print('나이는 %d살 입니다' % old)
if man:
print('남자입니다')
else:
print('여자 입니다')
say_myself('홍길동', 17)
say_myself('기본값', 17, False)
def say_myself(name, man=True, old=10): # 미리 기본 값 주기, 기본 값을 주면 안넘겨줘도 된다
print('나의 이름은 %s 입니다.' % name) # 기본 값은 뒤로
print('나이는 %d살 입니다' % old)
if man:
print('남자입니다')
else:
print('여자 입니다')
say_myself('홍길동', old=20) # 파라미터가 여러개인경우 이름까지 넘겨줘야함
say_myself('홍길동', man=False, old=20)
# 가변 인자 함수
# 가변 입력 값 : *args : tuple, **kwargs : dictionary
def add(a, b, c): # 파이썬은 함수 이름이 달라야한다.
print(a + b + c) # 오버로딩 안됨(중복정의), 오버 라이딩 됨(재정의)
add(2, 3, 4)
def add_arg(*args):
total = 0
for arg in args:
total += arg
print(total)
add_arg(1, 2, 3, 4, 5)
def cal(choice, *args): # 가변아닌게 앞으로
if choice == 'Sum':
result = 0
for i in args:
result += i
elif choice == 'Diff':
result = 0
for i in args:
result -= i
print(result)
cal('Diff', 1, 2, 3)
def myNum(**kwargs):
print(kwargs)
print('First value : {first}'.format(**kwargs))
print('Second value : {second}'.format(**kwargs))
myNum(first=1, second=2)
def kwargs_func(**kwargs):
for v in kwargs.keys():
print('{} {}'.format(v, kwargs[v]), end=' ')
print()
kwargs_func(name1='Kim')
kwargs_func(name1='Kim', name2='Park')
kwargs_func(name1='Kim', name2='Park', name3='Lee')
def kwargs_funci(**kwargs):
for k, v in kwargs.items():
print('{} {}'.format(k, v), end=' ')
print('ck')
kwargs_funci(name1='Kim')
kwargs_funci(name1='Kim', name2='Park')
kwargs_funci(name1='Kim', name2='Park', name3='Lee')
def args_func(*args):
for i, v in enumerate(args): # enumerate 알아서 스스로 인덱스를 붙여줌
print('{}'.format(i), v, end=' ')
print()
args_func('Kim')
args_func('Kim', 'Park')
args_func('Kim', 'Park', 'Lee')
def example(arg_1, arg_2, *args, **kwargs): # 섞었을 때 우선순위: 고정, 가변, 기본값
print(arg_1, arg_2, args, kwargs)
example(10, 20)
example(10, 20, 'park', 'kim')
example(10, 20, 'park', age1=33, age2=34)
example(10, 20, 'park', 'kim', 'lee', age1=33, age2=34, age3=44)
def bmi(a, b):
result = (b / ((a / 100) ** 2))
print('bmi = %.2f' % result)
if 35 < result:
print('고도비만')
elif 30 <= result:
print('중고도비만')
elif 25 <= result:
print('경도비만')
elif 23 <= result:
print('과체중')
elif 18.5 <= result:
print('정상')
else:
print('저체중')
bmi(170, 60)
# * 리스트나 튜플 언팩킹
# ** 딕셔너리 키, 값 언팩킹
lst = [11, 3, 4, 5, 'list']
print(lst)
print(*lst)
kwargs = {'first_name': 'john', 'last_name': 'doe', 'username': 'johndoe', 'email': 'jhlee@asdf', 'passwrd': '<PASSWORD>'}
print(*kwargs) # 키들만 언팩킹
print('첫번 째 key : {0}, 두번째 key : {1}'.format(*kwargs))
# 딕셔너리의 키: 값으로만 언팩킹
print('first_name : {first_name}, last_name : {last_name}'.format(**kwargs))
# 전역변수가 Rvalue면 b = a+2 전역변수 값을 읽어온다
# Lvalue 쪽으로 오면 지역
# global a 로하면 전역씀
def call_by_value(num, mlist):
num = num + 1
mlist.append('add 1')
num = 10
mlist = [1, 2, 3]
print(num, mlist)
call_by_value(num, mlist)
print(num, mlist)
# 중첩함수 내포함수
def nested_func(num):
def func_in_func(num):
print(num)
print('in func')
func_in_func(num + 100)
nested_func(1)
def gugu(p):
for j in range(1, 10):
print('%d x %d = %2d' % (p, j, p * j), end='\t')
gugu(6)
print()
# 람다 함수
# 익명 함수
# 쓰고 버리는 일시적인 함수
# 메모리 절약 가능하다
f = lambda x, y: x + y
print(f(4, 4))
f = lambda x: x ** 2
print(f(8))
print((lambda x, y: x + y)(12, 20))
f = lambda x: x * 10
t = lambda x, y: x * y
print(f(2))
print(f(5))
print(t(2, 6))
# 고차함수
def func_final(x, y, func):
result = x * y * func
return result
print(func_final(10, 10, f(10)))
def circle_area(radius, print_format):
area = 3.14 * (radius ** 2)
print_format(area)
def precise_low(value):
print('결과값: ', round(value, 1))
def precise_high(value):
print('결과값: ', round(value, 2))
circle_area(3, precise_low)
circle_area(3, precise_high)
# 함수의 스코프
x = 'global'
def outer():
x = 'local' # 내부 x 로컬로 생성
def inner():
nonlocal x # x는 로컬이아니다 --> local
x = 'nonlocal' # x값 nonlocal로 local 값이 바뀜
print('inner:', x) # non local
inner()
print('outer:', x)
outer()
print('global :', x)
def scope_test():
def do_local():
spam = 'local spam'
print('dolocal', spam)
def do_nonlocal():
nonlocal spam
spam = 'nonlocal spam'
def do_global():
global spam
spam = 'global spam'
spam = 'test spam'
do_local()
print('After local assignment:', spam)
do_nonlocal()
print('After nonlocal assignment:', spam)
do_global()
print('After global assignment', spam)
scope_test()
# 람다함수 시리즈 3개 map, filter, reduce
arr = [1, 2, 3, 4, 5]
brr = map(lambda x: x ** 2, arr)
print(brr)
crr = list(brr)
print(crr)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
brr = filter(lambda x: x % 3 == 0, arr) # 조건이 맞는지 필터링
print(brr)
for item in brr:
print(item, end=' ')
def oneto100():
sum = 0
for i in range(1, 101):
sum += i
return sum
print(oneto100())
# import numpy as np
# print(np.sum([x for x in range(1,101)]))
print(divmod(7, 3)) # 몫 과 나머지
print(eval('1+2')) # 문자열 수식처리
print(eval("'hi'+'a'"))
print(eval('divmod(4, 3)'))
my_list = ['apple', 'banana']
for index, value in enumerate(my_list, 1): # 색인부여 (,시작번호)
print(index, value)
actor = ['정우성', '나나'] # zip
gender = ['여', '여']
for i, j in zip(actor, gender):
print(i, '-', j)
actor = [('나나', '정우성'), ('여', '남')]
a, b = zip(*actor)
print(a, b)
print('-10 :', abs(-10))
result = divmod(10, 5)
print(result, type(result))
import math
print(math.ceil(5.1)) #올림
print(math.ceil(8.999))
print(math.floor(3.874)) #내림
print(math.floor(-25.5))
print(math.pi)
data = '5*9'
print(data)
result = eval(data)
print(data, '=', result)
print('최대값', max([34,50,100,1,20]))
print('최소값', min([34,50,100,1,20]))
aList = [78,90,80,50]
bList = [8,100,34,60]
newl = aList + bList
print('최대값', max(newl))
print('최소값', min(newl))
my_list = ['바나나','사과','수박','포도']
for i,v in enumerate(my_list,1) :
print(v,i)
result = list(enumerate(my_list,1))
print(result)
print(result[0])
str1 = '가나다'
str2 = '1234'
print(str1.isalpha())
print(str1.isdigit())
print(str2.isalpha())
print(str2.isdigit())
result_list = []
while 1 :
if len(result_list) == 5 :
print(result_list)
break
else :
data = input('입력')
if data.isdigit() :
result_list.append(data)
else :
print('숫자만 입력하세요')
<file_sep># 클래스
# class 클래스명대문자(부모클래스)
# 인스턴스 == 객체
# 객체(Object) = 속성(Attribute) + 기능(Method)
class Square:
alpha = 5
def __init__(self,width = 0,height= 0) : #self 는 빼고 계산, 클래스에서 정의된 변수
self.width = width
self.height = height #인스턴스 멤버 변수
self.__pwidth = width #바깥에서 접근 못하게
self.__pheight = height #private __
self._ptheight = height #protected _
def calcArea(self):
return self.height * self.width
def test(self):
return self.__pheight*self.__pwidth
def get_second(self):
return self.__second
def set_second(self, value):
self.__second = value
print(type(Square))
sq0 = Square()
sq1 = Square(5, 10) #Square 타입의 객체를 sq1로 생성
sq2 = Square(6, 20)
sq2.width = 30
sq2.height = 30
sq2.__pwidth = 10
sq2.__pheight = 10
print(Square.calcArea(sq2)) #클래스 이름으로 호출
print(Square.test(sq2)) #밖에서 주면 안바뀜
sq0.alpha = 44
print(sq1.alpha)
print(sq0.alpha)
a = Square(5,7)
print(a.get_second, a.height)
# sq1.__init__() #생성자
# sq1.__delattr__() #소멸자
# sq1.__dict__ #경로
# self : 인스턴스 변수, 인스턴스 매써드
#속성 @property --> private 변수를 만들 었을 때 씀 ///////get
# @price.setter ////////set
# @property
# def price(self):
# return self_price
# @price.setter
# def price(self, value):
# self_price = value
# def get_price(self):
# return self_price
# def set_price(self,value):
# self_price = value
#price = property(get_price, set_price)
#다중상속
# class 클래스이름(부모클래스1, 부모클래스2)<file_sep>from flask import Flask, render_template, request, current_app
import os
from werkzeug.utils import secure_filename
from flask import send_from_directory, send_file
from flask import flash
#파일 업로드 폴더 지정하기
UPLOAD_FOLDER = 'uploads' #절대경로로 준다.
#업로드 허용 가능한 파일 확장자
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'csv'])
#플라스크 객체 만들기
app = Flask(__name__)
app.secret_key = "<KEY>"
#설정파일에 저장하기
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#업로드 용량 제한
app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024*100 #업로드 최대크기-20M
#파일 업로드 html 랜더링
@app.route("/")
def index():
return render_template("upload.html")
#파일 확장자 사용 가능 여부
def allowed_file(filename):
print(filename)
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# s = 'one:two:three:four'
# s.split(':', 2)
# ['one', 'two', 'three:four']
# s.rsplit(':', 1)
# ['one:two:three', 'four']
#파일 전송하기
@app.route("/file/save", methods=['post'])
def file_upload():
file = request.files['upload'] #files로 받아야 한다. get- args, post - form, file - files로 받는다.
if file.filename == '':
flash('No selected file')
return "file 을 선택하지 않았습니다"
#파일을 선택했고, 확장자가 업로드를 허용한다면
if file and allowed_file(file.filename):
#filename = secure_filename(file.filename)
filename = file.filename
sfilename = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'], filename)
app.logger.debug(sfilename)
file.save(sfilename)
return filename+" 업로드 성공"
else:
print(file.filename)
@app.route('/download/<filename>')
def download(filename):
uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
app.logger.debug(filename)
return send_from_directory(directory=uploads, filename=filename)
'''
sfilename = os.path.join(uploads, filename)
ext = '.' in filename and filename.rsplit('.', 1)[1].lower()
file_mimeType = 'image/jpeg'
if ext in ('pdf'):
file_mimeType = 'application/pdf'
elif ext in ('csv'):
file_mimeType = 'text/csv'
elif ext in ('txt'):
file_mimeType = 'text/plain'
return send_file(sfilename,
mimetype=file_mimeType,
attachment_filename=filename, # 다운받아지는 파일 이름.
as_attachment=True)
'''
if __name__ == "__main__":
app.debug = True #서버 자동 재시작
app.run(host='127.0.0.1', port=8000)<file_sep>from flask import Flask, render_template
from day16_flask.blue1 import blue100
from day16_flask.blue2 import blue200
app = Flask(__name__, template_folder='templates')
app.register_blueprint(blue100)
app.register_blueprint(blue200)
@app.route('/')
def index() :
return 'index page'<file_sep>import pymysql
conn = pymysql.connect(host = 'localhost',
port = 3306,
user = 'root',
passwd = '<PASSWORD>',
db = 'pyMysql_db',
charset = 'utf8')
curs = conn.cursor() # 튜플커서
while 1 :
sel = input('1.목록 2.추가 3.수정 4.삭제 0.종료')
if sel == '1':
sql = 'select * from member'
curs.execute(sql)
rows = curs.fetchall()
for row in rows:
print(row[0], row[1], row[2], row[3])
print('-'*50)
elif sel == '2':
sql = 'insert into member(userid, pwd, name, email, regdate) values(%s, %s, %s, %s, now())'
userid = input('id :')
name = input('name :')
email = input('email :')
curs.execute(sql, (userid, '1234', name, email))
conn.commit()
elif sel == '3':
sql = 'update member set email = %s where userid = %s'
userid = input('id :')
email = input('email :')
curs.execute(sql, (email, userid))
conn.commit()
print('-' * 50)
elif sel == '4':
sql = 'delete from memeber where userid = %s'
userid = input('id :')
curs.execute(sql, userid)
conn.commit()
print('-' * 50)
elif sel == '0':
conn.close()
break
<file_sep># 모듈 import, form 모듈 import 클래스
# 표준 모듈. 외부 모듈, 사용자 정의 모듈
class FourCalc :
def __init__(self, num1 = None, num2 = None):
self.first = num1
self.second = num2
def add(self) :
return self.first + self.second
def sub(self) :
return self.first - self.second
def mul(self) :
return self.first * self.second
def div(self) :
return self.first / self.second
class MoreFourCalc(FourCalc) :
add_num = 10
@classmethod
def setPI(cls):
pass
@staticmethod
def setPI():
pass
def pow(self):
return self.first**self.second
def div(self) :
if self.second == 0:
return 0
else : return self.first / self.second
# 사용자 정의 모듈
# 테스트 해보기
if __name__ == "__main__" : #이 자체를 실행한 경우만 들어감, 다른데서 import할 때는 실행 안 됨
a = FourCalc(5, 7)
print(a.add(), a.sub(), a.mul(), a.div())
b = FourCalc(10, 5)
print(b.add(), b.sub(), b.mul(), b.div())
# c = FourCalc(5, 0)
# print(c.div())
#
ch_a = MoreFourCalc(10, 2)
print(ch_a.add(), ch_a.sub(), ch_a.mul())
print(ch_a.div(), ch_a.pow())
ch_b = MoreFourCalc(8, 2)
print(MoreFourCalc.add_num,id(MoreFourCalc.add_num))
print(ch_a.add_num,id(ch_a.add_num))
print(ch_b.add_num, id(ch_b.add_num))
#MoreFourCalc.add_num = 20
ch_a.add_num = 20 # 객체 명으로 클래스 접근 x
print(MoreFourCalc.add_num,id(MoreFourCalc.add_num))
print(ch_a.add_num,id(ch_a.add_num))
print(ch_b.add_num, id(ch_b.add_num))
import sys
# 현재 문서 경로가 표시
print(sys.argv)
print(sys.path) #list 로 줌, sys.path.append() 로 찾을 수 있음
#sys.exit()
print(sys.version)
print(sys.version_info)
print(dir(sys))
import math
# 수학 함수
print(math.pi)
# 프로그램 시작할 때 넘기고 싶을 때 사용
print('명령줄 인수 체크하기!!') # 터미널에서 넘기기 /python day06.py 12 34 abc 가나다 or run -> configuration
for n in sys.argv:
print(n)
#print('\n\n파이썬의 sys.path 디렉토리', sys.path)
import os
print(os.name)
# 디렉토리 정보
print(os.getcwd())
print(os.listdir())
if not os.path.isdir('test'):
os.mkdir('test')
elif os.path.exists('test'):
os.rmdir('test')
from urllib import request
target = request.urlopen('http://google.com')
output = target.read()
print(output)
from datetime import datetime
now = datetime.now()
print(now.year, '년')
print(now.month, '월')
print(now.day, '일')
import glob
print(glob.glob('*.*'))
print(glob.glob('C:\Temp\*.txt'))
import webbrowser
# webbrowser.open('http://google.co.kr')
foodList = [('갈비만두',4000), ('김치만두', 3000), ('물만두', 2000)]
for i in zip(*foodList): # 쪼갬
print(i)
# pyc 파일 : 컴파일된 파이썬 바이너리 파일
# 모듈을 호출할 때 빠르게 호출 하기 위해
#-----------------------------------------------------------------#
# 패키지 pakage : 모듈의 묶음
# 라이브러리리
# 에러처리, 예외처리
class InputValueError(Exception): # 만들어도 되고 안만들어도 되고
def __init__(self, msg='입력값 오류입니다'):
self.msg = msg
def __str__(self):
return self.msg
from random import randint
n = randint(1,100)
print(n)
while 1 :
ans = input('num : ?, Q (to exit)' )
if ans.upper() == 'Q':
break
try:
if not 0 < int(ans) < 101:
raise Exception('1~100 사이의 숫자를 입력하세요') #그냥 간단하게 이렇게 해도됨
# raise InputValueError('1~100 사이의 숫자를 입력하세요')
ians = int(ans)
if n == ians :
print('correct')
break
elif n > ians : print('up')
else : print('down')
except ValueError :
print('숫자입력!!')
except Exception as err :
print(err)
<file_sep>import sys
mlist = []
sum = 0
for n in sys.argv:
mlist.append(n)
for i in mlist[1:]:
sum += int(i)
print(sum)
<file_sep># 파이썬 excel, csv 읽기
import csv
with open('./csv/data/data1.csv', 'r') as f :
reader = csv.reader(f)
next(reader) #헤더를 스킵한다
print(reader)
print(type(reader))
print(dir(reader))
print()
for c in reader :
print(c)
# 예제 2
with open('./csv/data/data2.csv', 'r') as f :
reader = csv.reader(f, delimiter='|') #구분자 선택한다 default : ,
next(reader) #헤더를 스킵한다
print(reader)
print(type(reader))
print(dir(reader))
print()
for c in reader :
print(c)
# 예제 3 (Dict 변환)
with open('./csv/data/data1.csv', 'r') as f :
reader = csv.DictReader(f) #구분자 선택한다 default : ,
next(reader) #헤더를 스킵한다
print(reader)
print(type(reader))
print(dir(reader))
print()
for c in reader :
for k, v in c.items():
print(k, v)
print('-------')
# 예제 4
# 리스트 데이터를 csv 파일에 저장
w = [[1, 2 ,3],
[4, 5 ,6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]]
with open('./csv/data/out_data1.csv', 'w') as f :
wt = csv.writer(f)
print(dir(wt))
print(type(wt))
for v in w:
wt.writerow(v)
with open('./csv/data/out_data2.csv', 'w', newline = '') as f : #default \n 이므로
wt = csv.writer(f)
wt.writerows(w)<file_sep>from flask import Flask
def create_app():
app = Flask(__name__)
app.secret_key = '<KEY>'
from . import auth
app.register_blueprint(auth.bp)
from . import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
#app.add_url_rule('/', view_func=blog.index, methods=['GET'])
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app<file_sep># 파이썬 흐름제어(제어문)
# 1 ~ 5 문제 if 구문 사용
# 1. 아래 딕셔너리에서 '가을'에 해당하는 과일을 출력하세요.
q1 = {"봄": "딸기", "여름": "토마토", "가을": "사과"}
for key in q1:
if key == '가을':
print(q1[key])
print([q1[s] for s in q1 if s == '가을'])
print(''.join([q1[s] for s in q1 if s == '가을']))
# 2. 아래 딕셔너리에서 '사과'가 포함되었는지 확인하세요.(키 또는 값 모두 확인)
q2 = {"봄": "딸기", "여름": "토마토", "가을": "사과"}
for key, val in q2.items():
if key == '사과' or val == '사과':
print('있음')
break
else : print('없음')
# 3. 다음 점수 구간에 맞게 학점을 출력하세요.
# 81 ~ 100 : A학점
# 61 ~ 80 : B학점
# 41 ~ 60 : C학점
# 21 ~ 40 : D학점
# 0 ~ 20 : E학점
score = 75
if 80 < score : print('A 학점')
elif 60 < score : print('B 학점')
elif 40 < score : print('C 학점')
elif 20 < score : print('D 학점')
else : print('E 학점')
# 4. 다음 세 개의 숫자 중 가장 큰수를 출력하세요.(if문 사용) : 12, 6, 18
val = [12,6,18]
max = val[0]
for i in val :
if max < i : max = i
print(max)
# 5. 다음 주민등록 번호에서 7자리 숫자를 사용해서 남자, 여자를 판별하세요. (1,3 : 남자, 2,4 : 여자)
id = 1234567
flag = int(id/1000000)
if flag == 1 or 3 : print('남자')
elif flag == 2 or 4 : print('여자')
# 6 ~ 10 반복문 사용(while 또는 for)
# 6. 다음 리스트 중에서 '정' 글자를 제외하고 출력하세요.
q3 = ["갑", "을", "병", "정"]
for i in q3 :
if i == '정' : continue
print(i)
print(' '.join([s for s in q3 if s != '정']))
# 7. 1부터 100까지 자연수 중 '홀수'만 한 라인으로 출력 하세요.
for i in range(1,101) :
if i % 2 : print(i, end=' ')
print('')
print(' '.join([str(s) for s in range(1,101) if int(s%2) ]))
# 8. 아래 리스트 항목 중에서 5글자 이상의 단어만 출력하세요.
q4 = ["nice", "study", "python", "anaconda", "!"]
for i in q4:
if len(i) >= 5 : print(i)
print([s for s in q4 if len(s) >= 5])
# 9. 아래 리스트 항목 중에서 소문자만 출력하세요.
q5 = ["A", "b", "c", "D", "e", "F", "G", "h"]
for i in q5:
if ord(i) >= ord('a') : print(i)
# 10. 아래 리스트 항목 중에서 소문자는 대문자로 대문자는 소문자로 출력하세요.
q6 = ["A", "b", "c", "D", "e", "F", "G", "h"]
for i in q6 :
if ord(i) < ord('Z') : print(i.lower(), end=' ')
else : print(i.upper(), end=' ')
for i in q6 :
if i.islower() : print(i.upper(), end=' ')
else : print(i.lower(), end=' ')
print([s.upper() if s.islower() else s.lower() for s in q6])<file_sep>import sqlite3
conn = sqlite3.connect('database_new.db')
c = conn.cursor()
c.execute('SELECT * FROM users')
print('One -> \n', c.fetchone())
print('Three -> \n', c.fetchmany(size = 3))
print('All -> \n', c.fetchall())
print()
for row in c.fetchall():
print('retrieve2 > ', row) #조회 x
for row in c.execute('SELECT * FROM users ORDER BY id DESC'):
print('retrieve3 > ', row)
param1 = (12,)
c.execute('SELECT * FROM users WHERE id =?', param1)
print('param1',c.fetchone())
print('param1',c.fetchall())
param2 = 13
c.execute("SELECT * FROM users WHERE id='%s'"% param2)
print('param2',c.fetchone())
print('param2',c.fetchall())
c.execute("SELECT * FROM users WHERE id= :Id", {"Id": 19}) # 딕셔너리로 주기
print('param3',c.fetchone())
print('param3',c.fetchall())
param4 = (12,14)
c.execute("SELECT * FROM users WHERE id IN(?,?)", param4)
print('param4',c.fetchone())
print('param4',c.fetchall())
with conn:
# Dump 출력(데이터베이스 백업 시 중요)
# SQL 텍스트 형식으로 데이터베이스를 덤프
with open('dump.sql', 'w') as f:
for line in conn.iterdump():
f.write('%s\n' % line)
print('Dump Print Complete.')
# UPDATE 테이블명 SET 컬럼명=새 값 where<file_sep>class Car:
'''Parent Class'''
def __init__(self, tp, color):
self.type = tp
self.color = color
def show(self):
return 'Car Class "Show" Method!'
class BmwCar(Car):
'''Sub Class'''
def __init__(self, car_name, tp, color):
super().__init__(tp,color)
self.car_name = car_name
def show_model(self) -> None:
return 'Your Car Name : %s' % self.car_name
class BenzCar(Car):
'''Sub Class'''
def __init__(self, car_name, tp, color):
super().__init__(tp, color)
self.car_name = car_name
def show(self): # Override
super().show()
return 'Car Info : %s %s %s' % (self.car_name, self.type, self.color)
def show_model(self) -> None:
return 'Your Car Name : %s' % self.car_name
model1 = BmwCar('520d', 'sedan', 'red')
print(model1.color)
print(model1.type)
print(model1.car_name)
print(model1.show())
print(model1.show_model())
# Method Overriding
model2 = BenzCar('220d', 'suv', 'black')
print(model2.show())
#Parent Method Call
model3 = BenzCar('350s', 'sedan', 'silver')
print(model3.show())
#Inheritance Info
print('Inheritance Info : ', BmwCar.mro())
print('Inheritance Info : ', BenzCar.mro())
<file_sep>from flask import Flask, url_for, render_template, request, redirect, session
from flask_sqlalchemy import SQLAlchemy
from instagram import getfollowedby, getname
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
""" Create user table"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(80))
def __init__(self, username, password):
self.username = username
self.password = <PASSWORD>
@app.route('/', methods=['GET', 'POST'])
def index():
""" Session control"""
print(request.method)
if not session.get('logged_in'):
return render_template('index.html')
else:
if request.method == 'POST':
username = getname(request.form['username'])
cnt, data = getfollowedby(username)
return render_template('index.html', cnt=cnt, data=data)
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
"""Login Form"""
if request.method == 'GET':
return render_template('login.html')
else:
name = request.form['username']
passw = request.form['password']
try:
data = User.query.filter_by(username=name, password=<PASSWORD>w).first()
if data is not None:
session['logged_in'] = True
return redirect(url_for('index'))
else:
return redirect(url_for('login'))
except:
return "로그인 처리 중 오류가 발생하였습니다."
@app.route('/register/', methods=['GET', 'POST'])
def register():
"""Register Form"""
if request.method == 'POST':
new_user = User(username=request.form['username'], password=request.form['password'])
db.session.add(new_user)
db.session.commit()
return render_template('login.html')
return render_template('register.html')
@app.route("/logout")
def logout():
"""Logout Form"""
session['logged_in'] = False
return redirect(url_for('index'))
@app.route("/about")
def about():
"""about Form"""
return render_template('about.html')
if __name__ == '__main__':
app.debug = True
db.create_all()
app.secret_key = "123"
app.run(host='127.0.0.1')<file_sep>from flask import Flask
app = Flask(__name__)
@app.route('/')
def helloword():
return "<h1>Hello World</h1>"
@app.route('/sleep')
def NoSleep():
return "<h1>주무시지 마시오</h1>"
if __name__=="__main__":
app.run()<file_sep>from flask import Flask, render_template, request
app = Flask(__name__, template_folder='view')
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
#return render_template('index.html', posts=posts)
@app.route('/about')
def about():
return render_template('about.html', title='About')
app.run(host='0.0.0.0', port=80)
<file_sep># flask 모듈을 포함시킨다.
from flask import Flask, render_template, request
# flask 서버 객체를 생성한다.
app = Flask(__name__, template_folder='view')
# 주소만 입력했을 경우 호출되는 함수
@app.route("/")
def index() :
# index.html 파일에서 html 데이터를 읽어온다.
html = render_template('index.html')
return html
# 주소 뒤에 second라고 입력했을 경우 호출되는 함수
# 요청 방식 : get, post 등등
# post : form 태그의 method가 post인 경우
# get : 주소를 직접 입력했을 때, a 태그를 클릭 했을 때
# form 태그의 method가 없거나 get인 경우
@app.route("/second", methods=['GET', 'POST'])
def second() :
# 요청 방식
print(f'요청방식 : {request.method}')
# if request.method == 'POST':
html = render_template('second.html')
return html
# 서버 가동
app.run(host='0.0.0.0', port=80)
<file_sep># 1. a, b, c, d, e를 저장하는 튜플을 만들고 첫 번째 튜플값과 마지막 번째 튜플값을 출력하세요.
myTuple = ('a','b','c','d','e')
print(myTuple[0],myTuple[-1])
# 2. 다음 코드를 작성해서 실행해보고 에러가 나는 이유를 설명하세요.
# tupledata = ('dave', 'fun-coding', 'endless')
# tupledata[0] = 'david'
#튜플은 immutable 이기 때문에 수정할 수 없다.
# 3. 다음 튜플 데이터를 리스트 데이터로 변환한 후에 'fun-coding4' 데이터를 마지막에 추가하고,
# 다시 튜플 데이터로 변환하세요.
tupledata = ('fun-coding1', 'fun-coding2', 'fun-coding3')
temp = list(tupledata)
temp.append('fun-coding4')
tupledata = tuple(temp)
print(tupledata)
# 4. 비어 있는 튜플, 리스트, 딕셔너리 변수를 하나씩 각각 만드세요.
mt = ()
ml = []
md = {}
# 5. 다음 actor_info 딕셔너리 변수를 만들고, 홈페이지, 배우 이름, 최근 출연 영화 갯수를 다음과 같이 출력하세요
actor_info = {'actor_details': {'생년월일': '1971-03-01',
'성별': '남',
'직업': '배우',
'홈페이지': 'https://www.instagram.com/madongseok'},
'actor_name': '마동석',
'actor_rate': 59361,
'date': '2017-10',
'movie_list': ['범죄도시', '부라더', '부산행']}
#배우 이름: 마동석
#홈페이지: https://www.instagram.com/madongseok
#출연 영화 갯수: 3
print('배우이름 : ',actor_info.get('actor_name'))
print('홈페이지 : ',actor_info.get('actor_details').get('홈페이지'))
print('출연 영화 갯수 : ',len(actor_info.get('movie_list')))
# 6. 다음 리스트에서 "Apple" 항목만 삭제하세요. : ["Banana", "Apple", "Orange"]
mlist = ["Banana", "Apple", "Orange"]
mlist.remove('Apple')
print(mlist)
# 7. 다음 튜플을 리스트로 변환하세요. : (1,2,3,4)
mtuple = (1,2,3,4)
mlist = list(mtuple)
print(mlist)
# 8. 다음 항목을 딕셔너리(dict)으로 선언해보세요. : <성인 - 100000 , 청소년 - 70000 , 아동 - 30000>
mdict = {}
mdict['성인'] = 100000
mdict['청소년'] = 70000
mdict['아동'] = 30000
print(mdict,type(mdict))
# 9. 8번 에서 선언한 dict 항목에 <소아 - 0> 항목을 추가해보세요.
mdict['소아'] = '0'
print(mdict,type(mdict))
# 10. 8번에서 선언한 딕셔너리(dict)에서 Key 항목만 출력해보세요.
print(list(mdict.keys()))
# 11. 8번에서 선언한 딕셔너리(dict)에서 value 항목만 출력해보세요.
print(list(mdict.values()))
#연습문제####
#3,4
pin = '881120-1068234'
yyyymmdd = pin[:6]
num = pin[7:]
print(yyyymmdd,num,pin[7])
#5
a='a:b:c:d'
print(a.replace(':','#'))
#6
a=[1,3,5,4,2]
a.sort()
print(a)
a.reverse()
print(a)
#7
a = ['Life', 'is', 'too', 'short']
result = ' '.join(a)
print(result)
#8
a = (1, 2, 3)
a = a + (4,)
print(a)
#9
a = dict()
#a[[1]] = 'python'
print(a)
#10
a = {'A':90, 'B':80, 'C': 70}
result = a.pop('B')
print(a,'\n', result)
#11
a = [1,1,1,2,2,3,3,3,4,4,5]
aSet = set(a)
b = list(aSet)
print(b)
#12
a = b = [1, 2, 3]
a[1] = 4
print(b)<file_sep>from flask import Flask, render_template, request
import database as db
app = Flask(__name__, template_folder='view')
@app.route('/')
def index() :
html = render_template('index.html')
return html
@app.route('/student_list')
def student_list() :
# 검색어를 추출한다.
stu_name = request.args.get('stu_name')
# 학생 정보 리스트를 가져온다.
stu_list = db.get_student_list(stu_name)
html = render_template('student_list.html', data_list=stu_list)
return html
@app.route('/show_point')
def show_point() :
html = render_template('show_point.html')
return html
@app.route('/student_info', methods=['get', 'post'])
def student_info() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
# 학생 데이터를 가져온다.
result_dic = db.get_student_info(stu_idx)
# 학생 점수를 가져온다.
result_list = db.get_point(stu_idx)
html = render_template('student_info.html', data_dic=result_dic, data_list=result_list)
return html
@app.route('/add_student')
def add_student() :
html = render_template('add_student.html')
return html
@app.route('/add_point')
def add_point() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('add_point.html', data_dic=temp_dic)
return html
@app.route('/add_student_pro', methods=['post'])
def add_student_pro() :
# 파라미터 데이터 추출한다.
stu_name = request.form['stu_name']
stu_age = request.form['stu_age']
stu_addr = request.form['stu_addr']
# print(f'{stu_name} {stu_age} {stu_addr}')
# 저장한다.
idx = db.add_student(stu_name, stu_age, stu_addr)
result_dic = { 'stu_idx' : idx}
html = render_template('add_student_pro.html', data_dic=result_dic)
return html
@app.route('/add_point_pro', methods=['post'])
def add_point_pro() :
# 파라미터 추출
point_stu_grade = request.form['point_stu_grade']
point_stu_kor = request.form['point_stu_kor']
point_stu_idx = request.form['point_stu_idx']
# 점수 정보 저장
db.add_point(point_stu_idx, point_stu_grade, point_stu_kor)
temp_dic = {}
temp_dic['stu_idx'] = point_stu_idx
html = render_template('add_point_pro.html', data_dic=temp_dic)
return html
app.run(host='0.0.0.0', port=8080)
<file_sep>class TestClass:
memberCnt = 0
age = 10 # 클래스 변수 age
def __init__(self, *args, **kwargs): # 생성자 함수 정의 / name과 phone의 기본값을 주어야함
if len(args) == 2:
self.name = args[0]
self.phone = args[1]
else :
self.name = kwargs.get("name","홍길동") #name 이 오면 주고 안넘어오면 홍길동을 주자
self.phone = kwargs.get("phone", "010-1111")
TestClass.memberCnt += 1 # 생성시 카운트 늘리기
print('Instance created')
def showInfo(self):
return str(self) # str함수 부르기
# return self.__str__()
def __str__(self): # 인스턴스 값이 보였으면 하는 형변환
return "name:{0} phone:{1} age:{2}".format(self.name, self.phone, self.age)
# 소수점 표현 {0(인덱스순서):6(6자리중에서).3f(소수셋째자리까지)}
def __del__(self): # 인스턴스 값 삭제
TestClass.memberCnt -= 1 #삭제시 카운트 --
print('Instance removed')
print(TestClass.age)
t1 = TestClass()
t2 = TestClass('홍길동', '010-1111-1111')
t3 = TestClass(name = '김개동', phone = '090-111') #딕셔너리로
print(id(t1), t1.__dict__)
print(id(t2), t2.__dict__)
print(t1.showInfo())
print(str(t2))
print(TestClass.memberCnt)
t2.age = 25
print(id(t2), t2.__dict__)
print(str(t2))
del t2
print(TestClass.memberCnt)
print('end')
<file_sep>from flask import Flask, render_template, request
app = Flask(__name__, template_folder='view')
@app.route('/')
def index() :
html = render_template('index.html')
return html
@app.route('/test1')
def test1() :
return 'test1'
@app.route('/test1/sub1')
def test1_sub1() :
return 'test1 sub1'
@app.route('/test1/sub2')
def test1_sub2() :
return 'test1 sub2'
@app.route('/test2/<data1>')
def test2_data1(data1) :
return 'test2 data1 : {0}'.format(data1)
@app.route('/test2/<data1>/<data2>')
def test2_data1_data2(data1, data2) :
return 'test2 data1 : {0}, data2 : {1}'.format(data1, data2)
@app.route('/test3')
@app.route('/test4')
def test3_or_test4() :
return 'test3 or test4'
@app.route('/test5', defaults={'data1' : 1, 'data2' : 2})
@app.route('/test5/<data1>', defaults={'data2' : 20})
@app.route('/test5/<data1>/<data2>')
def test5(data1, data2) :
return 'test5 data1 : {0}, data2 : {0}'.format(data1, data2)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/user/<username>/<int:age>')
def show_user_profile_age(username, age):
return 'Username %s, 나이 %d' % (username, age)
app.run(host='0.0.0.0', port=80)
<file_sep>import json
from urllib.request import urlopen
from urllib.parse import quote
import re
import pandas as pd
import folium
url_base = 'http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureSidoLIst'
service_key = <KEY>'
page = '&numOfRows=10&pageNo=1'
sidoname = '&sidoName=' + quote('인천')
daily = '&searchCondition=DAILY'
url = url_base + service_key + page + sidoname + daily
xml = urlopen(url)
data = xml.read().decode('utf8')
goo = re.findall('<cityName>.+</cityName>', data)
list_a = []
for line in goo:
line = line.replace('<cityName>', '')
line = line.replace('</cityName>', '')
list_a.append(line)
pm10 = re.findall('<pm10Value>.+</pm10Value>', data)
list_b = []
for line in pm10:
line = line.replace('<pm10Value>', '')
line = line.replace('</pm10Value>', '')
list_b.append(line)
pm25 = re.findall('<pm25Value>.+</pm25Value>', data)
list_c = []
for line in pm25:
line = line.replace('<pm25Value>', '')
line = line.replace('</pm25Value>', '')
list_c.append(line)
so2 = re.findall('<so2Value>.+</so2Value>', data)
list_d = []
for line in so2:
line = line.replace('<so2Value>', '')
line = line.replace('</so2Value>', '')
list_d.append(line)
co = re.findall('<coValue>.+</coValue>', data)
list_e = []
for line in co:
line = line.replace('<coValue>', '')
line = line.replace('</coValue>', '')
list_e.append(line)
o3 = re.findall('<o3Value>.+</o3Value>', data)
list_f = []
for line in o3:
line = line.replace('<o3Value>', '')
line = line.replace('</o3Value>', '')
list_f.append(line)
no2 = re.findall('<no2Value>.+</no2Value>', data)
list_g = []
for line in no2:
line = line.replace('<no2Value>', '')
line = line.replace('</no2Value>', '')
list_g.append(line)
dtime = re.findall('<dataTime>.+</dataTime>', data)
list_h = []
for line in dtime:
line = line.replace('<dataTime>', '')
line = line.replace('</dataTime>', '')
list_h.append(line)
dataset = {'구': list_a, 'pm10': list_b, 'pm25': list_c, 'so2': list_d, 'co': list_e, 'o3': list_f, 'no2': list_g,
'dateTime': list_h}
df = pd.DataFrame(dataset)
df.drop(0, inplace=True)
df.drop(9, inplace=True)
df.set_index('구', inplace=True)
print(df)
for i in range(0, 8):
for j in range(0, 6):
if df.iloc[i][j] == '-':
df.iloc[i][j] = 0
df.to_csv("static/dust.csv", encoding='utf-8', sep=',')
dff = pd.read_csv('static/dust.csv', thousands=',', encoding='utf-8')
dff.set_index('구', inplace=True)
geo_path = 'static/skorea-municipalities-2018-geo.json'
geo_json = json.load(open(geo_path, encoding='utf-8'))
map = folium.Map(location=[37.454441, 126.708096],
zoom_start=11, tiles='Mapbox Control Room')
map.choropleth(geo_data=geo_json,
data=dff['pm10'],
columns=[dff.index, dff['pm10']],
fill_color='PuBu',
key_on='feature.properties.name',
fill_opacity=1,
line_opacity=1,
highlight=True)
map.save('view/dust.html')
<file_sep>{% extends "layout.html" %}
{% block content %}
<div class="container">
<h3>학생 정보 보기</h3>
<hr/>
<h5>이름 : {{data_dic.stu_name}}</h5>
<h5>나이 : {{data_dic.stu_age}}살</h5>
<h5>주소 : {{data_dic.stu_addr}}</h5>
{% for dic in data_list %}
<h5>{{dic.point_stu_grade}}학년 : {{dic.point_stu_kor}}점</h5>
{% endfor %}
<h5><a href="add_point?stu_idx={{data_dic.stu_idx}}">점수 추가</a></h5>
<h5><a href="student_list">목록보기</a></h5>
</div>
{% endblock %}<file_sep>import time
from datetime import datetime, timedelta
timestamp_now = time.time() # 절대 시간
print(timestamp_now)
datetime_now = datetime.now() # 익숙한시간
print(datetime_now)
delta_datetime = timedelta(days = -30)
print(datetime_now + delta_datetime)
end_datetime = datetime_now + delta_datetime
print(end_datetime.timetuple())
end_timestamp = time.mktime(end_datetime.timetuple()) #datetime -> timestamp로
print(timestamp_now)
print(datetime.fromtimestamp(timestamp_now)) # timestamp -> 를 datetime 형식으로
print(end_timestamp)
import calendar
print(calendar.calendar(2019))
year2019 = calendar.calendar(2019)
print(type(year2019))
print(calendar.prmonth(2019,7))
print(calendar.prmonth(datetime_now.year,datetime_now.month))
print('\n\n오늘 요일 인덱스:\n\n')
print(calendar.weekday(2019,7,11))
weekDay = ['월','화','수','목','금','토','일']
print('오늘은 {} 입니다'.format(weekDay[calendar.weekday(2019,7,11)]))
print('크리스마스 {} 입니다'.format(weekDay[calendar.weekday(2019,12,25)]))<file_sep>-- 퇴사 관련 필드가 정의된 것은 없지만, 종료일자가 있는 테이블의 데이터를 살펴보면 '9999-01-01'인 데이터가 있다.
-- 의미상 현재 근무 중인 직원은 급여나 현재 근무 부서, 업무의 종료일자가 없을 것이다.
-- 종료일자가 없다는 의미를 '9999-01-01'로 사용한 것 같다.
SELECT COUNT(*) FROM SALARIES WHERE TO_DATE='9999-01-01';
SELECT COUNT(*) FROM TITLES WHERE TO_DATE='9999-01-01';
SELECT COUNT(*) FROM DEPT_EMP WHERE TO_DATE='9999-01-01';
-- 1. 현재 근무중인 직원들의 업무별 직원수를 구하시오.
select distinct title, count(*) from titles group by title;
-- 2. 현재 근무중인 직원들의 평균 급여를 구하시오.
select emp_no, avg(salary) from salaries group by emp_no;
-- 3. 부서별 현재 인원수를 구하시오.
select distinct dept_no, count(*) from dept_emp group by dept_no;
-- 4. 부서별 현재 인원수를 인원수가 많은 부서부터 출력하시오
select distinct dept_no, count(*) from dept_emp WHERE TO_DATE='9999-01-01' group by dept_no order by count(*) desc;
-- 5. 부서 이동이 많은 직원순으로 리스트를 출력하시오 (퇴직자 포함)
select emp_no, count(*) cnt
from dept_emp
group by emp_no
having count(*)>1
order by cnt desc;
-- 6. 부서별 현재 인원수가 15,000명 이상인 부서를 구하시오.
-- 7. 부서별 현재 인원수가 가장 많은 상위 5개 부서를 구하시오
<file_sep>DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(50) NOT NULL,
password varchar(200) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE post (
id int(11) NOT NULL AUTO_INCREMENT,
author_id int(11) NOT NULL,
created timestamp NOT NULL DEFAULT current_timestamp(),
title varchar(50) NOT NULL,
body TEXT NOT NULL,
FOREIGN KEY (author_id) REFERENCES user (id),
PRIMARY KEY (id)
);<file_sep># 조건문 반복문
# 논리 연산자 and, or, not
# if, if else, if elif else
# : 로부터 같은 레벨은 같은 들여쓰기
# IndentationError : 들여쓰기 에러 , shift + tab 땡겨오기
# if ~ in [], if ~ not in []
# :뒤에 아무것도 없으면안됨, pass 사용 이유, 수도코드
# !가 아니라 not, ! 써도 되는데..?
a = 1
b = 10
if a > b :
print('a는 b보다 크다')
else :
print('a는 b보다 작다')
money = 1
if money : print('택시를 타고')
print('가자')
#data = int(input('정수를 입력 하세요'))
data = 1
if data > 0 : print('양수')
elif data <0 : print('음수')
else : print('0')
# age = int(input('나이 입력 : '))
age = 26
if age > 19 : print('성인')
elif 17 <= age : print('고등학생')
elif 14 <= age : print('중학생')
elif 8 <= age : print('초등학생')
else : print('유아')
num = 2
if num % 2 : print('홀')
else : print ('짝')
# k = int(input('키를 입력하세요 : '))
# w = int(input('무게를 입력하세요 : '))
k = 170
w = 60
bmi = (w/((k/100)**2))
print('bmi = %.2f'% bmi)
if 35 < bmi : print('고도비만')
elif 30 <= bmi : print('중고도비만')
elif 25 <= bmi : print('경도비만')
elif 23 <= bmi : print('과체중')
elif 18.5 <= bmi : print('정상')
else : print('저체중')
animal = ['원', '닭', '개','돼지','쥐', '소', '범', '토', '용', '뱀', '말', '양']
#year = int(input('몇년생?'))
year = 1994
print ('당신은 {0}년도에 태어난 {1} 띠 이시군요'. format(year, animal[year % 12]))
#문자열에서 in과 not in을 사용 할 수 있다
e = {'name' : 'kim', 'city': 'seoul', 'grade' : 'b'} #딕셔너리는 암말없으면 키로 비교
print('name' in e)
print('seoul' in e.values())
#score = float(input('')) #float 형변환
score = 4.5
if score == 4.5 : print('신')
# 시간은 문자열과 datetime이 다르다
# format 이 중요하다
import datetime
now = datetime.datetime.now()
print(' now = ',now)
print(' 년도 = ',now.year)
print(' 월 = ',now.month)
print(' 일 = ',now.day)
print(' 일 = ',now.date())
print(' 시 = ',now.hour)
print(' 오늘은 {} 년 {} 월 {} 일 입니다.'. format(now.year, now.month, now.day))
print(' 작성일자 {}'.format(now.strftime('%Y-%m-%d %H:%M:%S'))) #Y년 m월 d일, H시간 M분 S초
newdt = datetime.datetime.strptime('1994-07-15', '%Y-%m-%d')
print(newdt, now, type(newdt) , type(now))
print(now-newdt) #datetime 끼리 계산 가능
newd = datetime.timedelta(days=100) #miniutes, hours, weeks, years
print(now+newd)
# while, continue, break, ~비트 연산
i = 0
while i < 10 :
i += 1
if not i%2 : continue
print(i)
sum = 0
i = 0
while i < 100 :
i += 1
if i % 5 > 0 : continue
sum += i
print(sum)
# for 변수 in (iterator 개체) :
sum = 0
for nemo in range(1,101) :
if not nemo % 5 :
sum += nemo
print(sum)
aa = [('a', 'b'), ('c', 'd'), ('e', 'f')]
for (i, j) in aa:
print(i+j)
for i in range(0,21,2):
if not i : pass
for i in range(2,10) :
for j in range(1,10) :
print('%d x %d = %2d'% (i ,j , i*j) ,end='\t')
print('')
for i in range(2,10) :
for j in range(1,10) :
print('{0}*{1}={2:2}'.format(i, j, i*j) ,end='\t')
print('')
print('')
for j in range(1,10) :
for i in range(2,10) :
print('%d x %d = %2d'% (i ,j , i*j) ,end='\t')
print('')
print('')
for k in range(1,4) :
for j in range(1,10) :
for i in range(3*k-1,3*k+2) :
print('%d x %d = %2d'% (i ,j , i*j) ,end='\t')
print('')
print('')
# for 문과 list 내포
myl = []
for num in range(1,6) :
myl.append(num*3)
print(myl)
mylist = [num*3 for num in range(1,6)]
print(mylist)
print([x*y for x in range(2,10) for y in range(1,10)]) #이중 for문 list 내포
gugu = [i*5 for i in range(1,100) if i%2 == 0] #for문 if 문 list 내포
print(gugu)
for i in range(1,6):
print('*'*i)
i = 0
while i < 5 :
i += 1
print('*' * i)
i = 0
sum = 0
while i < 50 :
i += 1
sum += i
print(sum)
#
# while 1 :
# ans = input('아무거나 입력, 종료시 x')
# if ans == 'x' or 'X':
# print('종료')
# break
#
# while 1 :
# ans = input('아무거나 입력, x 종료시 ')
# if ans == 'x'.upper():
# print('종료')
# break
#iterator 개체: range, reversed, enumerate, filter, map, zip
cnt = 1
for i in ['a','b','c'] :
print('요소 {} : {}'.format(cnt,i))
cnt += 1
myList = [50, 44, 100, 30, 1, 300, 500]
myList.sort()
myList.reverse()
print(myList[0])
myList = [50, 44, 100, 30, 1, 300, 500]
result = myList[0]
for i in myList:
if result < i:
result = i
print(i)
my_info = {'name' : 'Kim','age':33,'city':'Seoul'}
for key in my_info:
print(key, ':', my_info[key]) #키와 value
for key, val in my_info.items() :
print(key,':',val)
#for의 else
numbers = [14, 2, 33, 15, 38]
for num in numbers:
if num == 39:
print('found : 33!')
break
else:
print('not found : ', num)
else:
print('not found 39...') #for문이 break없이 정상 실행 됬을 때 이동
for num in numbers:
if num == 33:
print('found : 33!')
break
else:
print('not found : ', num)
else:
print('not found 39...') #for문이 break없이 정상 실행 됬을 때 이동
numbers =[]
for num in numbers:
if num == 33:
print('found : 33!')
break
else:
print('not found : ', num)
else:
print('not found 39...') #for문이 break없이 정상 실행 됬을 때 이동
a = 1.5
<file_sep>from fourcalc import FourCalc, MoreFourCalc #from 모듈 import 클래스이름
c1 = FourCalc(6.3)
print(c1.add())
print('c1', isinstance(c1, FourCalc))
ch_a = MoreFourCalc(10, 2)
print(ch_a.add(), ch_a.sub(), ch_a.mul())
print(ch_a.div(), ch_a.pow())
print('ch_a_자식', isinstance(ch_a, MoreFourCalc)) # 자식 --> 부모 가능
print('ch_a_부모', isinstance(ch_a, FourCalc)) # 자식 --> 자식 불가능
print('c1_자식', isinstance(c1, MoreFourCalc)) # 부모 --> 자식 불가능
# 다중상속, 인터페이스 없다<file_sep># with 구분을 사용해서 작성하세요
# 1. 50~100 사이의 난수 5개를 생성해서 score.txt 파일을 생성하세요.
import random
with open('data/score.txt', 'w', encoding='utf-8') as f :
for i in range(1,6) :
f.write(str(random.randint(50, 100)) + '\n')
# 2. score.txt 파일을 생성한 후 평균을 소숫점3자리까지 표현하세요.
# 95
# 78
# 92
# 89
# 100
# 66
with open('data/score.txt', 'r', encoding='utf-8') as f:
score = f.readlines() # 리스트로 온다
print(score)
sum = 0
for i in score :
sum += eval(i)
print('%.3f' % float(sum/len(score)))
# sum = 0
# num = data.split('\n')
# for i in range(1,5) :
# sum += int(num[i])
# print('%.3f' % float(sum/5))
# 3. 다음 소스 코드에서 클래스를 작성하여
# 게임 캐릭터의 능력치와 '베기'가 출력되게 만드세요.
class Knight():
def __init__(self, health, mana, armor):
self.health = health
self.mana = mana
self.armor = armor
def slash(self):
print('베기')
x = Knight(health=542.4, mana=210.3, armor=38)
print(x.health, x.mana, x.armor)
x.slash()
<file_sep>use shopdb;
SELECT * FROM membertbl;
create table indextbl(
first_name varchar(14),
last_name varchar(15),
hire_date date);
insert into indextbl
select first_name,last_name, hire_date
from employees.employees
limit 500;
select * from indextbl;
select * from indextbl where first_name = 'mary';
create index idx_indexTBL_firstname on indexTBL(first_name);
<file_sep>#연습문제 Q1
class Calculator:
def __init__(self):
self.value = 0
def add(self,val):
self.value += val
class UpgradeCalculator(Calculator):
def minus(self, val):
self.value -= val
cal = UpgradeCalculator()
cal.add(10)
cal.minus(7)
print(cal.value)
#Q2
class MaxLimitCalculator(Calculator):
def add(self,val):
self.value += val
if self.value > 100 : self.value = 100
cal = MaxLimitCalculator()
cal.add(50)
cal.add(60)
print(cal.value)
#Q3
print(all([1, 2, abs(-3)-3])) #0 이있으면 False
print(chr(ord('a')) == 'a')
#Q4
mlist = [1, -2, 3, -5, 8, -3]
result = filter(lambda x : x > 0, mlist)
print(list(result))
#Q5
print(hex(234))
print(int(hex(234), 16))
#Q6
arr = [1, 2, 3, 4]
brr = map(lambda x: x * 3, arr)
print(list(brr))
#Q7
mlist = [-8, 2, 7, 5 ,-3, 5 ,0 ,1]
print(max(mlist) + min(mlist))
#Q8
print(round(17/3,4))
#Q10
import os
if not os.path.isdir('C:\doit'):
os.mkdir('C:\doit')
os.chdir('C:\doit')
os.system('dir')
f = os.popen('dir')
print(f.read())
#Q11
import glob
print(glob.glob('C:\doit\*.py'))
#Q12
from datetime import datetime
now = datetime.now()
print(now.strftime('%Y/%m/%d %H:%M:%S'))
#Q13
import random
k = range(1, 45)
com = random.sample(k, 6)
print(com)<file_sep>class PropertyClass:
def __init__(self, tmp = -2, ref = 2):
if tmp > 0: tmp = -2
if ref < 0 : ref = 2
self.__tmp = tmp
self.__ref = ref
@property
def tmp(self):
return self.__tmp
@tmp.setter
def tmp(self, val):
if val < 0:
self.__tmp = val
else:
self.__tmp = -2
@property
def ref(self):
return self.__ref
@ref.setter
def ref(self , val):
if 1< val < 5:
self.__ref = val
else:
self.__ref = 2
def showInfo(self):
return '냉동실 온도는 {0} 도, 냉장실 온도는 {1} 도 입니다'.format(self.__tmp,self.__ref)
@classmethod
def sampleClassMethod(cls):
return 'ClassMethod'
@staticmethod #클래스 매써드랑 차이가 없다
def sampleStaticMethod():
return 'StaticMethod'
t1 = PropertyClass()
print(t1.showInfo())
t1.tmp = 10
print(t1.showInfo())
t1.tmp = -5
print(t1.showInfo())
t1.ref = 4
print(t1.showInfo())
t1.ref = -4
print(t1.showInfo())
#클래스 매서드는 클래스 이름으로 호출해라
print(PropertyClass.sampleClassMethod())
print(t1.sampleClassMethod()) #인스턴스로 불러도 호출됨
print(PropertyClass.sampleStaticMethod())
print(t1.sampleStaticMethod())<file_sep>class FourCalc :
def __init__(self, num1 = None, num2 = None):
self.first = num1
self.second = num2
def add(self) :
return self.first + self.second
def sub(self) :
return self.first - self.second
def mul(self) :
return self.first * self.second
def div(self) :
return self.first / self.second
class MoreFourCalc(FourCalc) :
add_num = 10
@classmethod
def setPI(cls):
pass
@staticmethod
def setPI():
pass
def pow(self):
return self.first**self.second
def div(self) :
if self.second == 0:
return 0
else : return self.first / self.second
if __name__ == "__main__" : #이 자체를 실행한 경우만 들어감, 다른데서 import할 때는 실행 안 됨
a = FourCalc(5, 7)
print(a.add(), a.sub(), a.mul(), a.div())
b = FourCalc(10, 5)
print(b.add(), b.sub(), b.mul(), b.div())
# c = FourCalc(5, 0)
# print(c.div())
#
ch_a = MoreFourCalc(10, 2)
print(ch_a.add(), ch_a.sub(), ch_a.mul())
print(ch_a.div(), ch_a.pow())
ch_b = MoreFourCalc(8, 2)
print(MoreFourCalc.add_num,id(MoreFourCalc.add_num))
print(ch_a.add_num,id(ch_a.add_num))
print(ch_b.add_num, id(ch_b.add_num))
#MoreFourCalc.add_num = 20
ch_a.add_num = 20 # 객체 명으로 클래스 접근 x
print(MoreFourCalc.add_num,id(MoreFourCalc.add_num))
print(ch_a.add_num,id(ch_a.add_num))
print(ch_b.add_num, id(ch_b.add_num))<file_sep># 파일 입출력
# input('Message')
# f = open('파일경로','파일접근모드', encoding='utf-8')
# f.write('데이터')
# f.close()
# 접근모드 r:읽기, w:쓰기 ,a:추가
f = open('data/test.txt','w',encoding='utf-8')
for i in range(1,11):
data = '%d번째 줄입니다.\n' % i
f.writelines(data) # line들의 list를 넘긴다
f.close()
f = open('data/test.txt','a') # append
f.write('-'*50)
for i in range(1,21):
data = '\n %d : Hello Python ' %i
f.write(data)
f.write('\n'+'-'*50)
f.close()
f = open('data/test.txt','r', encoding='utf-8')
data = f.read() #한번에 다읽음, 파일 사이즈가 크면 못읽음
print(data)
data = f.read()
print('두번째' + data + '종료')
f.seek(0, 0) # 파일 핸들러
data = f.read()
print(data)
f.close()
f = open('data/test.txt','r', encoding='utf-8')
while 1 :
data = f.readline()
print(data, end='')
if not data : break
f.close()
f = open('data/test.txt','r', encoding='utf-8')
data = f.readlines() #리스트에 담음
for i in data :
print(i, end='')
f.close()
# with 문 이용하기
f = open('data/foo.txt','w')
f.write('Life is too short, you need python')
f.close()
with open('data/foo.txt','w') as f : # close 안써도 되는 with 문
f.write('Life is too short, you need python')
with open('data/test2.txt', 'w', encoding='utf-8') as f :
for i in range(1, 11) :
data = '%d번째 줄 입니다 \n' % i
f.write(data)
with open('data/test2.txt', 'r', encoding='utf-8') as f:
data = f.read()
print(data)
with open('./data/test4.txt','w') as f: #프린트를 이용해 파일에 쓸 수 있음
print('Test Contents!',file =f)
print('Test Contents!!', file=f)
<file_sep>from flask import Flask, render_template, request, session
import json
from urllib.request import urlopen
from urllib.parse import quote
import re
import pandas as pd
import folium
import database as db
app = Flask(__name__, template_folder='view')
app.secret_key='<KEY>'
@app.route('/')
def index() :
html = render_template('index.html')
return html
@app.route('/now', methods=['GET', 'POST'])
def now() :
url_base = 'http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureSidoLIst'
service_key = <KEY>'
page = '&numOfRows=10&pageNo=1'
sidoname = '&sidoName=' + quote('인천')
daily = '&searchCondition=DAILY'
url = url_base + service_key + page + sidoname + daily
xml = urlopen(url)
data = xml.read().decode('utf8')
goo = re.findall('<cityName>.+</cityName>', data)
list_a = []
for line in goo:
line = line.replace('<cityName>', '')
line = line.replace('</cityName>', '')
list_a.append(line)
pm10 = re.findall('<pm10Value>.+</pm10Value>', data)
list_b = []
for line in pm10:
line = line.replace('<pm10Value>', '')
line = line.replace('</pm10Value>', '')
list_b.append(line)
pm25 = re.findall('<pm25Value>.+</pm25Value>', data)
list_c = []
for line in pm25:
line = line.replace('<pm25Value>', '')
line = line.replace('</pm25Value>', '')
list_c.append(line)
so2 = re.findall('<so2Value>.+</so2Value>', data)
list_d = []
for line in so2:
line = line.replace('<so2Value>', '')
line = line.replace('</so2Value>', '')
list_d.append(line)
co = re.findall('<coValue>.+</coValue>', data)
list_e = []
for line in co:
line = line.replace('<coValue>', '')
line = line.replace('</coValue>', '')
list_e.append(line)
o3 = re.findall('<o3Value>.+</o3Value>', data)
list_f = []
for line in o3:
line = line.replace('<o3Value>', '')
line = line.replace('</o3Value>', '')
list_f.append(line)
no2 = re.findall('<no2Value>.+</no2Value>', data)
list_g = []
for line in no2:
line = line.replace('<no2Value>', '')
line = line.replace('</no2Value>', '')
list_g.append(line)
dtime = re.findall('<dataTime>.+</dataTime>', data)
list_h = []
for line in dtime:
line = line.replace('<dataTime>', '')
line = line.replace('</dataTime>', '')
list_h.append(line)
dataset = {'구': list_a, 'pm10': list_b, 'pm25': list_c, 'so2': list_d, 'co': list_e, 'o3': list_f, 'no2': list_g,
'dateTime': list_h}
df = pd.DataFrame(dataset)
df.drop(0, inplace=True)
df.drop(9, inplace=True)
df.set_index('구', inplace=True)
print(df)
for i in range(0, 8):
for j in range(0, 6):
if df.iloc[i][j] == '-':
df.iloc[i][j] = 0
db.add_air(df)
df.to_csv("static/dust.csv", encoding='utf-8', sep=',')
dff = pd.read_csv('static/dust.csv', thousands=',', encoding='utf-8')
dff.set_index('구', inplace=True)
geo_path = 'static/skorea-municipalities-2018-geo.json'
geo_json = json.load(open(geo_path, encoding='utf-8'))
map = folium.Map(location=[37.454441, 126.708096],
zoom_start=11, tiles='Mapbox Control Room')
map.choropleth(geo_data=geo_json,
data=dff['pm10'],
columns=[dff.index, dff['pm10']],
fill_color='PuBu',
key_on='feature.properties.name',
fill_opacity=1,
line_opacity=1,
highlight=True)
map.save('view/dust.html')
html = render_template('dust.html')
return html
@app.route('/about')
def about() :
return 'about page'
@app.route('/student_list')
def student_list() :
stu_name = request.args.get('stu_name')
stu_list = db.get_student_list(stu_name)
html = render_template('student_list.html', data_list=stu_list)
return html
@app.route('/show_point')
def show_point() :
html = render_template('show_point.html')
return html
@app.route('/student_info', methods=['get', 'post'])
def student_info() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
# 학생 데이터를 가져온다.
result_dic = db.get_student_info(stu_idx)
# 학생 점수를 가져온다.
result_list = db.get_point(stu_idx)
html = render_template('student_info.html', data_dic=result_dic, data_list=result_list)
return html
@app.route('/add_student')
def add_student() :
html = render_template('add_student.html')
return html
@app.route('/add_point')
def add_point() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('add_point.html', data_dic=temp_dic)
return html
@app.route('/add_student_pro', methods=['post'])
def add_student_pro() :
# 파라미터 데이터 추출한다.
stu_name = request.form['stu_name']
stu_age = request.form['stu_age']
stu_addr = request.form['stu_addr']
# print(f'{stu_name} {stu_age} {stu_addr}')
# 저장한다.
idx = db.add_student(stu_name, stu_age, stu_addr)
result_dic = { 'stu_idx' : idx,
'msg' : '학생등록이 완료되었습니다'}
html = render_template('add_student_pro.html', data_dic=result_dic)
return html
@app.route('/add_point_pro', methods=['post'])
def add_point_pro() :
# 파라미터 추출
point_stu_grade = request.form['point_stu_grade']
point_stu_kor = request.form['point_stu_kor']
point_stu_idx = request.form['point_stu_idx']
# 점수 정보 저장
db.add_point(point_stu_idx, point_stu_grade, point_stu_kor)
temp_dic = {}
temp_dic['stu_idx'] = point_stu_idx
html = render_template('add_point_pro.html', data_dic=temp_dic)
return html
@app.route('/login', methods=['get','post'])
def login() :
html = render_template('login.html')
return html
@app.route('/login_pro', methods=['get','post'])
def login_pro() :
id = request.form['id']
pwd = request.form['pwd']
session['m_session'] = db.login(id,pwd)
html = render_template('login_pro.html')
return html
@app.route('/register', methods=['GET', 'POST'])
def register():
html = render_template('register.html')
return html
@app.route('/register_pro', methods=['GET', 'POST'])
def register_pro():
# 파라미터 추출
id = request.form['id']
pwd = request.form['pwd']
# 점수 정보 저장
db.register(id,pwd)
html = render_template('register_pro.html')
return html
@app.route('/logout', methods=['get','post'])
def logout() :
session['m_session'] = False
html = render_template('index.html')
return html
@app.route('/modify_student', methods=['GET', 'POST'])
def modify_student() :
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('modify_student.html',data_dic=temp_dic)
return html
@app.route('/modify_student_pro', methods=['GET', 'POST'])
def modify_student_pro() :
idx = request.form['stu_idx']
name = request.form['stu_name']
age = request.form['stu_age']
addr = request.form['stu_addr']
db.modify(idx, name, age,addr)
temp_dic = {}
temp_dic['stu_idx'] = idx
html = render_template('modify_student_pro.html',data_dic=temp_dic)
return html
@app.route('/delete_student', methods=['GET', 'POST'])
def delete_student() :
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('delete_student.html', data_dic=temp_dic)
return html
@app.route('/delete_student_pro', methods=['GET', 'POST'])
def delete_student_pro() :
idx = request.form['stu_idx']
db.delete_student(idx)
html = render_template('delete_student_pro.html')
return html
for i in range(1,11) :
print(i,end='')
app.run(host='127.0.0.1', port=8080)<file_sep>from day16_flask.main import app
if __name__=="__main__":
app.run(host='127.0.0.1', port = 80, debug=True) #모든 클라이언트에 접속허용 0.0.0.0
#127.0.0.1 로 들어가야함
#허용하지면 원격은 허용안함 0.0.0.1
# app.run()
<file_sep>import csv
with open('./csv/data/population.csv', 'r') as f :
reader = csv.reader(f)
next(reader) #헤더를 스킵한다
max = 0
idx = ''
for c in reader :
mstr = c[1]
mstr = mstr.replace(',','')
c[1] = mstr
print(c)
if max < int(c[1]) :
max = int(c[1])
idx = c[0]
print(idx,max)
with open('./csv/data/population.csv', 'r') as f :
reader = csv.reader(f)
#next(reader) #헤더를 스킵한다
resultList = []
for c in reader :
#print(c)
resultList.append(c)
resultList = resultList[1:]
for i in range(0, len(resultList)):
data = resultList[i][1]
data = int(data.replace(',',''))
resultList[i][1] = data
print(resultList)
status = resultList[0][0]
max = resultList[0][1]
for i in range(0, len(resultList)):
if max < resultList[i][1]:
max = resultList[i][1]
status = resultList[i][0]
print(status)
#XSL, XLSX
#pip install pandas
#pip install xlrd
#pip install openpyxl<file_sep>use employees;
-- 1. 현재 근무 중인 직원 정보를 출력하시오.
select employees.*, dept_emp.dept_no from employees
inner join dept_emp on employees.emp_no = dept_emp.emp_no
where dept_emp.to_date = '9999-01-01';
-- 2. 현재 근무 중인 직원의 모든 정보(수행업무 포함) 를 출력하시오.
select e.*, t.title
from employees e
inner join dept_emp d on e.emp_no = d.emp_no
inner join titles t on e.emp_no = t.emp_no
where d.to_date = '9999-01-01';
-- 3. 현재 근무 중인 부서명를 출력하시오. (사원번호, 사원명, 부서코드, 부서명)
-- 4. 가장오래 근무한 직원 10명의 현재 부서를 출력하시오.
select e.emp_no, d.dept_name
from dept_emp de
inner join employees e on e.emp_no = de.emp_no
inner join departments d on de.dept_no = d.dept_no
where de.to_date = '9999-01-01'
order by hire_date
limit 10;
-- 5. 부서별로 직원 수를 구하되 부서 이름이 나오게 출력하시오.
select d.dept_name, count(*)
from departments d
inner join dept_emp de on d.dept_no = de.dept_no
where de.to_date = '9999-01-01'
group by d.dept_name
order by d.dept_name;
-- 6. 부서별, 성별 직원 수를 구하시오
select d.dept_name, sum(if(e.gender in ('m'),1,0)) as 'm', sum(if(e.gender in ('f'),1,0)) as 'f'
from departments d
inner join dept_emp de on d.dept_no = de.dept_no
inner join employees e on e.emp_no = de.emp_no
where de.to_date = '9999-01-01'
group by d.dept_name
order by d.dept_name;
select * from employees;
-- 7. 급여 평균이 가장 높은 부서 5개를 출력하시오.
select d.dept_name, sa
from (select de.dept_no, avg(s.salary) sa
from dept_emp de
inner join salaries s on de.emp_no = s.emp_no
where s.to_date = '9999-01-01'
and s.to_date = '9999-01-01'
group by de.dept_no
order by sa desc
limit 5) A inner join departments d
on A.dept_no = d.dept_no;
-- 8. 급여 평균이 가장 높은 부서를 제외하고, 급여 평균이 높은 부서를 5개를 출력하시오.
select d.dept_no, de.dept_name, avg(s.salary)
from dept_emp d
inner join salaries s on d.emp_no = s.emp_no
inner join departments de on de.dept_no = d.dept_no
where s.to_date = '9999-01-01'
group by d.dept_no
order by avg(s.salary) desc
limit 2,5;
-- 9. 급여를 많이 받는 부서장 리스트를 출력하시오
select m.*, s.salary
from dept_manager m
inner join salaries s on m.emp_no = s.emp_no
where s.to_date = '9999-01-01' and m.to_date = '9999-01-01'
order by s.salary desc
limit 1;
-- 10. 개발부(Development)에서 급여를 가장 많이 받는 직원 5명을 출력하시오.
select e.first_name, e.last_name, s.salary
from employees e
inner join salaries s on e.emp_no = s.emp_no
where s.to_date = '9999-01-01'
order by s.salary desc
limit 5;
<file_sep>class My:
def __init__(self):
self.name = 'python'
print('My')
def getName(self):
return self.name
class SubMy(My):
def __init__(self):
super().__init__() #이걸 해 주어야 합니다
print('SubMy')
#
# m1 = My()
# print(m1.getName())
cm1 = SubMy()
print(cm1.getName())<file_sep>#야구
import random
com = set()
while 1 :
com.add(random.randint(1,9))
if len(com) == 3 : break
print(com)
com = list(com)
print('*'*20)
cnt = 0
while 1:
val = input('숫자 세개 입력 : ')
myval = [int(i) for i in val]
out = 0
strike = 0
ball = 0
for i in range(0,3) :
for j in range(0, 3) :
if com[i] == myval[i] :
strike += 1
break
elif (com[i] == myval[j]) and (i != j) :
ball += 1
break
out = 3 - strike - ball
print('Strike : %d, Ball : %d, Out : %d '% (strike,ball,out))
cnt += 1
if strike == 3 :
print('*' * 20)
print('%d 번 만에 정답!!'% (cnt))
break
<file_sep>{% extends "layout.html" %}
{% block content %}
<div class="container">
<h1>학생 정보 추가</h1>
<form action="add_student_pro" method="post">
이름 : <input type="text" name="stu_name"/><br/>
나이 : <input type="text" name="stu_age"/><br/>
주소 : <input type="text" name="stu_addr"/><br/>
<button type="submit">추가하기</button>
</form>
<p>
<a href="student_list">목록보기</a>
</p>
</div>
{% endblock %}
<file_sep>{% extends "layout.html" %}
{% block content %}
<div class="container">
{% if session['logged_in'] %}
{% if data %}
<h3>팔로워 : {{ '{:,}'.format(cnt) }} </h3>
<table border="0" cellpadding="10" cellspacing="10">
<tr>
{% for thumb in data %}
<td><img src={{thumb}} width="150" height="150"></td>
{% if (loop.index > 1) and (loop.index % 5 == 0) and (loop.index == loop.length) %}
</tr>
{% elif loop.index > 1 and loop.index % 5 == 0 %}
</tr><tr>
{% endif %}
{% endfor %}
</table>
{% endif %}
<br><br>
<form action="" method="POST">
<input type="username" name="username" placeholder="Instagram Username">
<input type="submit" value="Finds">
</form>
<p>
박신혜 : ssinz7 <br>
공 유 : gongyoo1079<br>
박서준 : bn_sj2013<br>
이효리 : lee_hyori_onni<br>
정해인 : holyhaein<br>
</p>
{% else %}
<p><h4>로그인을 하시면 스타들의 인스타그램을 이용하실 수 있습니다.</h4></p>
{% endif %}
</div>
{% endblock %}<file_sep>import json
from flask import Flask
app = Flask(__name__, template_folder='view')
@app.route('/')
def index() :
test_dic = {
'a1' : 100,
'a2' : '문자열'
}
#JSON Encoding : Python Object (Dictionary, List, Tuple 등)를 JSON 문자열로 변경
json_data = json.dumps(test_dic, indent=4, ensure_ascii=False)
# indent 는 들여쓰기, ensure_ascii 는 한글 처리
print(type(json_data), json_data)
#JSON Decoding : JSON 문자열을 Python Object (Dictionary, List, Tuple 등)로 변경
python_data = json.loads(json_data)
print(type(python_data), python_data)
return json_data
app.run(host='127.0.0.1', port=80)
<file_sep>import pymysql
conn = pymysql.connect(host = 'localhost',
port = 3306,
user = 'root',
passwd = '<PASSWORD>',
db = 'pyMysql_db',
charset = 'utf8')
curs = conn.cursor() # 튜플커서
sql = 'insert into member(userid, pwd, name, email, regdate) values(%s, %s, %s, %s, now())'
curs.execute(sql, ('ccc','1234','토이','toystory'))
data = (
('ddd','1234','알라딘','<EMAIL>'),
('EEE', '1234', '기생충', '<EMAIL>'),
('fff', '1234', '인어공주', '<EMAIL>')
)
curs.executemany(sql, data)
sql = 'update member set email = %s where userid = %s'
curs.execute(sql, ('<EMAIL>','aaa'))
sql = 'delete from member where userid = %s'
curs.execute(sql,('fff'))
conn.commit()
sql = 'select * from member'
curs.execute(sql)
rows = curs.fetchall()
print(rows)
conn.close()<file_sep>from flask import Flask, render_template, request, session, redirect, url_for
import datetime
app = Flask(__name__, template_folder='view')
app.secret_key = '<KEY>'
@app.route('/')
@app.route('/index')
def index():
print(datetime.datetime.now())
if not session.get('logged_in'):
return render_template('index.html')
else:
if request.method == 'POST':
#username = getname(request.form['username'])
#return render_template('index.html', data=getfollowedby(username))
username = request.form['username']
return render_template('index.html', data=username)
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
name = request.form['username']
passw = request.form['password']
try:
#DB에서 회원정보 조회
session['logged_in'] = True
session['user_id'] = name
return redirect(url_for('index'))
except:
return "Dont Login"
@app.route('/register/', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username=request.form['username']
password=request.form['<PASSWORD>']
#DB에 회원정보 등록
return render_template('login.html')
return render_template('register.html')
@app.route('/logout')
def logout():
if session.get('logged_in'):
del session['logged_in']
if session.get('user_id'):
del session['user_id']
session.pop('logged_in', None)
session.pop('user_id', None)
return redirect(url_for('index'))
@app.route('/about')
def about():
return render_template('about.html', title='About')
app.run(host='127.0.0.1', port=80)
<file_sep>from flask import Blueprint, render_template, request
blue100 = Blueprint('blue1', __name__, template_folder='view/sub1')
@blue100.route('/test3')
def test3() :
html = render_template('test2.html')
return html<file_sep>import json
from flask import Flask, render_template
app = Flask(__name__, template_folder='templates')
test_dic = {
'a1' : 100,
'a2' : '문자열'
}
test_list = (10, 20, 30, 40, 50)
@app.route("/")
def index() :
html = render_template('index.html', data_dic = test_dic, data_list=test_list)
return html
@app.route("/testjson")
def testjson():
json_data = json.dumps(test_dic, indent=4, ensure_ascii=False)
print(type(json_data), json_data)
python_data = json.loads(json_data)
print(type(python_data), python_data)
return json_data
@app.route('/test1')
def test1():
return 'test1'
@app.route('/test1/sub1')
def test1_sub1() :
return 'test1 sub1'
@app.route('/user/<username>/<int:age>') #형변환
def show_user_profile_age(username, age):
return 'Username %s, 나이 %d' % (username,age)
<file_sep>-- SQL 퀴즈
-- 1. 직원 이름이 빠른 순(A, B, C …) 순으로 리스트를 출력하시오.
use employees;
select * from employees order by first_name;
-- 2. 직원 나이가 적은 순으로 출력하시오.
select * from employees order by birth_date desc;
-- 3. 직원 중 나이가 가장 많은 사람의 나이는 몇 살 인가?
select min(birth_date) from employees;
select timestampdiff(year, min(birth_date), now()) as 나이 from employees;
-- 4. 직원들의 업무(titles)에는 직원별로 업무가 저장되어 있다. 이 회사의 업무 종류 리스트를 구하시오.
select distinct title from titles;
-- 5. 이 회사의 업무 종류 개수를 구하시오.
select count(distinct title) from titles;
select count(*) from (select title from titles group by title) a;
-- 6. 가장 최근에 입사한 사람 100명만 출력하시오
select * from titles order by from_date limit 100;
-- 7. 급여가 가장 많은 사람 10명을 구하시오.
select * from salaries order by salary desc limit 10;
select last_name from (select * from salaries order by salary desc limit 10);
-- 8. 급여가 가장 많은 사람 10명을 제외하고 다음 10명을 구하시오.
-- 즉, 11등부터 20등 까지…
select * from salaries order by salary desc limit 11,10;
-- 9. 입사한지 가장 오래된 사람의 이름은 무엇인가?
select first_name, last_name from employees order by hire_date limit 1;
-- 10. 1999년에 입사한 직원 리스트를 구하시오.
select * from employees;
select * from employees where year(hire_date)= 1999;
-- 11. 1999년에 입사한 직원 중 여자 직원(GENDER='F') 리스트를 구하시오.
select * from employees where year(hire_date)= 1999 and gender = 'F';
-- 12. 1998년에 입사한 직원 중 남자 직원(M)은 몇 명인가?
select count(*) from employees where year(hire_date)= 1998 and gender = 'm';
-- 13. 1998년이나 1999년에 입사한 직원의 수를 구하시오.
select count(*) from employees where year(hire_date)= 1998 or year(hire_date)= 1999;
-- 14. 1995년부터 1999년까지 입사한 직원의 수를 구하시오.
select count(*) from employees where year(hire_date)> 1994 and year(hire_date)< 2000;
-- 15. 성(last_name)이 Senzako, Pettis, Henseler인 직원을 출력하시오.
select * from employees where last_name ='Senzako' or last_name ='Pettis' or last_name ='Henseler';<file_sep>from day16_flask.main2 import app
if __name__=="__main__":
app.run(host='127.0.0.1', port = 80, debug=True)
<file_sep>from flask import Flask, render_template, request, session
import json
from urllib.request import urlopen
from urllib.parse import quote
import re
import pandas as pd
import folium
import database as db
app = Flask(__name__, template_folder='view')
app.secret_key='<KEY>'
@app.route('/')
def index() :
html = render_template('index.html')
return html
@app.route('/now', methods=['GET', 'POST'])
def now() :
url_base = 'http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureSidoLIst'
service_key = <KEY>'
page = '&numOfRows=10&pageNo=1'
sidoname = '&sidoName=' + quote('인천')
daily = '&searchCondition=DAILY'
url = url_base + service_key + page + sidoname + daily
xml = urlopen(url)
data = xml.read().decode('utf8')
goo = re.findall('<cityName>.+</cityName>', data)
list_a = []
for line in goo:
line = line.replace('<cityName>', '')
line = line.replace('</cityName>', '')
list_a.append(line)
pm10 = re.findall('<pm10Value>.+</pm10Value>', data)
list_b = []
for line in pm10:
line = line.replace('<pm10Value>', '')
line = line.replace('</pm10Value>', '')
list_b.append(line)
pm25 = re.findall('<pm25Value>.+</pm25Value>', data)
list_c = []
for line in pm25:
line = line.replace('<pm25Value>', '')
line = line.replace('</pm25Value>', '')
list_c.append(line)
so2 = re.findall('<so2Value>.+</so2Value>', data)
list_d = []
for line in so2:
line = line.replace('<so2Value>', '')
line = line.replace('</so2Value>', '')
list_d.append(line)
co = re.findall('<coValue>.+</coValue>', data)
list_e = []
for line in co:
line = line.replace('<coValue>', '')
line = line.replace('</coValue>', '')
list_e.append(line)
o3 = re.findall('<o3Value>.+</o3Value>', data)
list_f = []
for line in o3:
line = line.replace('<o3Value>', '')
line = line.replace('</o3Value>', '')
list_f.append(line)
no2 = re.findall('<no2Value>.+</no2Value>', data)
list_g = []
for line in no2:
line = line.replace('<no2Value>', '')
line = line.replace('</no2Value>', '')
list_g.append(line)
dtime = re.findall('<dataTime>.+</dataTime>', data)
list_h = []
for line in dtime:
line = line.replace('<dataTime>', '')
line = line.replace('</dataTime>', '')
list_h.append(line)
dataset = {'구': list_a, 'pm10': list_b, 'pm25': list_c, 'so2': list_d, 'co': list_e, 'o3': list_f, 'no2': list_g,
'dateTime': list_h}
df = pd.DataFrame(dataset)
df.drop(0, inplace=True)
df.drop(9, inplace=True)
df.set_index('구', inplace=True)
print(df)
for i in range(0, 8):
for j in range(0, 6):
if df.iloc[i][j] == '-':
df.iloc[i][j] = 0
db.add_air(df)
df.to_csv("static/dust.csv", encoding='utf-8', sep=',')
dff = pd.read_csv('static/dust.csv', thousands=',', encoding='utf-8')
dff.set_index('구', inplace=True)
geo_path = 'static/skorea-municipalities-2018-geo.json'
geo_json = json.load(open(geo_path, encoding='utf-8'))
map = folium.Map(location=[37.454441, 126.708096],
zoom_start=11, tiles='Mapbox Control Room')
map.choropleth(geo_data=geo_json,
data=dff['pm10'],
columns=[dff.index, dff['pm10']],
fill_color='PuBu',
key_on='feature.properties.name',
fill_opacity=1,
line_opacity=1,
highlight=True)
map.save('view/dust.html')
html = render_template('dust.html')
return html
@app.route('/hour', methods=['GET', 'POST'])
def hour() :
html = render_template('hour.html')
return html
@app.route('/future', methods=['GET', 'POST'])
def future() :
html = render_template('future.html')
return html
@app.route('/sample', methods=['GET', 'POST'])
def sample() :
html = render_template('dust.html')
return html
@app.route('/login', methods=['get','post'])
def login() :
html = render_template('login.html')
return html
@app.route('/login_pro', methods=['get','post'])
def login_pro() :
id = request.form['id']
pwd = request.form['pwd']
session['m_session'] = db.login(id,pwd)
html = render_template('login_pro.html')
return html
@app.route('/register', methods=['GET', 'POST'])
def register():
html = render_template('register.html')
return html
@app.route('/register_pro', methods=['GET', 'POST'])
def register_pro():
# 파라미터 추출
id = request.form['id']
pwd = request.form['pwd']
# 점수 정보 저장
db.register(id,pwd)
html = render_template('register_pro.html')
return html
@app.route('/logout', methods=['get','post'])
def logout() :
session['m_session'] = False
html = render_template('index.html')
return html
app.run(host='127.0.0.1', port=8080)<file_sep>use sqldb;
select * from buytbl;
select * from usertbl;
select userid,
sum(price * amount) as '총 구매액',
case when sum(price * amount) < 200 then '새싹고객'
when sum(price * amount) < 1500 then '우수고객'
else 'vip 고객' end as '고객구분'
from buytbl
group by userid
order by 2;
select prodName from buytbl where groupName is not null;
select prodName from buytbl where length(groupName) < 1;
select prodName from buytbl where length(ifnull(groupName, '')) <1;
-- 대체하고 체크하기
select distinct prodName, ifnull(groupName,'미분류') as groupName from buytbl;
alter table usertbl add pwd varchar(20);
update usertbl set pwd=concat(userid,right(birthyear,2),'<PASSWORD>');
select * from usertbl;
select userid, mdate from usertbl where right(mDate,5) like '07%';
select userid, mdate, timestampdiff(year,mdate,curdate()) as aa
from usertbl
where month(mdate) = month(curdate());
create table maxtbl(col1 longtext, col2 longtext);
insert into maxtbl values (repeat('a',1000000), repeat('가',1000000));
select length(col1), length(col2) from maxtbl;
select userid, name, mdate,
case when month(mdate) in (12,1,2) then '겨울'
when month(mdate) in (3,4,5) then '봄'
when month(mdate) in (6,7,8) then ' 여름'
when month(mdate) in (9,10,11) then '가을'
end as '계절'
from usertbl;
select
sum(if(month(mdate) in (12,1,2),1,0)) as '겨울',
sum(if(month(mdate) in (3,4,5),1,0 )) as '봄',
sum(if(month(mdate) in (6,7,8),1,0 )) as ' 여름',
sum(if(month(mdate) in (9,10,11),1,0 )) as '가을'
from usertbl;
-- json
select json_object('name',name,'height',height, 'id',userid)
from usertbl
where userid = 'BBK';
select count(distinct userid) from buytbl;
select *
from buytbl
inner join usertbl
on buytbl.userID = usertbl.userID
where usertbl.userID = 'bbk';
select b.userID,
u.name, b.prodname, u.addr,
u.mobile1 + u.mobile2 as '연락처'
from buytbl b inner join usertbl u
on b.userID = u.userID;
select buytbl.userID, name, prodname, addr, mobile1 + mobile2 as '연락처'
from buytbl, usertbl
where buytbl.userID = usertbl.userID;
select b.userID, name, prodname, addr, mobile1 + mobile2 as '연락처'
from buytbl b, usertbl u
where b.userID = u.userID
and b.userid = 'bbk';
select b.userID, name, prodname, addr, mobile1 + mobile2 as '연락처'
from buytbl b inner join usertbl u
on b.userID = u.userID
where b.userid = 'bbk';
select u.userID, u.name, u.addr, sum(b.price * b.amount) as '총구매액'
from usertbl u
inner join buytbl b on b.userID = u.userID
group by u.userid
order by u.userid;
select u.userID, u.name, u.addr
from usertbl u
where exists (
select *
from buytbl b
where u.userID = b.userID);
-- left outer join
use sqldb;
select u.userid, u.name, b.prodname, u.addr
from usertbl u
left outer join buytbl b
on u.userID = b.userID;
-- union, union all, self join
create view v_usertbl
AS
select userid, name, addr from usertbl;
select * from v_usertbl;
select a.*, b.price
from v_usertbl a, sqldb.buytbl b
where a.userid = b.userid;<file_sep># 컬렉션 : List Tuple Dictionary Set
# 튜플 -> 고정(여러 데이터 타입) 변경x 인덱스로 접근, 중복o, 읽기만가능, 튜플이 리스트 보다 성능 좋음
# 리스트 -> 인덱스로 접근, 서로 다른 데이터 형을 함께 사용 가능
# 딕셔너리 -> 키:값, 순서x 인덱스x 키 값으로 접근, 테이블 구조
# 셋 -> 키x 인덱스x, 값만있음 주머니구조 무작위, 값들의 중복이 안됨
# immutable - 숫자형, 문자열, 튜플
# mutable - 리스트, 딕셔너리
#list
#indexing
a = []
print(type(a))
b = [1,2,3]
c = [1 ,2 ,'Life','is']
d = [1 ,2 ,['Life','is']]
print(d[2][0])
#slicing
a = [1,2,3,4,5]
print(a[0:3])
b = [5,6,7]
print(a+b)
print(b*3)
a.extend(b) #a 자체 늘이기
print(a)
b[2] = 4 # 수정하기
print(b)
b[1:2] = ['a','b','c']
print(b)
b[1:3] = []
print(b)
del b[1]
print(b)
a=['a','c','b']
a.reverse()
print(a)
a.sort()
print(a)
a.append('a')
print(a)
a.remove('a')
print(a)
print(a.pop())
a = ['Life','is','too','short']
result = ''.join(a)
print(result) #리스트를 문자열로 반환할 때 사용
fruits = ['사과','수박','망고','바나나','망고','바나나']
print('사과' in fruits)
print('fruits 목록 : {}'.format(fruits))
print('fruits[0] = {}'.format(fruits[0]))
print('fruits[-1] = {}'.format(fruits[-1]))
fruits[0] = '자두'
print('fruits 목록 : {}'.format(fruits))
x = 1
y = x
print(id(x), id(y), x, y)
#숫자는 immutable 이므로, 새로운 변수를 할당하므로 주소번지가 달라진다. 문자열도 마찬가지, 깊은 복사
y += 3
print(id(x), id(y), x, y)
x = [1, 2]
y = x
print(id(x), id(y), x, y)
# list 는 mutable이다, 얕은 복사
y.append(3)
print(id(x), id(y), x, y)
print('fruits 리스트 전체 길이 : {}'.format(len(fruits)))
fruits.append('복숭아')
print('fruits 목록 : {}'.format(fruits))
fruits.insert(1,'키위') #insert(번째,값)
print('fruits 목록 : {}'.format(fruits))
#삭제방법 : remove(값), del(index), slicing 빈 리스트 등등
fruits.remove('망고')
print('fruits 목록 : {}'.format(fruits))
print(fruits.pop())
print('fruits 목록 : {}'.format(fruits))
print(fruits.pop(0))
print('fruits 목록 : {}'.format(fruits))
del fruits[0:3]
print('fruits 목록 : {}'.format(fruits))
fruits.clear()
print('fruits 목록 : {}'.format(fruits))
a = [1,2,3,4,5]
b = [7,8,9,10]
print('a + b = ',a+b)
a.extend(b)
print(a)
foods = ['라면','돈가스','볶음밥']
print(' foods = ', foods)
sep = ','
print(sep.join(foods))
myStr = '강/김/홍/박/선우/우/이/신' #문자열 리스트로 나누기
print(myStr.split('/'))
#튜플 선언 ','가 중요하다.
tupleName = ('item',)
print(type(tupleName))
tupleName = 'item',
print(type(tupleName))
#튜플 삭제 변경시 오류 발생 함
#더하기 곱, 리스트와 같음
t1 = ('도','레','미','파','솔')
print(t1,type(t1))
t2 = 1,2,3,4,5
print(t2,type(t2))
myTuple = (100,'강아지',('지렁이'))
print('myTuple = ', myTuple)
print('myTuple[0] = ', myTuple[0])
myTuple += (50,100) #값 변경x 새로 만드는 것임
print('myTuple = ', myTuple)
myTuple += ('끝',)
print('myTuple = ', myTuple)
t1 = 100,50,30,30,30
print('30의 반복 횟수 : ',t1.count(30)) #sort 는 값이 수정되기 때문에 안됨
print(len(t1))
print(t1.index(30))
#튜플 형변환
myStr = 'Python'
print(myStr, type(myStr))
myTuple = tuple(myStr)
print(myTuple, type(myTuple))
myList = ['수학','과학','영어']
print(myList, type(myList))
myTuple = tuple(myList)
print(myTuple, type(myTuple))
myTuple = ('도','레','미')
print(myTuple, type(myTuple))
myStr = str(myTuple)
print(myStr, type(myStr))
print(myStr[0]) #(
myStr = ','.join(myTuple)
print(myStr,type(myStr))
myStr2 = ' / '.join(myTuple)
print(myStr2, type(myStr2))
#dictionary :키 값 중복x 나머지 값 중복가능, 순서x
#키 값이 같은 경우 마지막 아이템만 유지됨
#키 값으로 리스트 쓸 수 없다
dic1 = {1:'a',2:'b',3:'c'}
print(dic1,type(dic1))
dic1[4] = 'd'
print(dic1)
dic1[3] = 'e'
print(dic1)
del dic1[1] #del dic1[키]
print(dic1)
a = {'name' : 'pay', 'phone': '010555151151', 'birth' : '1994'}
print(a.get('name'))
print('name' in a) # 키 값으로만 찾기
print(a.pop('name'))
print(a)
dict1 = {'a':'africa', 'b':'banana', 'c':'cat'}
print('dict1 = ',dict1)
dict2 = {'a':'africa', 'b':'banana', 'c':'cat', 'a' : 'abc'}
print('dict2 = ',dict2, len(dict2))
dict0 = {}
dict0_0 = dict()
print('dict0 = ', dict0, type(dict0))
print(dict1.keys()) #키만, 값만, 둘다
print(dict1.values())
print(dict1.items())
myStr = ' '.join(dict1) #키 기준임
print(myStr)
#딕셔너리 얕은 복사
a = {'alice': [1, 2, 3], 'bob': 20, 'tody': 15, 'suzy': 30}
b = a.copy()
b['alice'].append(5)
print('a=', a)
print('b=', b)
#딕셔너리 깊은 복사
import copy
b = copy.deepcopy(a)
b['alice'].append(5)
print('a=', a)
print('b=', b) #구조체나 클래스 로 생각
t_list = tuple(a) #항상 키값 기준
print('t_list =', t_list)
a = {'alice': {1:'1', 2:'2', 3:'3'}, 'bob': 20, 'tody': 15, 'suzy': 30}
print(a['alice'][1]) #딕셔너리 안에 딕셔너리
# set 은 중복을 허용하지 않는다
# list를 set으로 형변환해서 합집합하는걸 많이 사용함
# 수정, 추가가능
s1 = set("hello")
print(s1) #중복제거
s1 = set([1,2,3,4,5,6])
s2 = set([4,5,6,7,8,9])
print(s1 & s2, s1.intersection(s2)) #교집합
print(s1 | s2, s1.union(s2)) #합집합
print(s1 - s2, s2 - s1, s1.difference(s2), s2.difference(s1)) #차집합
s1.add(7)
print(s1)
s1.update([8,9,10]) #여러개 add하기
print(s1)
s1.remove(10) #없는거 빼면 에러 생김
print(s1) #빼기
s1.discard(9) #에러 없이 빼기
print(s1)
s1.clear() # 모든 컬렉션 자료형에 다있음
print(s1)
############################################################
# 로또 프로그램
import random
lotto = []
lotto.append(random.randint(1, 6)) # randint 난수는 원래 소수임, 따라서 난수를 정수로 주는
lotto.append(random.randint(1, 6)) # 함수이다 randint(1, 6) 이면 1~6까지범위 줌
lotto.append(random.randint(1, 6))
lotto.append(random.randint(1, 6))
lotto.append(random.randint(1, 6))
lotto.append(random.randint(1, 6))
print (len(lotto), lotto)
lotto = set() #set 초기화 방법
lotto.add(random.randint(1,6))
lotto.add(random.randint(1,6))
lotto.add(random.randint(1,6))
lotto.add(random.randint(1,6))
lotto.add(random.randint(1,6))
lotto.add(random.randint(1,6))
print (len(lotto), lotto)
lotto = set()
while True:
lotto.add(random.randint(1, 6))
if (len(lotto)) == 6:
break
print(len(lotto), lotto)
k = range(1,47) #(상한값, 하한값, 인터벌)
lott_num = random.sample(k,6)
print(lott_num)
f = random.random()
print(f)
f = random.uniform(1.0, 36.5)
print(f)
i = random.randrange(1, 101, 2) # 1~100 사이의 짝수
print(i)
i = random.randrange(10) # 끝값 = (0,10,1)
print(i)<file_sep>-- --------------------------------------------------------
-- 호스트: 127.0.0.1
-- 서버 버전: 10.3.14-MariaDB - mariadb.org binary distribution
-- 서버 OS: Win64
-- HeidiSQL 버전: 10.1.0.5464
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- python_ex_db 데이터베이스 구조 내보내기
CREATE DATABASE IF NOT EXISTS `python_ex_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `python_ex_db`;
-- 테이블 python_ex_db.point_table 구조 내보내기
CREATE TABLE IF NOT EXISTS `point_table` (
`point_stu_idx` int(11) DEFAULT NULL,
`point_stu_grade` varchar(50) DEFAULT NULL,
`point_stu_kor` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 테이블 데이터 python_ex_db.point_table:~0 rows (대략적) 내보내기
DELETE FROM `point_table`;
/*!40000 ALTER TABLE `point_table` DISABLE KEYS */;
INSERT INTO `point_table` (`point_stu_idx`, `point_stu_grade`, `point_stu_kor`) VALUES
(2, '2', '90'),
(2, '3', '95'),
(1, '1', '89');
/*!40000 ALTER TABLE `point_table` ENABLE KEYS */;
-- 테이블 python_ex_db.student_table 구조 내보내기
CREATE TABLE IF NOT EXISTS `student_table` (
`stu_idx` int(11) NOT NULL AUTO_INCREMENT,
`stu_name` varchar(50) DEFAULT NULL,
`stu_age` varchar(3) DEFAULT NULL,
`stu_addr` varchar(50) DEFAULT NULL,
PRIMARY KEY (`stu_idx`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- 테이블 데이터 python_ex_db.student_table:~1 rows (대략적) 내보내기
DELETE FROM `student_table`;
/*!40000 ALTER TABLE `student_table` DISABLE KEYS */;
INSERT INTO `student_table` (`stu_idx`, `stu_name`, `stu_age`, `stu_addr`) VALUES
(1, '홍길동', '18', '서울시'),
(2, '김개똥', '19', '서울시');
/*!40000 ALTER TABLE `student_table` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep>-- 1. 부서별 직원 수를 구하시오.
-- 2. 각 부서에서 가장 오래 근무한 직원을 출력하시오.
-- 3. 가장 오래된 직원 10명이 근무했던 처음과 마지막 부서를 출력하시오.
-- 4. 각 부서에서 급여를 가장 많이 받는 직원 리스트를 구하시오.
-- 5. 전체 평균보다 많이 받는 직원 수를 계산하시오.
-- 6. 퇴직한 직원 정보를 구하시오.
<file_sep># 정규표현식 - 입력값이 정확한지 처리
# 모듈 re
import re
str = 'My id number is kim0902'
# findall(정규표현식패턴,문자열)
a = re.findall('a',str)
print(a) # []
b = re.findall('kim',str)
print(b) # ['kim']
c = re.findall('m',str)
print(c) # ['m', 'm']
print('-'*30)
# 복잡한 패턴 예제
# 정규표현 패턴 [a-z], [A-Z], [0-9]
# 정규표현 패턴 [a-z]+, [A-Z]+, [0-9]+ - 단어단위로 찾음
str = 'My id number is kim0902'
# 소문자를 모두 찾아서 리스트로 반환
s1 = re.findall('[a-z]',str)
print(s1)
# ['y', 'i', 'd', 'n', 'u', 'm', 'b', 'e', 'r', 'i', 's', 'k', 'i', 'm']
# + 반복옵션, 소문자를 하나씩 끊어서 찾지 않고 연속해서 찾음.
# 단어 단위리스트로 반환
s2 = re.findall('[a-z]+',str)
print(s2)
# ['y', 'id', 'number', 'is', 'kim']
# 대문자를 모두 찾아서 리스트로 반환
s3 = re.findall('[A-Z]',str)
print(s3)
# ['M']
# 숫자를 모두 찾아서 리스트로 반환
s4 = re.findall('[0-9]',str)
print(s4)
# ['0', '9', '0', '2']
# + 반복옵션, 숫자를 하나씩 끊어서 찾지 않고 연속해서 찾음.
# 단어 단위리스트로 반환
s5 = re.findall('[0-9]+',str)
print(s5)
# ['0902']
print('-'*30)
# 정규표현 패턴 알아보기
str = 'My id number is 김_kim_0502$'
# 소문자,대문자, 숫자(문자 단위)
a = re.findall('[a-zA-Z0-9]',str)
print(a)
# ['M', 'y', 'i', 'd', 'n', 'u', 'm', 'b', 'e', 'r', 'i', 's', 'k', 'i', 'm', '0', '5', '0', '2']
# 소문자,대문자, 숫자(단어단위)
b = re.findall('[a-zA-Z0-9]+',str)
print(b)
# ['My', 'id', 'number', 'is', 'kim', '0502']
# ^(not),소문자,대문자, 숫자가 아닌 문자들(공백문자, 특수문자)
c = re.findall('[^a-zA-Z0-9]+',str)
print(c)
# [' ', ' ', ' ', ' ', '_', '$']
# 영문자, 숫자, _
d = re.findall('[\w]',str)
print(d)
# ['M', 'y', 'i', 'd', 'n', 'u', 'm', 'b', 'e', 'r', 'i', 's', 'k', 'i', 'm', '_', '0', '5', '0', '2']
# 영문자, 숫자, _, 단어단위
e = re.findall('[\w]+',str)
print(e)
# ['My', 'id', 'number', 'is', 'kim_0502']
# 영문자, 숫자, _ 가 아닌경우
f = re.findall('[\W]',str)
print(f)
# [' ', ' ', ' ', ' ', '$']
print('-'*30)
# 비밀번호 정합성 체크 함수
def pwd_check(pwd):
# 비밀번호 길이 확인 (6~12)
if len(pwd) < 6 or len(pwd) > 12:
print('비밀번호의 길이가 적당하지 않습니다.')
return False
# 숫자 혹은 알파베스 유무 확인
# 특수문자 걸러짐. 영문자, 숫자만
# findall() 리스트로 리턴. [0] 첫번째 요소밖에 없다.
if re.findall('[a-zA-Z0-9]+',pwd)[0] != pwd:
print(pwd, '==> 숫자와 영문자로만 구성되어야 합니다.')
return False
# 알파벳 대문자 확인
# 소문자의 길이가 0이거나 대문자의 길이가 0이면
if len(re.findall('[a-z]',pwd))==0 or len(re.findall('[A-Z]',pwd)) ==0:
print('대문자와 소문자 모두 필요합니다.')
return False
print(pwd, '올바른 비밀번호입니다.')
pwd_check('<PASSWORD>') # 비밀번호의 길이가 적당하지 않습니다.
pwd_check('<PASSWORD>') # 대문자와 소문자 모두 필요합니다.
pwd_check('<PASSWORD>*') # 숫자와 영문자로만 구성되어야 합니다.
pwd_check('<PASSWORD>') # xcv467rtA 올바른 비밀번호입니다.
print('-'*30)
# Email 주소 체크
def email_check(email):
# ^ []시작 , [^]not, $끝
# {2,}2글자 이상
# ^[a-z0-9]{2,} 소문자 또는 숫자 2글자 이상
# .[a-z]{2,}$ . 후에 소문자영자로 시작해서 2글자 이상으로 끝난다.
exp=re.findall('^[a-z0-9]{2,}@[a-z0-9]{2,}\.[a-z]{2,}$',email)
if len(exp) == 0:
print(email, '잘못된 이메일 형식')
return
print(email,'올바른 이메일 주소')
return
email_check('<EMAIL>')
email_check('<EMAIL>')
email_check('kim')
email_check('<EMAIL>')
print('-'*30)<file_sep>import sqlite3
conn = sqlite3.connect('database_new.db')
c = conn.cursor()
c.execute('UPDATE users SET username = ? WHERE id = ?', ('niceman',11))
conn.commit()
c.execute('UPDATE users SET username = :name WHERE id = :id', {'name': 'goodman', 'id': 12})
conn.commit()
c.execute("UPDATE users SET username = '%s' WHERE id = '%s'" % ('badman','13'))
conn.commit()
c.execute("DELETE FROM users WHERE id = ?",(14,))
conn.commit()
conn.close()<file_sep>from flask import Flask, render_template, request, Blueprint
from blue1 import blue100
from blue2 import blue200
app = Flask(__name__, template_folder='view')
# blue print 등록
app.register_blueprint(blue100)
app.register_blueprint(blue200)
@app.route('/test1')
def test1() :
html = render_template('sub1/test1.html')
return html
@app.route('/test2')
def test2() :
html = render_template('sub2/test3.html')
return html
app.run(host='0.0.0.0', port=80)<file_sep>import random
n = random.randint(1,100)
print(n)
while 1:
ans = input("Guess my number (1~100)? (Q to EXIT) :")
if ans.upper() == 'Q':
break
ans = int(ans)
if n == ans :
print("Correct!")
break
elif n > ans :
print('UP!')
else : print('DOWN!')<file_sep>from flask import Flask, render_template, request, session
import database as db
app = Flask(__name__, template_folder='view')
app.secret_key='<KEY>'
@app.route('/')
def index() :
html = render_template('index.html')
return html
@app.route('/about')
def about() :
return 'about page'
@app.route('/student_list')
def student_list() :
stu_name = request.args.get('stu_name')
stu_list = db.get_student_list(stu_name)
html = render_template('student_list.html', data_list=stu_list)
return html
@app.route('/show_point')
def show_point() :
html = render_template('show_point.html')
return html
@app.route('/student_info', methods=['get', 'post'])
def student_info() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
# 학생 데이터를 가져온다.
result_dic = db.get_student_info(stu_idx)
# 학생 점수를 가져온다.
result_list = db.get_point(stu_idx)
html = render_template('student_info.html', data_dic=result_dic, data_list=result_list)
return html
@app.route('/add_student')
def add_student() :
html = render_template('add_student.html')
return html
@app.route('/add_point')
def add_point() :
# 파라미터 데이터 추출
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('add_point.html', data_dic=temp_dic)
return html
@app.route('/add_student_pro', methods=['post'])
def add_student_pro() :
# 파라미터 데이터 추출한다.
stu_name = request.form['stu_name']
stu_age = request.form['stu_age']
stu_addr = request.form['stu_addr']
# print(f'{stu_name} {stu_age} {stu_addr}')
# 저장한다.
idx = db.add_student(stu_name, stu_age, stu_addr)
result_dic = { 'stu_idx' : idx,
'msg' : '학생등록이 완료되었습니다'}
html = render_template('add_student_pro.html', data_dic=result_dic)
return html
@app.route('/add_point_pro', methods=['post'])
def add_point_pro() :
# 파라미터 추출
point_stu_grade = request.form['point_stu_grade']
point_stu_kor = request.form['point_stu_kor']
point_stu_idx = request.form['point_stu_idx']
# 점수 정보 저장
db.add_point(point_stu_idx, point_stu_grade, point_stu_kor)
temp_dic = {}
temp_dic['stu_idx'] = point_stu_idx
html = render_template('add_point_pro.html', data_dic=temp_dic)
return html
@app.route('/login', methods=['get','post'])
def login() :
html = render_template('login.html')
return html
@app.route('/login_pro', methods=['get','post'])
def login_pro() :
id = request.form['id']
pwd = request.form['pwd']
session['m_session'] = db.login(id,pwd)
html = render_template('login_pro.html')
return html
@app.route('/register', methods=['GET', 'POST'])
def register():
html = render_template('register.html')
return html
@app.route('/register_pro', methods=['GET', 'POST'])
def register_pro():
# 파라미터 추출
id = request.form['id']
pwd = request.form['pwd']
# 점수 정보 저장
db.register(id,pwd)
html = render_template('register_pro.html')
return html
@app.route('/logout', methods=['get','post'])
def logout() :
session['m_session'] = False
html = render_template('index.html')
return html
@app.route('/modify_student', methods=['GET', 'POST'])
def modify_student() :
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('modify_student.html',data_dic=temp_dic)
return html
@app.route('/modify_student_pro', methods=['GET', 'POST'])
def modify_student_pro() :
idx = request.form['stu_idx']
name = request.form['stu_name']
age = request.form['stu_age']
addr = request.form['stu_addr']
db.modify(idx, name, age,addr)
temp_dic = {}
temp_dic['stu_idx'] = idx
html = render_template('modify_student_pro.html',data_dic=temp_dic)
return html
@app.route('/delete_student', methods=['GET', 'POST'])
def delete_student() :
stu_idx = request.args.get('stu_idx')
temp_dic = {}
temp_dic['stu_idx'] = stu_idx
html = render_template('delete_student.html', data_dic=temp_dic)
return html
@app.route('/delete_student_pro', methods=['GET', 'POST'])
def delete_student_pro() :
idx = request.form['stu_idx']
db.delete_student(idx)
html = render_template('delete_student_pro.html')
return html
app.run(host='127.0.0.1', port=8080)<file_sep># 1. 반복문, 조건문, 함수를 활용하여 주어진 정수 리스트의 최대값을 출력하는 함수를 만들어보세요.
# 주어진 함수는 주어진 리스트 A 를 입력값으로 받습니다.
# if문의 적절한 조건을 추가해 봅시다. (max와 리스트내의 값들을 순서대로 비교)
# 리스트의 값이 max보다 클 때 max를 그 리스트의 값으로 바꿉니다.
def maxFunc(mlist) :
max = 0
for i in mlist :
if max < i:
max = i
return max
A = [1, 2, 3, 4, 5, 6, 73, 8, 10, 54]
maxNum = maxFunc(A)
print (maxNum)
# 2. 다음 조건에 맞는 함수를 작성해보세요.
# 함수의 이름은 자유롭게 정합니다.
# a, b를 입력값으로 받습니다.
# 함수 내에서 list 자료형에 a + b, a - b, a * b를 저장한다.
# 위에서 저장한 list 를 리턴합니다.
def cal(a,b) :
mlist = [a+b,a-b,a*b]
return mlist
print(cal(2,3))
# 3. 한 개 또는 두 개의 숫자 인자를 전달받아,
# 하나가 오면 제곱, 두개를 받으면 두 수의 곱을 반환해주는 함수를 정의하고 사용해본다.
def cal2(a,b=False) :
num = 0
if b is not False :
num = a*b
else : num = a* a
return num
print(cal2(3,1))
print(cal2(3))
def calc(*args):
num = len(args)
if not(num ==1 or num ==2):
raise ValueError('인자는 1개나 2개만 입력하셈')
if num == 1:
return args[0] ** 2
elif num == 2:
return args[0] * args[1]
print(calc(3,1))
print(calc(3))
def calc2(x, y =None) :
return x * (y if y else x)
print(calc2(3,1))
print(calc2(3))
# 4. 매개변수로 문자열을 받고, 해당 문자열이 red면 apple을,
# yellow면 banana를, green이면 melon을, 어떤 경우도 아닐 경우
# I don’t know를 리턴하는 함수를 정의하고,
# 이 함수를 사용하여 result 변수에 결과를 할당하고 print 해본다.
def chk(str):
'''색깔 문자열을 입력하면
대응하는 과일 이름을 출력하는 함수'''
if str == 'red' :
return 'apple'
elif str == 'yellow' :
return 'banana'
elif str == 'green' :
return 'melon'
else :
return 'I don’t know'
result = chk('yellow')
print(result)
help(chk)<file_sep>import pymysql
# 데이터 베이스에 접속하는 함수
def get_connection() :
conn = pymysql.connect(host='127.0.0.1', user='root',
password='<PASSWORD>', db='flask_db'
, charset='utf8')
return conn
# 학생 목록을 가져오는 함수
def get_student_list(stu_name) :
# 데이터베이스 접속
conn = get_connection()
# 쿼리문
sql = '''select stu_idx, stu_name, stu_age, stu_addr
from student_table'''
if stu_name != None and len(stu_name) > 0 : # 검색어가 있을 경우
sql += ' where stu_name like %s'
sql += ' order by stu_idx desc'
# 쿼리문 실행
cursor = conn.cursor()
if stu_name != None and len(stu_name) > 0 :
cursor.execute(sql, (f'%{stu_name}%'))
else :
cursor.execute(sql)
# 결과를 가져온다.
result = cursor.fetchall()
# 데이터를 추출한다.
temp_list = []
for row in result :
temp_dic = {}
temp_dic['stu_idx'] = row[0]
temp_dic['stu_name'] = row[1]
temp_dic['stu_age'] = row[2]
temp_dic['stu_addr'] = row[3]
temp_list.append(temp_dic)
conn.close()
return temp_list
# 학생 정보를 저장한다.
def add_student(stu_name, stu_age, stu_addr) :
# 쿼리문
sql = '''insert into student_table
(stu_name, stu_age, stu_addr)
values (%s, %s, %s)'''
# 데이터 베이스 접속
conn = get_connection()
# 쿼리 실행
cursor = conn.cursor()
cursor.execute(sql, (stu_name, stu_age, stu_addr))
conn.commit()
# 방금 저장한 학생의 번호를 가져온다.
sql2 = 'select max(stu_idx) from student_table'
cursor.execute(sql2)
result = cursor.fetchone()
idx = result[0]
# 접속 종료
conn.close()
return idx
# 학생 한명의 정보를 가져오는 함수
def get_student_info(stu_idx) :
# 쿼리문
sql = '''select stu_name, stu_age, stu_addr
from student_table
where stu_idx = %s'''
# 접속
conn = get_connection()
# 쿼리 실행
cursor = conn.cursor()
cursor.execute(sql, (stu_idx))
result = cursor.fetchone()
# 데이터 추출
result_dic = {}
result_dic['stu_idx'] = stu_idx
result_dic['stu_name'] = result[0]
result_dic['stu_age'] = result[1]
result_dic['stu_addr'] = result[2]
conn.close()
return result_dic
# 점수 정보를 저장한다.
def add_point(point_stu_idx, point_stu_grade, point_stu_kor) :
# 쿼리문
sql = '''insert into point_table
(point_stu_idx, point_stu_grade, point_stu_kor)
values (%s, %s, %s)'''
# 데이터베이스 접속
conn = get_connection()
# 쿼리 실행
cursor = conn.cursor()
cursor.execute(sql, (point_stu_idx, point_stu_grade, point_stu_kor))
conn.commit()
conn.close()
# 학생 점수 가져오기
def get_point(stu_idx) :
# 쿼리문
sql = '''select point_stu_grade, point_stu_kor
from point_table
where point_stu_idx=%s
order by point_stu_grade'''
# 접속
conn = get_connection()
# 쿼리 실행
cursor = conn.cursor()
cursor.execute(sql, (stu_idx))
result = cursor.fetchall()
# 데이터 추출
result_list = []
for result_dic in result :
temp_dic = {}
temp_dic['point_stu_grade'] = result_dic[0]
temp_dic['point_stu_kor'] = result_dic[1]
result_list.append(temp_dic)
conn.close()
return result_list
<file_sep>
print('hello', end=', ')
print('hello', end=', ')
print('hello', sep='\n')
# shift alt e
# ctrl /
print('hello', 'hello','hello', sep='')
# \b 백스페이스 \r 맨 앞쪽으로 커서 보내기
print('I\'m XXX') # \' '출력
print("I'm XXX")
print("I'm \"XXX\"") #쌍이 맞아야 함
#아스키값 받나?
a = b = 1
print(type(a), id(a), id(b), a is b) #type 자료형, id 참조값
print(a is b) #레퍼런스 값이 같니?
print(a == b) #값이 같니?
print(a)
print(b)
b=2
print(id(a), id(b))
print(a,b)
print(a is b)
print(a == b)
a, b = b, a #swap 이 이렇게 된다
print("a: ", a,"b: ",b)
import this
import keyword
print(keyword.kwlist)
print(len(keyword.kwlist))
a = None
#del(a) #변수 삭제
print(a,b)
a = 'A'
print('%d %c', a, a) #?????????
#a = input("What is your name? ") #다 문자열임
print(a)
print(ord(a)) #아스키 문자 -> 숫자
print(chr(ord(a))) #아스키 숫자 -> 문자
import sys
print(sys.maxsize) #2147483647
print(sys.maxsize +1) #2147483648
num = 231412341234124132412341234
print(num, type(num))
num2 = 2*5*3.14
print(num2,type(num2)) #31.400000000000002 0.000000000000002 기본소수 15자리 표현, 부동소숫점 오차
#복소수 j
print(sys.stdout.encoding)
print(sys.stdin.encoding) #인코딩 : UTF-8
print(
"""
asdfasdfas
asdfasdfasdf
asdfasdfsadf
""")
"""여러줄 주석
도됨
쿼리 문 작성할 때 좋다"""
a = (100 == 100)
b = (10 > 100)
print(a,b)
#a = input("number")
#b = input("number2")
print(a+b)
print(int(a)+int(b))
a = 2**3 #2의 3승
a = 7//4 #나눗셈의 몫
# && -> and || -> or
print("Python" + "3.7")
print("Python", 3.7)
print("*" * 50)
a = 'Life is too short, You need Python'
print(a[0], a[12], a[-1]) #index
print(a[0:4], a[5:7]) #slicing 0부터 3까지 5부터 6까지
a = '20190703Rainy'
date = a[:8]
print(date, a[8:] , a[8:len(a)-1])
print(a[0:12:3]) #interval 건너뛰기
addr1 = '서울시'
addr2 = '서초구'
addr3 = '역삼동'
addr4 = '멀티로 123'
print(addr1, addr2, addr3, addr4)
print(addr1 +' '+ addr2 +' '+ addr3 +' '+ addr4)
print("우리집 주소는 {0} {1} {2} {3}". format(addr1, addr2, addr3, addr4)) #format 튜플타입
print("우리집 주소는 {} {} {} {}". format(addr1, addr2, addr3, addr4))
print("우리집 주소는 {0} {1} {2} {0}". format(addr1, addr2, addr3)) #번호를 주는게 좋음
print("%s %s" % (addr1, addr2))
print("%10s %s" % (addr1, addr2))
print("{0:d} {1:5d} {2:05d}". format(123, 123, 123)) #데이터 분석할 때 씀
print('value1: {a}, value2: {b}'. format(a = 'dog',b = 20)) #콕콕 찝어주기
a = 'A'
print("%d %c" % (ord(a),a))
a = 'hobby'
print(a.count('b')) #갯수 찾기, 있는지 없는지 찾을 때 씀
a = " Python is best choice"
print(a.find('b'), a.find('k')) #위치 값 반환, 없으면 -1
print(a.index('t'))
#print(a.index('k')) #인덱스는 없으면 오류가 남
b = '@'
print(b.join('abcd'))
print(b.join('abcd').split('@'))
print(a.split())
print(a.upper(), a.upper().lower(), a.strip(), a.replace(" ",""), a.replace("best","worst"), sep='\n') #대소문자, 공백 없애기, 바꾸기
a = "Pithon"
print(a)
#a[1] = 'y' # 이거 안됨
a = a[:1] + 'y' + a[2:]
print(a)
stName3 = stName4 = '기생충'
print(stName3 == stName4)
print(stName3 is stName4)
a = b = 10
print(a is b)
c = 10
print(a is c)
beer = input()
if(beer is 'cass'):
print ('cass is favorite beer!') #실행안됨
if(beer == 'cass'):
print ('cass is favorite beer!') #실행됨
num = int(input())
if(num is 7):
print ('My favorite number is 7')
hong = '881120-1068234'
print(hong[:6],hong[-7:])<file_sep>{% extends "layout.html" %}
{% block content %}
<div class="container">
<h1>홍길동 점수</h1>
<h3>1학년 : 80점</h3>
<h3>2학년 : 70점</h3>
<h3>3학년 : 60점</h3>
<h3>
<a href="student_list">목록보기</a>
</h3>
</div>
{% endblock %} | 321da78dacd95ce19d91e71363f7ca9b2b26c693 | [
"SQL",
"Python",
"HTML"
] | 79 | Python | 2hwan/multicampus | 0a0efaab0a8de36b7c8b070d2f6423f28527ae87 | b304517d66d54fbf866f6cd48a5d339ca72a1087 |
refs/heads/master | <repo_name>mohankumaru/java9<file_sep>/8th.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ITreturns extends HttpServlet {
private static final long serialVersionUID = 1L;
public ITreturns() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name=request.getParameter("name");
String gender=request.getParameter("gender");
String salary=request.getParameter("salary");
String tax=request.getParameter("tax");
PrintWriter out=response.getWriter();
File file = new File("/home/mahen/1.txt");
file.createNewFile();
FileOutputStream fout = new FileOutputStream(file);
out.println(""+name+gender+salary+tax);
fout.write(("hello"+name+gender+salary+tax).getBytes());
fout.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
info.jsp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<html>
<head>
<meta http-equiv="Content- Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="ITreturns" method="get" >
name:<input type="text" name="name"/>
<select name="gender">
<option>male</option>
<option>fe</option>
</select>
sal:<input type="text" name="salary"/>
tax:<input type="text" name="tax"/>
<input type="submit"/>
</form>
</body>
</html><file_sep>/6th.java
public class myFrame extends JFrame
{
myFrame()
{
super("My Jframe Example");
JLabel jlrep = new JLabel("Representative Information");
JLabel jl11 = new JLabel("Enter RepNo");
final JTextField jtf11 = new JTextField();
JLabel jl12 = new JLabel("Enter RepName");
final JTextField jtf12 = new JTextField();
JLabel jl13 = new JLabel("Enter State");
final JTextField jtf13 = new JTextField();
JLabel jl14 = new JLabel("Enter Commission");
final JTextField jtf14 = new JTextField();
JLabel jl15 = new JLabel("Enter Rate");
final JTextField jtf15 = new JTextField();
JButton jb1 = new JButton("Submit");
JLabel jlcus = new JLabel("Customer Information");
JLabel jl21 = new JLabel("Enter CustomerNo");
final JTextField jtf21 = new JTextField();
JLabel jl22 = new JLabel("Enter CustomerName");
final JTextField jtf22 = new JTextField();
JLabel jl23 = new JLabel("Enter State");
final JTextField jtf23 = new JTextField();
JLabel jl24 = new JLabel("Enter Credit limit");
final JTextField jtf24 = new JTextField();
JLabel jl25 = new JLabel("Enter RepNo");
final JTextField jtf25 = new JTextField();
JButton jb2 = new JButton("Submit");
JPanel panel = new JPanel();
final JTextArea jta = new JTextArea();
jta.setRows(10);
jta.setColumns(5);
JButton jb3 = new JButton("click");
panel.add(jl11);
panel.add(jtf11);
panel.add(jl12);
panel.add(jtf12);
panel.add(jl13);
panel.add(jtf13);
panel.add(jl14);
panel.add(jtf14);
panel.add(jl15);
panel.add(jtf15);
panel.add(jb1);
panel.add(jl21);
panel.add(jtf21);
panel.add(jl22);
panel.add(jtf22);
panel.add(jl23);
panel.add(jtf23);
panel.add(jl24);
panel.add(jtf24);
panel.add(jl25);
panel.add(jtf25);
panel.add(jb2);
panel.add(jta);
panel.add(jb3);
jb1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Statement stmt;
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "deek");
if (conn != null)
{
System.out.println("Connection successful !!!");
String Repno = jtf11.getText();
String Repname = jtf12.getText();
String state = jtf13.getText();
String commission = jtf14.getText();
String rate = jtf15.getText();
stmt = (Statement) conn.createStatement();
System.out.println(Repno + Repname + state + commission);
String query1 = "insert into Representative values('"
+ Repno + "','" + Repname + "','" + state
+ "','" + commission + "','" + rate + "');";
stmt.executeUpdate(query1);
}
else
System.out.println("Connection not successful !!!");
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
catch (ClassNotFoundException exx)
{
System.out.println(exx.getMessage());
}
}
});
jb2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Statement stmt2;
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "deek");
if (conn != null)
{
System.out.println("Connection successful !!!");
String Custno = jtf21.getText();
String CustName = jtf22.getText();
String state = jtf23.getText();
String Credit = jtf24.getText();
int cr = Integer.parseInt(Credit);
String Rno = jtf25.getText();
stmt2 = (Statement) conn.createStatement();
System.out.println(Custno + CustName + state + cr + Rno);
String query2 = "insert into Customer values('"+ Custno + "','" +
CustName + "','" + state+ "','" + cr + "','" + Rno + "');";
stmt2.executeUpdate(query2);
}
else
System.out.println("Connection not successful !!!");
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
catch (ClassNotFoundException exx)
{
System.out.println(exx.getMessage());
}
}
});
jb3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Statement stmt;
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "deek");
if (conn != null)
{
stmt = (Statement) conn.createStatement();
String query3="SELECT * FROM Representative
WHERE RepNo IN (SELECT RepNo FROM Customer WHERE Credit_Limit > 15000 )";
ResultSet rs = stmt.executeQuery(query3);
while (rs.next())
{
jta.append("Representative Information");
jta.append("\n");
jta.append("Number:");
jta.append(rs.getString("RepNo"));
jta.append("\n");
jta.append("Name:");
jta.append(rs.getString("RepName"));
jta.append("\n");
jta.append("State:");
jta.append(rs.getString("State"));
jta.append("\n");
jta.append("Comission:");
jta.append(rs.getString("Comission"));
jta.append("\n");
jta.append("Rate:");
jta.append(rs.getString("Rate"));
jta.append("\n");
}
System.out.println("Connection successful !!!");
}
else
System.out.println("Connection not successful !!!");
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
catch (ClassNotFoundException exx)
{
System.out.println(exx.getMessage());
}
}
});
setContentPane(panel);
}
public static void main(String[] args) {
myFrame mf = new myFrame();
mf.getContentPane().setLayout(
new BoxLayout(mf.getContentPane(), BoxLayout.Y_AXIS));
mf.setVisible(true);
mf.setDefaultCloseOperation(EXIT_ON_CLOSE);
mf.pack();<file_sep>/7th.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
public class ProgressBar extends JFrame implements ActionListener
{
private JProgressBar jp = new JProgressBar();
private JButton jb = new JButton("Copy");
private JButton jc = new JButton("Cancel");
private JTextField fromFile = new JTextField();
private JTextField toFile = new JTextField();
private ProgressBarThread thread;
public static void main(String[] args) // creating the frame application
{
ProgressBar application = new ProgressBar();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setTitle("Copy file");
application.setSize(400, 180);
application.setVisible(true);
}
public ProgressBar() // class constructor
{
Container pane = getContentPane(); // building the GUI
pane.setLayout(new BorderLayout());
jp.setStringPainted(true); // display style of the progress bar
pane.add(jp, BorderLayout.NORTH);
JPanel panel1 = new JPanel(new BorderLayout());
panel1.setBorder(new TitledBorder("From:"));
panel1.add(fromFile, BorderLayout.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBorder(new TitledBorder("To:"));
panel2.add(toFile, BorderLayout.CENTER);
JPanel panel3 = new JPanel(new GridLayout(2,1));
panel3.add(panel1);
panel3.add(panel2);
pane.add(panel3, BorderLayout.CENTER);
JPanel panel4 = new JPanel();
panel4.add(jb);
panel4.add(jc);
pane.add(panel4, BorderLayout.SOUTH);
jb.addActionListener(this);
jc.addActionListener(this);
jc.setEnabled(false);
}
public void actionPerformed(ActionEvent e) // buttons events processing
{
if (e.getSource() == jb)
{
thread = new ProgressBarThread(this, jp, fromFile, toFile);
thread.start();
jb.setEnabled(false);
jc.setEnabled(true);
}
else if (e.getSource() == jc)
{
thread.cancel = true;
jc.setEnabled(false);
}
}
}
class ProgressBarThread extends Thread
{
private JFrame frame;
private JProgressBar jp;
private JTextField fromFile;
private JTextField toFile;
public boolean cancel = false;
public ProgressBarThread(JFrame f, JProgressBar jp,
JTextField from, JTextField to)
{
frame = f; // thread constructor
this.jp = jp;
fromFile = from;
toFile = to;
}
public void run()
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
File inFile = new File(fromFile.getText().trim()); // input stream
in = new BufferedInputStream(new FileInputStream(inFile));
File outFile = new File(toFile.getText().trim()); // output stream
out = new BufferedOutputStream(new FileOutputStream(outFile));
long fileSize = in.available(); // input file size in bytes
jp.setValue(0); // set up the progress bar
jp.setMaximum(100); // indicator
int r = 0;
long bytesRead = 0;
byte[] buffer = new byte[5]; // read/write buffer
while ((r = in.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, r); // write to the file
bytesRead += r;
int copyProgress = (int) (bytesRead*100.0/fileSize);
jp.setValue(copyProgress); // update the indicator
if (cancel) return; // kill the thread
}
}
catch(FileNotFoundException e)
{
JOptionPane.showMessageDialog(frame, "File not found",
"Error message", JOptionPane.ERROR_MESSAGE);
}
catch(IOException e)
{
JOptionPane.showMessageDialog(frame, "Cannot write to file",
"Error message", JOptionPane.ERROR_MESSAGE);
}
finally // close the files
{
try
{
if (in != null) in.close();
if (out != null) out.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(frame, "I/O error",
"Error message", JOptionPane.ERROR_MESSAGE);
}
}
}
}
<file_sep>/10th.java
JDBClogin.java
~~~~~~~~~~~~~~~~~~~~~~~~
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
@WebServlet(urlPatterns={"/javaConnection"})
public class JDBClogin extends HttpServlet {
static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/onlinedirectory";
String username = "root";
String password = "<PASSWORD>;;
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,
password);
return conn;
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
PrintWriter out = response.getWriter();
//out.print("Working");
boolean flag = false;
Connection conn = null;
Statement stmt = null;
java.sql.ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
out.print("Working");
long inp;
try
{
inp =Long.parseLong(request.getParameter("phone"));
out.println(""+inp);
rs = stmt.executeQuery("SELECT * FROM tele_dir where
contact="+inp);
}
catch(Exception e)
{
String name=request.getParameter("phone");
// out.println(""+name);
rs = stmt.executeQuery("SELECT * FROM tele_dir where
name='"+name+"'");
}
if(rs.next()) {
String name = rs.getString(1);
long contact = rs.getLong(2);
String address = rs.getString(3);
String company = rs.getString(4);
int pin =rs.getInt(5);
out.println("name"+name);
out.println("contact:"+contact);
out.println("address:"+address);
out.println("company:"+company);
out.println("pin:"+pin);
}
else
{
out.println("no contact found");
}
} catch (ClassNotFoundException e) {
System.out.println("Error: failed to load MySQL driver.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Error: failed to create a connection
object.");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error: unknown");
e.printStackTrace();
}
finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~
insert1.java
~~~~~~~~~~~~~~~~~~~~~~~~
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/ins" })
public class insert1 extends HttpServlet {
static Connection getConn() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/onlinedirectory";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,
password);
return conn;
}
Connection conn1 = null;
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException {
PrintWriter out = response.getWriter();
// out.print("Working");
boolean flag = false;
Connection conn = null;
Statement stmt = null;
java.sql.ResultSet rs = null;
try {
// conn = getConn();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/onlinedirectory";
String username = "root";
String password = "<PASSWORD>;;
Class.forName(driver);
conn1 = DriverManager.getConnection(url, username,
password);
if (conn1 != null)
System.out.println("Successful");
stmt = conn1.createStatement();
out.print("Working");
String name = request.getParameter("nam");
long contact = Long.parseLong(request.getParameter("cnt"));
String address = request.getParameter("address");
String company = request.getParameter("company");
int pin = Integer.parseInt(request.getParameter("pin"));
out.println("name" + name);
out.println("contact:" + contact);
out.println("address:" + address);
out.println("company:" + company);
out.println("pin:" + pin);
stmt.executeUpdate("insert into tele_dir values('" + name +
"'," + contact + ",'" + address + "','" + company + "'," + pin + ");");
out.println("updated the records");
} catch (ClassNotFoundException e) {
System.out.println("Error: failed to load MySQL driver.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Error: failed to create a connection
object.");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error: unknown");
e.printStackTrace();
} finally {
try {
stmt.close();
conn1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~
Index.jsp
~~~~~~~~~~~~~~~~~~~~~~~~
<html>
<head>
<meta http-equiv="Content- Type" content="text/html; charset=ISO-8859- 1">
<title>Insert title here</title>
</head>
<body>
<form action="javaConnection" method="get"/>
Enter name or phone:<input type="text" name="phone" /><br/>
<input type="submit" />
</form>
<a href="insert.html;">insert into directory</a>
</body>
</html>
~~~~~~~~~~~~~~~~~~~~~~~~
insert.html
~~~~~~~~~~~~~~~~~~~~~~~~
<html>
<head>
<meta charset="ISO-8859- 1">
<title>Insert title here</title>
</head>
<body>
<form action="ins" method="get" >
name:<input type="text" name="nam" /><br/>
contact:<input type="text" name="cnt" /><br/>
address:<input type="text" name="address" /><br/>
company:<input type="text" name="company" /><br/>
pincode:<input type="text" name="pin" />
<input type="submit" />
</form>
</body>
</html>
| 5befc2411691fdb512c3501b1aa2eef045117e0f | [
"Java"
] | 4 | Java | mohankumaru/java9 | c6beceaae98cd3d90c60c812ed49025de06dd1c0 | 920251bc5af98381776a9ca52d0bedcbaeb62a6e |
refs/heads/master | <repo_name>rimDas09/Rimjim-0304<file_sep>/dataVisualization.py
import pandas as pd
import numpy as np
from Cython import inline
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
from kmeans import run_kmeans
data = pd.read_csv('data-sample-clinton-50k.csv')
print(data.head())
km = KMeans(n_clusters=5, init='k-means++', n_init=10)
km.fit(df1)
| 28ae3435e9c97fb675952e5c79ac997730d0fb70 | [
"Python"
] | 1 | Python | rimDas09/Rimjim-0304 | 3150a8d2d360c0a28afb27086145236f0e3a0678 | a6e3760649242f4479f4e2415c3babf701976a2a |
refs/heads/master | <repo_name>miquecg/ansible-roles<file_sep>/containers/archlinux/README.md

Arch Linux container
====================
Creates an Arch Linux container from latest bootstrap tarball available.
Requirements
------------
This role uses [`buildah`](https://github.com/containers/buildah/blob/master/install.md), a tool for building OCI images.
Elevated privileges are needed to create the root filesystem.
Role Variables
--------------
### defaults
```yaml
archive_url: https://archive.archlinux.org/iso
download_path: "{{ playbook_dir }}"
```
### optional
**`main_mirror`**
Configure the mirror that pacman will try to use first.
```yaml
- include_role:
name: arch_container
vars:
main_mirror: https://osl.ugr.es/archlinux
```
### created
**`bootstrap_release`**
Date formatted as '%Y.%m.01'.
**`working_container`**
Container name. Dynamically allocated to avoid collisions with any other existing container in the environment (e.g. previously created by this role).
License
-------
See [LICENSE](https://github.com/miquecg/ansible-roles/blob/master/LICENSE).
<file_sep>/README.md
# Ansible roles
On my way to learn Ansible I wrote my very first role inside the project that uses it. Because it's in roles' nature to be reusable, there is a good reason to have a dedicated repository for them.
<file_sep>/containers/archlinux/filter_plugins/date.py
from datetime import timedelta
from functools import reduce, wraps
def formatted(func):
@wraps(func)
def date_with_format(*args, **kwargs):
format = kwargs.pop('fmt', '%Y.%m.%d')
date = func(*args, **kwargs)
return date.strftime(format)
return date_with_format
@formatted
def move_date(date, months_back=0):
new_month = change_month(date, months_back)
return change_day_to_first(new_month)
def change_month(date, months_back):
times = max(0, months_back)
return reduce(lambda new_date, _: change_day_to_first(new_date) - timedelta(days=1), range(times), date)
def change_day_to_first(date):
return date.replace(day=1)
class FilterModule(object):
def filters(self):
return {
'day_one': move_date
}
<file_sep>/common/README.md

Common setup
============
Common system setup tasks.
Tasks
-----
`main.yml` does not include any. Load them on your playbook using `tasks_from`.
- locale
- timezone
Role Variables
--------------
### defaults
```yaml
system_locale: en_US.UTF-8
```
### required
**`timezone`**
Must be a valid timezone available at `/usr/share/zoneinfo` (e.g. Europe/Berlin).
### optional
**`locale`**
Alternative locale to generate on the system. When this value is supplied no system locale is set.
License
-------
See [LICENSE](https://github.com/miquecg/ansible-roles/blob/master/LICENSE).
| 16cf43c978ce498c4f53289a076829534893da12 | [
"Markdown",
"Python"
] | 4 | Markdown | miquecg/ansible-roles | e435648becfd7b338814979e41994a1bc5dc8fcc | 937186d80b876cbe02bcec3048e458703d7162c9 |
refs/heads/master | <file_sep>#!/usr/bin/python3
import requests
import zipfile
import os
import pandas as pd
import numpy as np
from io import BytesIO
def download_cia_aberta_ITR(years, folder = "./"):
"""
This function downloads ITR historical for the range of years inserted.
The individual files are saved in the folder provided as variable.
Args:
years: range of years to download the information
folder: a path to the desired folder in which the files will be downloaded into. If folder doesn't exist, will be created
"""
base_url = "http://dados.cvm.gov.br/dados/CIA_ABERTA/DOC/ITR/DADOS/ITR_CIA_ABERTA_"
for i in years:
request_itr = requests.get(base_url + str(i) + ".zip")
zip_itr = zipfile.ZipFile(BytesIO(request_itr.content))
for j in zip_itr.namelist():
zip_itr.extract(j, folder)
new_file_name = j.lower()
os.rename(folder + j, folder + new_file_name)
def download_cia_aberta_DFP(years, folder = "./"):
"""
This function downloads DFP historical for the range of years inserted.
The individuala files are saved in the folder provided as variable.
Args:
years: range of years to download the information
folder: a path to the desired folder in which the files will be downloaded into. If folder doesn't exist, will be created
"""
tipos = ["BPA","BPP","DFC_MD","DFC_MI","DMPL","DRE","DVA"]
for i in years:
for j in tipos:
url = "http://dados.cvm.gov.br/dados/CIA_ABERTA/DOC/DFP/%s/DADOS/%s_cia_aberta_%s.zip" % (j, j, str(i))
request_dfp = requests.get(url)
zip_dfp = zipfile.ZipFile(BytesIO(request_dfp.content))
for k in zip_dfp.namelist():
zip_dfp.extract(k, folder)
new_file_name = "dfp_" + k.lower()
os.rename(folder + k, folder + new_file_name)
def group_yearly_csv_files( values,
column_name,
files_identifier= "",
remove_from_filename= "",
files_path = "./",
save_path= "./group/"):
"""
This function groups multiples CSV files with equal structure and something commom in their name.
The year must be at the end of each file name and have the YYYY format.
The consolidated files are then saven to the path.
ISO5549-1 encoding is use to save and read the files since they are in portuguese language.
Args:
values: list of values to filter and group files by.
column_name: column to be used to filter and group files.
files_identifier: value present in the name of all files, will be used to distinguish which files to group.
remove_from_filename: string to be removed from the filename. May be used when there is a repated and non-informative string in the name.
files_path: path of the folder containing the ITR documents.
save_path: path of the folder in which the documents will be saved into.
"""
print("oi1")
dir_files = os.listdir(files_path)
print("oi2")
dir_files = [x for x in dir_files if (files_identifier in x)]
print(dir_files)
print("oi3")
files_unique = np.unique([x[:-9] for x in dir_files])
print("oi4")
years_unique = np.unique([x.replace(".csv", "")[-5:] for x in dir_files])
print("oi5")
if not os.path.exists(save_path):
os.mkdir(save_path)
print("oi6")
print(years_unique)
for year in years_unique:
print(year)
for file in files_unique:
print(file)
file_df = pd.read_csv(files_path + file + year + ".csv",
sep= ";",
decimal= ".",
encoding= "iso8859-1")
print(file)
print(year)
# file_df = file_df.loc[file_df["ORDEM_EXERC"] == "ÚLTIMO"]
for i in values:
folder_file_path = save_path + i.replace("/", "-") + "/"
if not os.path.exists(folder_file_path):
os.mkdir(folder_file_path)
filepath = folder_file_path + file.replace(remove_from_filename, "") + ".csv"
company_df = file_df.loc[file_df["CNPJ_CIA"] == i]
if not os.path.isfile(filepath):
header = True
else:
header = False
company_df.to_csv(filepath,
mode= "a",
encoding= "iso8859-1",
index= False,
header= header)
<file_sep>#!/usr/bin/python3
__author__ = "<NAME> @ kaduulson in GitHub"
__version__ = "0.0.1"
from pynance.cvm import download_cia_aberta_ITR, download_cia_aberta_DFP, group_yearly_csv_files<file_sep># pynance
Finance data handled with python. Get data, analyze data and more!
## Pynance
First commit. | 452925576506eba1da774ac1931ae5c7c9493638 | [
"Markdown",
"Python"
] | 3 | Python | KaduUlson/pynancebr | f6545eaa1f2b7a831217d463005c9a67f71cad0d | c2fc25463e296d73c51133de39be7d43ca787099 |
refs/heads/master | <repo_name>mentaal/py_sm<file_sep>/tests.py
from py_sm import State, StateMachine
class StateOne(State):
def exit(self):
super().exit()
self.next_state = 'StateTwo'
class StateTwo(State):
def exit(self):
self.next_state = 'StateOne'
def test_state_execution():
state_machine = StateMachine()
next_state = state_machine.run('StateOne')
for i in range(5):
next_state = state_machine.run(next_state)
<file_sep>/py_sm.py
import logging
logger = logging.getLogger(__name__)
class State:
next_state = None
states = {}
def entry(self):
logger.debug("Entry into %s...", self.__class__.__name__)
def main(self):
logger.debug("Main method for %s...", self.__class__.__name__)
def exit(self):
logger.debug("Exit method for %s...", self.__class__.__name__)
def __init_subclass__(cls, **kwargs):
"add this state the dictionary of possible states"
super().__init_subclass__(**kwargs)
#logger.debug("In __init_subclass__ for: %s", cls.__name__)
print("In __init_subclass__ for: %s" %cls.__name__)
cls.states[cls.__name__] = cls
class StateMachine:
states = {}
def __init__(self):
for s,cls in State.states.items():
self.states[s] = cls()
def run(self, state_name):
state = self.states[state_name]
state.entry()
state.main()
state.exit()
return state.next_state
| de91b8e3d0c6076e3b6e24dcdb3ed4baa54bef2a | [
"Python"
] | 2 | Python | mentaal/py_sm | 4b299de7bf5a7a11412df802b0516a3deedd4319 | 8f025747b7ebb827fa975227cd3085931604c8b5 |
refs/heads/master | <file_sep>package com.ujiuye.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
System.out.println(username);
System.out.println("get方法");
resp.getWriter().println("成功");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("postfangfa");
}
@Override
public void init() throws ServletException {
System.out.println("初始化服务");
}
// @Override
// protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// System.out.println("正在服务");
// }
@Override
public void destroy() {
System.out.println("警察来了,销毁");
}
}
| 968269702c6653ce6452aef33e720ff5ff813b69 | [
"Java"
] | 1 | Java | yogurtyou/day13 | 44693b34a85473232b85780bd9899d7ce63e6f49 | b5484be997ca02dfee118dee2ac06ff7bcdd212a |
refs/heads/main | <repo_name>nerd35/chiixchangetext<file_sep>/src/components/mainContent/topTiltle.jsx
import React from 'react'
import { NewGig, Title, TopTiTleColumn, TopTitleSection } from './main.element'
const TopTiltle = ({setPages, pages}) => {
return (
<TopTitleSection className="px-4 py-3">
<TopTiTleColumn>
<Title>Gigs</Title>
</TopTiTleColumn>
<TopTiTleColumn>
<NewGig onClick={() => setPages(!pages)} className="px-4 py-2">
New gig <i class="fas fa-plus"></i>
</NewGig>
</TopTiTleColumn>
</TopTitleSection>
)
}
export default TopTiltle
<file_sep>/src/components/mainContent/main.element.js
import styled from "styled-components";
import { FaTimes } from "react-icons/fa";
export const MainContentContainer = styled.div`
width: 100%;
@media screen and (max-width: 800px) {
width: 100%;
}
`;
export const NavbarContainer = styled.div`
display: flex;
flex-decoration: row;
align-items: center;
justify-content: space-between;
`;
export const NavbarLeft = styled.div`
display: flex;
flex-direction: row;
align-item: center;
`;
export const NavbarLeftInput = styled.div`
height: 40px;
display: flex;
flex-direction: row;
align-item: center;
border: 1px solid #ececec;
border-radius: 16px;
opacity: 1;
`;
export const NavbarRight = styled.div``;
export const SearchInput = styled.input`
color: #7e7e7e;
outline: none;
box-shadow: none !important;
border: none;
`;
export const NavbarIconContainer = styled.span``;
export const NavbarIcon = styled.img``;
export const SidenavContainer = styled.aside`
position: fixed;
z-index: 999;
width: 350px;
height: 100%;
background: #fff;
display: grid;
align-items: center;
top: 0;
left: 0;
padding: 0 40px;
z-index: 1000;
transition: 0.3s ease-in-out;
border-right: 1px solid #eee;
left: ${({ isOpen }) => (isOpen ? "0" : "-1000px")};
@media screen and (max-width: 400px) {
width: 100%;
}
`;
export const CloseIcon = styled(FaTimes)`
color: #000;
font-weight: 200;
`;
export const Icon = styled.div`
position: absolute;
top: 1.2rem;
right: 1.5rem;
background: transparent;
border: transparent;
font-size: 2rem;
cursor: pointer;
outline: none;
`;
export const NavIcon = styled.div`
display: block;
position: absolute;
cursor: pointer;
`;
export const SidenavLogo = styled.img``;
export const SidenavSection = styled.div`
margin-top: -305px;
`;
export const TopTitleSection = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
`;
export const TopTiTleColumn = styled.div``;
export const Title = styled.h1`
font: normal normal normal 45px/63px Circular Std Bold;
letter-spacing: 0px;
color: #2c263d;
opacity: 0.8;
`;
export const NewGig = styled.span`
width: 153px;
height: 60px;
background: #2f417e 0% 0% no-repeat padding-box;
border: 1px solid #f6f6f6;
border-radius: 15px;
font: normal normal normal 18px/26px Circular Std Book;
letter-spacing: 0px;
color: #ffffff;
opacity: 1;
text-decoration: none;
`;
export const TopTabSection = styled.div`
border-bottom: 1px solid #ececec;
`;
export const TopTabRow = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
overflow-x: auto;
::-webkit-scrollbar {
width: 0em;
height: 0em
}
::-webkit-scrollbar-button {
background: #fff
}
::-webkit-scrollbar-track-piece {
background: #fff
}
::-webkit-scrollbar-thumb {
background: #fff
}
`;
export const TopTabActiveLink = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify_content: flex-start;
border-bottom: 3px solid #fbb30b;
`;
export const TopTabActiveSpan = styled.span`
text-align: left;
font: normal normal normal 20px/28px Circular Std Medium;
width: 80px;
letter-spacing: 0px;
color: #585461;
opacity: 1;
`;
export const TopTabActiveBgSpan = styled.span`
background: #fbb30b 0% 0% no-repeat padding-box;
border-radius: 8px;
font: normal normal bold 14px/17px Graphie;
letter-spacing: 0px;
color: #ffffff;
`;
export const TopTabLink = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify_content: flex-start;
`;
export const TopTabSpan = styled.span`
font: normal normal normal 20px/28px Circular Std Book;
letter-spacing: 0px;
text-align: left;
width: 120px;
color: #585461;
opacity: 0.6;
`;
export const TopTabBgSpan = styled.span`
background: #fdf2e9 0% 0% no-repeat padding-box;
border-radius: 8px;
font: normal normal bold 14px/17px Graphie;
letter-spacing: 0px;
color: #fbb30b;
opacity: 1;
`;
export const GigsCategoryContainer = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
overflow-x: auto;
::-webkit-scrollbar {
width: 0em;
height: 0em
}
::-webkit-scrollbar-button {
background: #fff
}
::-webkit-scrollbar-track-piece {
background: #fff
}
::-webkit-scrollbar-thumb {
background: #fff
}
`;
export const GigsCategoryColumn = styled.div`
border: 1px solid #eeeeee;
border-radius: 15px;
`;
export const GigsCategoryActiveColumn = styled.div`
border: 2px solid #e18700;
border-radius: 17px;
`;
export const GigsText = styled.p`
font: normal normal normal 16px/19px ;
letter-spacing: -0.32px;
color: #bcbcbc;
`;
export const GigsActiveText = styled.p`
font: normal normal normal 16px/19px ;
letter-spacing: -0.32px;
color: #e18700;
`;
export const GigTableContainer = styled.div`
overflow-x: auto;
::-webkit-scrollbar {
width: 0em;
height: 0em
}
::-webkit-scrollbar-button {
background: #fff
}
::-webkit-scrollbar-track-piece {
background: #fff
}
::-webkit-scrollbar-thumb {
background: #fff
}
`;
export const AddGigTitle = styled.h1`
font: normal normal normal 45px/63px Circular Std Bold;
letter-spacing: 0px;
color: #2c263d;
`;
export const AddGigFormSection = styled.div``;
<file_sep>/src/components/mainContent/basicData.jsx
import React from "react";
import "./style.css";
const BasicData = ({ addgigs, setAddGigs, pages, setPages}) => {
return (
<div className="py-3 ">
<div className="row">
<div className="mb-3 col-md-3">
<div className="px-3 py-3 addGigSideContainer">
<h5 className="py-2 GigLink">
<i
className="far fa-circle me-2"
style={{
color: "#E18700",
fontSize: "8px",
fontWeight: "bold",
}}
></i>{" "}
Basic Data
</h5>
<h5 onClick={() => setAddGigs(!addgigs)} className="py-2 GigLinknon ms-3">Renumeration</h5>
</div>
</div>
<div className="col-md-6">
<div className="px-4 py-5 addGigMainContainer">
<form className="form-group">
<div class="row">
<div className="mb-3 col-md-6">
<label className="mb-2 labelText">Role</label>
<input
type="text"
className="form-control inputcontrol1"
placeholder="Product Designer"
aria-label="First name"
/>
</div>
<div className="col-md-6">
<label className="mb-2 labelText">Company</label>
<input
type="text"
className="form-control inputcontrol1"
placeholder="TM30"
aria-label="Last name"
/>
</div>
</div>
<div class="row mt-3">
<div className="col-md-6">
<label className="mb-2 labelText">Location</label>
<select id="inputState" class="form-select selectcontrol" style={{color: '#E5E5E5 !important'}}>
<option selected >Country</option>
<option>...</option>
</select>
</div>
<div className="col-md-6">
<label className="mb-2 text-light labelText">role</label>
<select id="inputState" class="form-select selectcontrol">
<option selected>State/City</option>
<option>...</option>
</select>
</div>
</div>
<div className="mt-3 col-12">
<input type="text" class="form-control addressText" id="inputAddress2" placeholder="Address"/>
</div>
<div className="mt-3 col-12 ">
<label className="mb-2 labelText">Add tags</label>
<div className="px-3 py-3 tagsection">
<span className="px-3 py-2 removetext">Remove <i className="fas fa-times ps-2"></i></span>
<input type="text" placeholder="Add more tags" className="form-control taginput w-50"/>
</div>
<div className="mt-3">
<span className="sugest-tag ">Suggested tags: </span><span className="sug-tags me-2">fulltime</span><span className="sug-tags me-2">Contract</span><span className="sug-tags ">freelance</span>
</div>
</div>
<div className="mt-3 col-12 text-end">
<span onClick={() => setPages(!pages)} className="cancel-text me-3">Cancel</span> <span onClick={() => setAddGigs(!addgigs)} className="px-3 py-2 continue-btn text-light">Continue</span>
</div>
</form>
</div>
</div>
</div>
</div>
);
};
export default BasicData;
<file_sep>/src/components/mainContent/addGigs.jsx
import React, { useState } from "react";
import BasicData from "./basicData";
import { AddGigFormSection, AddGigTitle } from "./main.element";
import Remuneration from "./remuneration";
const AddGigs = ({ pages, setPages }) => {
const [addgigs, setAddGigs] = useState(false)
return (
<>
<div className="py-2" style={{ border: "1px solid #ECECEC" }}>
<AddGigTitle className="px-4">Gigs</AddGigTitle>
</div>
<AddGigFormSection className="px-4 py-3">
<h1
style={{
font: "normal normal normal 25px/35px Circular Std Book",
letterSpacing: "0px",
color: "#565D74",
}}
>
New gig
</h1>
{addgigs ? <Remuneration setPages={setPages} addgigs={addgigs} setAddGigs={setAddGigs} pages={pages}/> : <BasicData setAddGigs={setAddGigs} addgigs={addgigs} setPages={setPages} pages={pages}/>}
</AddGigFormSection>
</>
);
};
export default AddGigs;
<file_sep>/src/components/mainContent/gigsTable.jsx
import React from 'react'
import {GigTableContainer} from './main.element'
import DateIcon from '../../assets/dateicon.png'
const GigsTable = () => {
return (
<GigTableContainer className="px-3 mb-5">
<table class="table table-borderless">
<thead>
<tr style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6"}}>
<th scope="col"></th>
<th scope="col" style={{color: '#514C5D', opacity: "0.5"}}>Role</th>
<th scope="col" style={{color: '#514C5D', opacity: "0.5"}}>Company</th>
<th scope="col" style={{color: '#514C5D', opacity: "0.5"}}>Date<img src={DateIcon} alt="" /></th>
<th scope="col" style={{color: '#514C5D', opacity: "0.5"}}>Salary($)<img src={DateIcon} alt=""/></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr className="py-5" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
<tr className="pt-3 pb-3" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
<tr className="pt-3 pb-3" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
<tr className="pt-3 pb-3" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
<tr className="pt-3 pb-3" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
<tr className="mt-3" style={{boxShadow: "0px 3px 6px #00000003", borderBottom: "1px solid #F6F6F6", padding: " 20px 0px"}}>
<th scope="row"><input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"/></th>
<td>Product Manager</td>
<td>TM30</td>
<td>20th, June 2020</td>
<td>20,000 - 30,000</td>
<td><span className="px-3 py-2" style={{background: "#fdf2e9", color: "#fbb30b"}}>Delete</span></td>
</tr>
</tbody>
</table>
</GigTableContainer>
)
}
export default GigsTable
<file_sep>/src/components/index.jsx
export { default as MainContent } from './mainContent'
export { default as Sidebar } from './sidebar'<file_sep>/src/components/mainContent/gigsCategory.jsx
import React from 'react'
import { GigsCategoryContainer, GigsCategoryColumn, GigsText, GigsCategoryActiveColumn, GigsActiveText} from './main.element'
import Keyword from '../../assets/keywordicon.png'
import Location from '../../assets/locationicon.png'
import Design from '../../assets/designicon.png'
import Contact from '../../assets/contacticon.png'
import Remote from '../../assets/remoteicon.png'
const GigsCategory = () => {
return (
<>
<div className="d-none d-xl-block">
<GigsCategoryContainer className="px-5 py-5 row ">
<GigsCategoryColumn className="px-2 text-center me-3 col-md-2">
<GigsText className="mt-3">
Freelance
</GigsText>
</GigsCategoryColumn>
<GigsCategoryColumn className="px-2 col-md-2 me-3">
<GigsText className="mt-3 ">
<img src={Keyword} alt="" className="pe-2"/>
Keywords
<i className="fas fa-angle-down ms-5"></i>
</GigsText>
</GigsCategoryColumn>
<GigsCategoryColumn className="px-2 col-md-2 me-3">
<GigsText className="mt-3 ">
<img src={Location} alt="" className="pe-2"/>
Location
<i className="fas fa-angle-down ms-5"></i>
</GigsText>
</GigsCategoryColumn>
<GigsCategoryActiveColumn className="px-2 col-md-2 me-3">
<GigsActiveText className="mt-3">
<img src={Design} alt="" className="pe-2"/>
Design
<i className="fas fa-check ms-5"></i>
</GigsActiveText>
</GigsCategoryActiveColumn>
<GigsCategoryColumn className="px-2 col-md-2 me-3">
<GigsText className="mt-3">
<img src={Contact} alt="" className="pe-2"/>
Contact
</GigsText>
</GigsCategoryColumn>
</GigsCategoryContainer>
</div>
<div className="px-5 py-5 d-block d-xl-none" >
<div class="dropdown">
<button class="btn btn-transparent text-warning text-start w-100" style={{outline: 'none', borderRadius: '10px', color: '#E18700', border: '2px solid #EEEEEE'}} type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<img src={Design} alt="" className="me-2"/>
Design
</button>
<ul class="dropdown-menu w-100" aria-labelledby="dropdownMenuButton1">
<li><span class="dropdown-item" > Freelance</span></li>
<li><span class="dropdown-item" ><img src={Keyword} alt="" className="me-2"/> Keyword</span></li>
<li><span class="dropdown-item" ><img src={Location} alt="" className="me-2"/>
Location</span></li>
<li><span class="dropdown-item" ><img src={Remote} alt="" className="me-2"/>
Remote Friendly</span></li>
<li><span class="dropdown-item" style={{color: '#E18700'}} ><img src={Design} alt="" className="me-2"/>
Design</span></li>
<li><span class="dropdown-item" ><img src={Contact} alt="" className="me-2"/>
Contact</span></li>
</ul>
</div>
</div>
</>
)
}
export default GigsCategory
<file_sep>/src/components/mainContent/sidenav.jsx
import React from "react";
import {
LinkContainer,
LinkIcon,
LinkText,
LinkTextActive,
} from "../sidebar/sidebar.Element";
import { CloseIcon, Icon, SidenavContainer, SidenavLogo, SidenavSection } from "./main.element";
import Logo from "../../assets/logo.svg";
import HomeIcon from "../../assets/homeIcon.png";
import GigsIcon from "../../assets/gigsicon.png";
import CompanyIcon from "../../assets/company icon.png";
import AccountIcon from "../../assets/account icon.png";
const Sidenav = ({ isOpen, toggle }) => {
return (
<SidenavContainer isOpen={isOpen} onClick={toggle}>
<Icon className="me-3">
<CloseIcon></CloseIcon>
</Icon>
<SidenavSection>
<SidenavLogo src={Logo} alt="" />
<LinkContainer>
<LinkIcon src={HomeIcon} alt="" />
<LinkText>Dashboard</LinkText>
</LinkContainer>
<LinkContainer>
<LinkIcon src={GigsIcon} alt="" />
<LinkTextActive>Gigs</LinkTextActive>
</LinkContainer>
<LinkContainer>
<LinkIcon src={CompanyIcon} alt="" />
<LinkText>Company</LinkText>
</LinkContainer>
<LinkContainer>
<LinkIcon src={AccountIcon} alt="" />
<LinkText>Account</LinkText>
</LinkContainer>
</SidenavSection>
</SidenavContainer>
);
};
export default Sidenav;
<file_sep>/src/components/mainContent/giigsHome.jsx
import React from 'react'
import TopTab from "./topTab";
import TopTiltle from "./topTiltle";
import GigsCategory from "./gigsCategory"
import GigsTable from './gigsTable'
const GigsHome = ({setPages, pages}) => {
return (
<>
<TopTiltle setPages={setPages} pages={pages}/>
<TopTab/>
<GigsCategory/>
<GigsTable/>
</>
)
}
export default GigsHome
<file_sep>/src/components/mainContent/Navbar.jsx
import React from 'react'
import { NavbarContainer, NavbarLeft, NavbarRight, SearchInput, NavbarLeftInput, NavbarIcon, NavIcon } from './main.element';
import BellIcon from '../../assets/bellicon.png';
import MessageIcon from '../../assets/messageicon.png';
import SettingIcon from '../../assets/settingIcon.png';
import ProfileIcon from '../../assets/profileicon.png';
import Logo from '../../assets/logo.svg';
const Navbar = ({ toggle }) => {
return (
<NavbarContainer className="px-4 py-4 border-bottom ">
<NavbarLeft className="d-block d-lg-none">
<NavIcon onClick={toggle}>
<i className="mt-3 fas fa-bars fa-lg text-secondary"></i>
</NavIcon>
<NavbarIcon src={Logo} alt="" className="ms-4"/>
</NavbarLeft>
<NavbarLeftInput className="d-none d-md-block w-50">
<i className="fas fa-search me-2 ms-2" style={{ marginTop:"12px",color: "#514C5D"}}></i>
<SearchInput className="ms-3" placeholder="Search"/>
</NavbarLeftInput>
<NavbarRight>
<NavbarIcon src={BellIcon} alt="" className="me-3"/>
<NavbarIcon src={MessageIcon} alt="" className="me-3"/>
<NavbarIcon src={SettingIcon} alt="" className="me-3"/>
<NavbarIcon src={ProfileIcon} alt="" className=""/>
</NavbarRight>
</NavbarContainer>
)
}
export default Navbar
<file_sep>/src/components/mainContent/topTab.jsx
import React from 'react'
import { TopTabActiveBgSpan, TopTabActiveLink, TopTabActiveSpan, TopTabBgSpan, TopTabLink, TopTabRow, TopTabSection, TopTabSpan } from './main.element'
const TopTab = () => {
return (
<TopTabSection className="">
<TopTabRow className="px-4" >
<TopTabActiveLink className="py-3 pe-5">
<TopTabActiveSpan className="ps-2">All gigs</TopTabActiveSpan>
<TopTabActiveBgSpan className="px-2 py-1">3404</TopTabActiveBgSpan>
</TopTabActiveLink>
<TopTabLink className="py-3 pe-5">
<TopTabSpan>My gigs</TopTabSpan>
<TopTabBgSpan className="px-2 py-1 " style={{marginLeft: "-40px"}}>1200</TopTabBgSpan>
</TopTabLink>
<TopTabLink className="py-3 pe-5">
<TopTabSpan>Rejected gigs</TopTabSpan>
<TopTabBgSpan className="px-2 py-1">100</TopTabBgSpan>
</TopTabLink>
</TopTabRow>
</TopTabSection>
)
}
export default TopTab
| d672a4c349eafdbc7fbcb435abf06d066995f221 | [
"JavaScript"
] | 11 | JavaScript | nerd35/chiixchangetext | ceaab59919b89fe1ea2bfcf4ba77b7d561fc6c36 | 2d33d173a735fafebfaf61f81516b9c65fb274d8 |
refs/heads/master | <repo_name>Wylie-S/chrome<file_sep>/background.js
/*chrome.runtime.onMessage.addListener(
function(message, callback) {
if (message == “runContentScript”){
chrome.tabs.executeScript({
file: 'popup.js'
});
}
});
/// background
/*function getSearchDetail(body)
{
fname = extractData(body,"First Name:"/ "\n")
lname = extractData(body,"Last Name: ", "\n")
email = extractData(body,"E-mail: ", "\n")
company = extractData(body,"Company: ", "\n")
address = extractData(body,"Address1: ", "\n")
alert (fname + "\n" + lname + "\n" + email + "\n" + company + "\n" + address)
}
function extractData(data, startStr, endStr)
{
subStrStart = data.indexOf(startStr) + startStr.length
return data.substring(subStrStart,
subStrStart + data.substring(subStrStart).indexOf(endStr));
}
const emptyObj = {pattern: "", secondaryPattern: "", result: []}
const emptyArray = []
const resetStorage = () => {
localStorage.setItem("regex_search", JSON.stringify(emptyObj))
localStorage.setItem("user_links", JSON.stringify(emptyArray))
}
chrome.browserAction.onClicked.addListener((tab) => {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
let activeTab = tabs[0]
chrome.tabs.sendMessage(activeTab.id, {
message: 'search',
pattern: '([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)',
})
chrome.tabs.sendMessage(activeTab.id, {
message: 'getSearchDetailHere',
})
})
})
<file_sep>/popup.js
function hello() {
chrome.tabs.executeScript({
file: 'content.js'
});
}
document.getElementById('checkPage').addEventListener('click', hello);
<file_sep>/scripts/search.js
window.click = function () {
// inject gmailUtils into gmail page
var url = "resources/gmailUtils.js";
var newScript = document.createElement('script');
var scriptURL = chrome.extension.getURL(url);
newScript.src = scriptURL;
// listen to messages from the open gmail tab
window.addEventListener("message", handleEvent, false);
}
chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.label) {
location.href = "#label/" + msg.label;
};
});
/**
* Handles messages received from the gmail page and forwards it to the background page.
* @param {event} The event to be handled.
*/
function handleEvent(event) {
// Wmessages se
if (event.source == window)
return;
if (event.data.type) {
var request = {
action: event.data.type,
data: {}
}
var eventMessage;
if (request.action == "search") {
console.time('search');
var input = event.data.search;
request.data = {
keyword: input
};
eventMessage = "Received search request " + input;
} else if (request.action == "thread") {
request.data = {
id: event.data.id,
messages: event.data.emailContent
};
eventMessage = "Captured thread from gmail page. #messages: " + request.data.messages.length + " for id: " + request.data.id;
} else if (request.action == "deleteLabels") {
eventMessage = "Unlabelling - script.js";
} else {
console.log("Incorrect message type:" + event.data.type);
return;
}
console.log(eventMessage);
chrome.extension.sendMessage(request, function (response) {
console.log(response);
});
}
}
<file_sep>/README.md
# chrome
# ChromeExtension
<file_sep>/myapp.js
InboxSDK.load(2, 'dijchnginpbblaeglopkgdncgldnjpim').then(function(sdk){
// the SDK has been loaded, now do something with it!
sdk.Compose.registerComposeViewHandler(function(composeView){
// a compose view has come into existence, do something with it!
composeView.addButton({
title: "PHLux Search",
iconUrl: "icons/128phlux.png",
onClick: function(event) {
event.composeView.insertTextIntoBodyAtCursor('SEARCH');
},
});
});
});
<file_sep>/content.js
$.ajax({
url: 'https://mail.google.com/',
dataType: 'jsonp'
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$('.star_gray').click();
$('a.btn.page_next').click();
sendResponse({result: "success"});
});
/*var searchText = forwardmarch;*/
var searchText = prompt('Enter the Email, Name or Keyword(s) to Search for');
var inboxMatchRegex = /\<([^\@]+\@[^\>]+)\>/
if (searchText.length > 0) {
var unreadMailSelector = '.Cp .zE';
setTimeout(function () {
if ($(unreadMailSelector).length > 0) {
var counter = 0
for (var i = $(unreadMailSelector).length - 1; i >= 0; i--) {
if ($(unreadMailSelector)[i].innerText.match(new RegExp(searchText, 'i'))) {counter++};
};
if (counter > 0) {
alert( 'you have ' + counter + 'unread email(s) containing' + ":" + "" + searchText + location);
} else {
alert ('Sorry your selected category has no emails matching your search criteria')
}};
var rootLinkMatch = location.href.match(inboxMatchRegex);
if (rootLinkMatch) {
var inboxLink = rootLinkMatch + '/#inbox'
};
if (inboxLink == location.href) {
$("a[href = '" + inboxLink + "']")[0].click();
};
}, 0)
};
// delete everything below if test not responsive
/*function Search() {
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Format and print the date of the matching message
sheet.getRange(row,1).setValue(
Utilities.formatDate(messages[m].getDate(),"GMT","yyyy-MM-dd"));
// Print the sender's name and email address
sheet.getRange(row,2).setValue(messages[m].getFrom());
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getSubject());
// Print the unique URL of the Gmail message
var id = "https://mail.google.com/mail/u/0/#all/"
+ messages[m].getId();
sheet.getRange(row,4).setFormula(
'=hyperlink("' + id + '", "View")');
// Move to the next row
row++;
}
}
}
}*/
var Gmail_Filter_Api = function(){
this.set_gmail_params = function() {
var gmail_params = {}
//Parse out Base Url
var regex = new RegExp("https://mail.google.com/(a/(.+?)/|(mail(.+?)#))");
var matches = document.location.href.match(regex);
m = matches[0]
gmail_params['GMAIL_BASE_URL'] = m.substring(0, m.length-1) + '?'
//Parse out gmailchat value
var regex = new RegExp("gmailchat=(.+?)/(.+?);")
var matches = document.cookie.match(regex)
gmail_params['USER_EMAIL'] = matches[1]
//Parse out gmail_at value
var regex = new RegExp("GMAIL_AT=(.+?);")
var matches = document.cookie.match(regex)
gmail_params['GMAIL_AT'] = matches[1]
//Parse out Gmail_ik value from GLOBALS
var ik_index = get_useremail_pos(0, gmail_params['USER_EMAIL']);
if(ik_index == -1) {
//TODO: handle this
// Could not find ik
}
else{
gmail_params['GMAIL_IK'] = window.GLOBALS[ik_index -1]
}
this.gmail_params = gmail_params ;
}
//Recursion
function get_useremail_pos(index, user_email) {
if(window.GLOBALS[index] == user_email) {
return index;
}
if(index >= (window.GLOBALS.length - 1) )//Failsafe
{
return -1;
}
else {
return get_useremail_pos(index+1, user_email);
}
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
this.process_gmail_filter_response = function(response, keyValues){
pattern = ""
if(keyValues['from'] !== undefined)
pattern += "from:\\(" + escapeRegExp(keyValues['from']) + "\\) "
if(keyValues['has'] !== undefined)
pattern += keyValues['has'] + " "
if(keyValues['hasnot'] !== undefined)
pattern += "-\\{" + keyValues['hasnot'] + "\\} "
if(pattern.length > 0){
pattern = pattern.substring(0, pattern.length-1)
}
pattern = "\"\(\\d+\)\",\"" + pattern + "\"";
console.log(pattern);
var regex = new RegExp(pattern)
matches = response.match(regex)
if(matches === undefined)
return 0;
return matches[1];
};
this.deleteGmailFilter = function(filter_id){
baseurl = this.gmail_params.GMAIL_BASE_URL;
urlsend = baseurl + "ik=" + this.gmail_params.GMAIL_IK + "&at=" + this.gmail_params.GMAIL_AT + "&view=up&act=df&pcd=1&mb=0&rt=c";
postdata = "tfi=" + filter_id;
$.post(urlsend, postdata, function(data){
var gmailresponse = data;
console.log(data);
});
};
this.createGmailFilter = function(keyValues) {
thisobj = this;
baseurl = this.gmail_params.GMAIL_BASE_URL;
gmail_filter_url = baseurl + "ik=" + this.gmail_params.GMAIL_IK + "&at=" + this.gmail_params.GMAIL_AT + "&view=up&act=cf&pcd=1&mb=0&rt=c"
//GMail filter variables
postdata = "search=cf"
for(key in keyValues){
switch(key){
case "from":
postdata = postdata + "&cf1_from=" + keyValues[key];
break;
case "has":
postdata = postdata + "&cf1_has=" + keyValues[key];
break;
case "hasnot":
postdata = postdata + "&cf1_hasnot=" + keyValues[key];
break;
case "markread":
postdata = postdata + "&cf2_ar=true";
break;
case "skipinbox":
postdata = postdata + "&cf2_cat=true";
break;
case "labelas":
postdata = postdata + "&cf2_sel=" + keyValues[key];
}
}
jQuery.post(gmail_filter_url, postdata, function(gmail_response){
thisobj.filterid = thisobj.process_gmail_filter_response(gmail_response, keyValues);
});
};
};
/*var searchText = prompt('Enter the Email, Name or Keyword(s) to Search for');
var inboxMatchRegex = /\<([^\@]+\@[^\>]+)\>/
if (searchText.length > 0) {
var allMailSelector = '.Cp .zE';
setInterval(function ($) {
if $(allMailSelector).length > 0) {
var counter = 0
for (var i = $(allMailSelector).length - 1; i >= 0; i--) {
if $(allMailSelector)[i].innerText.match(new RegExp(searchText, 'i'))) {counter++};
};
if (counter > 0) {
alert( 'you have ' + counter + 'unread email(s) containing' + searchText + location);
};
} else {
alert ('Sorry your inbox does not have any unread emails matching your search criteria')
};
var rootLinkMatch = location.href.match(inboxMatchRegex);
if (rootLinkMatch) {
var inboxLink = rootLinkMatch + '/#inbox'
};
if (inboxLink == location.href) {
$("a[href = '" + inboxLink + "']")[0].click();
};
}, 5000)
};
// delete everything below if test not responsive
/*function Search() {
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Format and print the date of the matching message
sheet.getRange(row,1).setValue(
Utilities.formatDate(messages[m].getDate(),"GMT","yyyy-MM-dd"));
// Print the sender's name and email address
sheet.getRange(row,2).setValue(messages[m].getFrom());
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getSubject());
// Print the unique URL of the Gmail message
var id = "https://mail.google.com/mail/u/0/#all/"
+ messages[m].getId();
sheet.getRange(row,4).setFormula(
'=hyperlink("' + id + '", "View")');
// Move to the next row
row++;
}
}
}
}*/
var Gmail_Filter_Api = function(){
this.set_gmail_params = function() {
var gmail_params = {}
//Parse out Base Url
var regex = new RegExp("https://mail.google.com/(a/(.+?)/|(mail(.+?)#))");
var matches = document.location.href.match(regex);
m = matches[0]
gmail_params['GMAIL_BASE_URL'] = m.substring(0, m.length-1) + '?'
//Parse out gmailchat value
var regex = new RegExp("gmailchat=(.+?)/(.+?);")
var matches = document.cookie.match(regex)
gmail_params['USER_EMAIL'] = matches[1]
//Parse out gmail_at value
var regex = new RegExp("GMAIL_AT=(.+?);")
var matches = document.cookie.match(regex)
gmail_params['GMAIL_AT'] = matches[1]
//Parse out Gmail_ik value from GLOBALS
var ik_index = get_useremail_pos(0, gmail_params['USER_EMAIL']);
if(ik_index == -1) {
//TODO: handle this
// Could not find ik
}
else{
gmail_params['GMAIL_IK'] = window.GLOBALS[ik_index -1]
}
this.gmail_params = gmail_params ;
}
//Recursion
function get_useremail_pos(index, user_email) {
if(window.GLOBALS[index] == user_email) {
return index;
}
if(index >= (window.GLOBALS.length - 1) )//Failsafe
{
return -1;
}
else {
return get_useremail_pos(index+1, user_email);
}
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
this.process_gmail_filter_response = function(response, keyValues){
pattern = ""
if(keyValues['from'] !== undefined)
pattern += "from:\\(" + escapeRegExp(keyValues['from']) + "\\) "
if(keyValues['has'] !== undefined)
pattern += keyValues['has'] + " "
if(keyValues['hasnot'] !== undefined)
pattern += "-\\{" + keyValues['hasnot'] + "\\} "
if(pattern.length > 0){
pattern = pattern.substring(0, pattern.length-1)
}
pattern = "\"\(\\d+\)\",\"" + pattern + "\"";
console.log(pattern);
var regex = new RegExp(pattern)
matches = response.match(regex)
if(matches === undefined)
return 0;
return matches[1];
};
this.deleteGmailFilter = function(filter_id){
baseurl = this.gmail_params.GMAIL_BASE_URL;
urlsend = baseurl + "ik=" + this.gmail_params.GMAIL_IK + "&at=" + this.gmail_params.GMAIL_AT + "&view=up&act=df&pcd=1&mb=0&rt=c";
postdata = "tfi=" + filter_id;
$.post(urlsend, postdata, function(data){
var gmailresponse = data;
console.log(data);
});
};
this.createGmailFilter = function(keyValues) {
thisobj = this;
baseurl = this.gmail_params.GMAIL_BASE_URL;
gmail_filter_url = baseurl + "ik=" + this.gmail_params.GMAIL_IK + "&at=" + this.gmail_params.GMAIL_AT + "&view=up&act=cf&pcd=1&mb=0&rt=c"
//GMail filter variables
postdata = "search=cf"
for(key in keyValues){
switch(key){
case "from":
postdata = postdata + "&cf1_from=" + keyValues[key];
break;
case "has":
postdata = postdata + "&cf1_has=" + keyValues[key];
break;
case "hasnot":
postdata = postdata + "&cf1_hasnot=" + keyValues[key];
break;
case "markread":
postdata = postdata + "&cf2_ar=true";
break;
case "skipinbox":
postdata = postdata + "&cf2_cat=true";
break;
case "labelas":
postdata = postdata + "&cf2_sel=" + keyValues[key];
}
}
jQuery.post(gmail_filter_url, postdata, function(gmail_response){
thisobj.filterid = thisobj.process_gmail_filter_response(gmail_response, keyValues);
});
};
};
| bcfc195112034c6166fdf1c81e4cd3d85c8dae54 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | Wylie-S/chrome | f52dd9b63d4c1c9dc7d8c7e55fe2f87528225cf1 | a43046ef8e4b1c56cb1dc807d36f1d1713c26cf7 |
refs/heads/main | <file_sep>Locales['hr'] = {
-- Svlačionica
['cloakroom'] = 'Svlacionica | 👒',
['citizen_wear'] = 'Civilno Odjelo | 👨',
['mafia_wear'] = 'Mafijaška Uniforma | 🎩',
['no_outfit'] = 'Ne postoji uniforma koja vam odgovara!',
['open_cloackroom'] = 'Pritisni ~INPUT_CONTEXT~ da promijeniš ~b~odjeću~s~.',
-- Oružarnica
['remove_object'] = 'Uzmi predmet | 📷',
['deposit_object'] = 'Ostavi predmet| 📷',
['get_weapon'] = 'Uzmi oružje | 🔫',
['put_weapon'] = 'Ostavi oružje | 🔫',
['buy_weapons'] = 'Kupi oružje | 💵',
['armory'] = 'Oružarnica | ⚙️',
['open_armory'] = 'Pritisni ~INPUT_CONTEXT~ da pristupiš ~b~oružarnici~s~.',
['armory_owned'] = 'Već Imate ✅',
['armory_free'] = 'Besplatno',
['armory_item'] = '%s$',
['armory_weapontitle'] = 'Oružarnica | ⚙️ ➥ Kupi oružje',
['armory_componenttitle'] = 'Dodatci za oružje | ⚙️',
['armory_bought'] = 'Kupio si ~b~%s~s~ za ~b~%s$~s~',
['armory_money'] = 'Nemaš dovoljno novca za ovo oružje',
['armory_hascomponent'] = 'Već imaš taj dodatak!',
['get_weapon_menu'] = 'Oružarnica | ⚙️ ➥ Uzmi oružje',
['put_weapon_menu'] = 'Oružarnica | ⚙️ ➥ Ostavi oružje',
-- Garaža
['vehicle_menu'] = 'Vozila',
['vehicle_blocked'] = 'Spawn pointi su blokirani!',
['garage_prompt'] = 'Pritisnite ~INPUT_CONTEXT~ da izabereš ~b~vozilo~s~.',
['garage_title'] = 'Izaberi Vozilo | 🚗',
['garage_stored'] = 'Parkirano ✅',
['garage_notstored'] = 'Van Garaže ❌',
['garage_storing'] = 'Pokušavamo ukloniti vozilo, budite sigurni da nema igraca oko njega.',
['garage_has_stored'] = 'Vozilo je parkirano u garazu',
['garage_has_notstored'] = 'U blizini nema vozila',
['garage_notavailable'] = 'Tvoje vozilo nije parkirano.',
['garage_blocked'] = 'Nema slobodnih spawn pointa!',
['garage_empty'] = 'Nemaš vozilo u garazi.',
['garage_released'] = 'Tvoje je vozilo izvandjeno iz garaže.',
['garage_store_nearby'] = 'U blizini nema vozila.',
['garage_storeditem'] = 'Izaberi Vozilo | 🚗',
['garage_storeitem'] = 'Parkiraj Vozilo | 🚗',
['garage_buyitem'] = 'Kupi Vozilo | 🚗',
['helicopter_prompt'] = 'Pritisni ~INPUT_CONTEXT~ da pristupiš meniju ~b~za helikoptere~s~.',
['helicopter_notauthorized'] = 'Nisi ovlašćen za tu radnju.',
['shop_item'] = '%s$',
['vehicleshop_title'] = 'Kupi Vozilo | 🚗',
['vehicleshop_confirm'] = 'Želiš li kupiti to vozilo',
['vehicleshop_bought'] = 'Kupio si ~b~%s~s~ za ~b~$%s~s~',
['vehicleshop_money'] = 'Nemaš dovoljno novca',
['vehicleshop_awaiting_model'] = 'Vozilo se trenutno ~b~PREUZIMA & UCITAVA~s~ molim da pricekas',
['confirm_no'] = 'Ne ❌',
['confirm_yes'] = 'Da ✅',
-- Radnje
['citizen_interaction'] = 'Upravljaj s ljudima | 👨',
['vehicle_interaction'] = 'Upravljaj s vozilom | 🚗',
['object_spawner'] = 'Stvaraj Predmete | 👜',
['id_card'] = 'Osobna karta | 💳',
['search'] = 'Pretraži | 🔍',
['handcuff'] = 'Zaveži / Odveži | ⛓️',
['drag'] = 'Vuci | 👨',
['put_in_vehicle'] = 'Stavi u vozilo | 🚗',
['out_the_vehicle'] = 'Izvuci iz vozila | 🚗',
['no_players_nearby'] = 'Nema igraca u blizini!',
['being_searched'] = '~b~Pretražen~s~ si od strane ~b~mafije~s~',
-- Vozila
['vehicle_info'] = 'Informacije o vozilu | 🚗',
['pick_lock'] = 'Obi vozilo | 🔓',
['vehicle_unlocked'] = 'Vozilo uspiješno ~b~otkljućano~s~',
['no_vehicles_nearby'] = 'U blizini nema vozila',
['search_database'] = 'Pretraga po registraciji | 🚗',
['search_database_title'] = 'Informacije - pretraži registraciju',
['search_database_error_invalid'] = 'To nije ~b~tocan~s~ broj registracije',
['search_database_error_not_found'] = 'Taj ~b~registracijski broj~s~ nije ni na jednom vozilu!',
['search_database_found'] = 'Vozilo je ~b~registrirano~s~ na ~b~%s~s~',
-- Promet
['traffic_interaction'] = 'Upravljanje Prometom | 🚦',
['cone'] = 'Cunj | 🛑',
['barrier'] = 'Granica | 🚧',
['spikestrips'] = 'Bodlje | ⛏️',
['box'] = 'Kutija | 📦',
-- Osobna
['name'] = 'Ime: %s',
['job'] = 'Posao: %s',
['sex'] = 'Spol: %s',
['dob'] = 'Datum rodjenja: %s',
['height'] = 'Visina: %s',
['id'] = 'OIB: %s',
['bac'] = 'Pijan: %s',
['unknown'] = 'Nepoznato',
['male'] = 'Muško',
['female'] = 'Žensko',
-- Pretrazivanje
['guns_label'] = '--- Oružja ---',
['inventory_label'] = '--- Inventar ---',
['license_label'] = ' --- Dozvole ---',
['confiscate'] = 'Oduzmi %s',
['confiscate_weapon'] = 'Oduzmi %s s %s metka',
['confiscate_inv'] = 'Oduzmi %sx %s',
['confiscate_dirty'] = 'Oduzmi prljav novac: <span style="color:red;">%s$</span>',
['you_confiscated'] = 'Oduzeo si ~b~%sx~s~ ~b~%s~s~ od ~b~%s~s~',
['got_confiscated'] = '~b~%sx~s~ ~b~%s~s~ je uzeto od strane ~b~%s~s~',
['you_confiscated_account'] = 'Oduzeo si ~b~%s$~s~ (%s) od ~b~%s~s~',
['got_confiscated_account'] = '~b~%s$~s~ (%s) je oduzeto od ~b~%s~s~',
['you_confiscated_weapon'] = 'Oduzeo si ~b~%s~s~ od ~b~%s~s~ s ~o~%s~s~ metaka',
['got_confiscated_weapon'] = 'Tvoj ~b~%s~s~ s ~o~%s~s~ metaka je oduzet od strane ~b~%s~s~',
-- Boss Meni
['open_bossmenu'] = 'Pritisni ~INPUT_CONTEXT~ za otvaranje ~b~sefa~s~',
['quantity_invalid'] = 'Nevažeća kolicina',
['have_withdrawn'] = 'Podigao si ~b~%sx~s~ ~b~%s~s~',
['have_deposited'] = 'Ostavio si ~b~%sx~s~ ~b~%s~s~',
['quantity'] = 'Kolicina',
['inventory'] = 'Inventar',
['mafia_stock'] = 'Mafijaške zalihe',
-- Misc
['remove_prop'] = 'Pritisni ~INPUT_CONTEXT~ da obrišeš ~b~objekt~s~.',
['map_blip'] = 'Mafija'
}
<file_sep>USE `es_extended`;
INSERT INTO `addon_account` (name, label, shared) VALUES
('society_vagos', 'Vagosi', 1),
('society_automafija', 'Automafija', 1),
('society_pinkpanteri', 'Pinkpanteri', 1),
('society_zg80', 'ZG80', 1),
('society_crnogorci', 'Crnogorci', 1),
('society_cartel', 'Cartel', 1),
('society_gsf', 'Gsf', 1)
;
INSERT INTO `datastore` (name, label, shared) VALUES
('society_vagos', 'Vagosi', 1),
('society_automafija', 'Automafija', 1),
('society_pinkpanteri', 'Pinkpanteri', 1),
('society_zg80', 'ZG80', 1),
('society_crnogorci', 'Crnogorci', 1),
('society_cartel', 'Cartel', 1),
('society_gsf', 'Gsf', 1)
;
INSERT INTO `addon_inventory` (name, label, shared) VALUES
('society_vagos', 'Vagosi', 1),
('society_automafija', 'Automafija', 1),
('society_pinkpanteri', 'Pinkpanteri', 1),
('society_zg80', 'ZG80', 1),
('society_crnogorci', 'Crnogorci', 1),
('society_cartel', 'Cartel', 1),
('society_gsf', 'Gsf', 1)
;
INSERT INTO `jobs` (name, label, whitelisted) VALUES
('vagos', 'Vagosi', 1),
('automafija', 'Automafija', 1),
('pinkpanteri', 'Pinkpanteri', 1),
('zg80', 'ZG80', 1),
('crnogorci', 'Crnogorci', 1),
('cartel', 'Cartel', 1),
('gsf', 'Gsf', 1)
;
INSERT INTO `job_grades` (job_name, grade, name, label, salary, skin_male, skin_female) VALUES
-- ('police',0,'recruit','Recrue',20,'{}','{}'),
-- ('police',1,'officer','Officier',40,'{}','{}'),
-- ('police',2,'sergeant','Sergent',60,'{}','{}'),
-- ('police',3,'lieutenant','Lieutenant',85,'{}','{}'),
-- ('police',4,'boss','Commandant',100,'{}','{}')
-- boss zamjenik radnik novak
('vagos',1,'novak','Novak',2000,'{}','{}'),
('vagos',2,'radnik','Radnik',2500,'{}','{}'),
('vagos',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('vagos',4,'boss','Šef',3500,'{}','{}'),
('automafija',1,'novak','Novak',2000,'{}','{}'),
('automafija',2,'radnik','Radnik',2500,'{}','{}'),
('automafija',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('automafija',4,'boss','Šef',3500,'{}','{}'),
('pinkpanteri',1,'novak','Novak',2000,'{}','{}'),
('pinkpanteri',2,'radnik','Radnik',2500,'{}','{}'),
('pinkpanteri',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('pinkpanteri',4,'boss','Šef',3500,'{}','{}'),
('zg80',1,'novak','Novak',2000,'{}','{}'),
('zg80',2,'radnik','Radnik',2500,'{}','{}'),
('zg80',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('zg80',4,'boss','Šef',3500,'{}','{}'),
('crnogorci',1,'novak','Novak',2000,'{}','{}'),
('crnogorci',2,'radnik','Radnik',2500,'{}','{}'),
('crnogorci',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('crnogorci',4,'boss','Šef',3500,'{}','{}'),
('cartel',1,'novak','Novak',2000,'{}','{}'),
('cartel',2,'radnik','Radnik',2500,'{}','{}'),
('cartel',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('cartel',4,'boss','Šef',3500,'{}','{}'),
('gsf',1,'novak','Novak',2000,'{}','{}'),
('gsf',2,'radnik','Radnik',2500,'{}','{}'),
('gsf',3,'zamjenik','Zamjenik Šefa',3000,'{}','{}'),
('gsf',4,'boss','Šef',3500,'{}','{}')
;<file_sep>Locales['en'] = {
-- Svlačionica
['cloakroom'] = 'Cloakroom | 👒',
['citizen_wear'] = 'Civil Outfit | 👨',
['mafia_wear'] = 'Mafia Outfit | 🎩',
['no_outfit'] = 'There\'s no uniform that fits you!',
['open_cloackroom'] = 'Press ~INPUT_CONTEXT~ to change ~b~clothes~s~.',
-- Oružarnica
['remove_object'] = 'Withdraw object | 📷',
['deposit_object'] = 'Deposit object| 📷',
['get_weapon'] = 'Take weapon | 🔫',
['put_weapon'] = 'Leave weapon | 🔫',
['buy_weapons'] = 'Buy weapon | 💵',
['armory'] = 'Armory | ⚙️',
['open_armory'] = 'Press ~INPUT_CONTEXT~ to access ~b~armory~s~.',
['armory_owned'] = 'You have it ✅',
['armory_free'] = 'Free',
['armory_item'] = '%s$',
['armory_weapontitle'] = 'Armory | ⚙️ ➥ Buy weapons',
['armory_componenttitle'] = 'Weapon attatchments | ⚙️',
['armory_bought'] = 'You bought ~b~%s~s~ for ~b~%s$~s~',
['armory_money'] = 'You don\'t have enough money for that!',
['armory_hascomponent'] = 'You have that attatchment already!',
['get_weapon_menu'] = 'Armory | ⚙️ ➥ Take weapon',
['put_weapon_menu'] = 'Armory | ⚙️ ➥ Leave weapon',
-- Garaža
['vehicle_menu'] = 'Vehicles',
['vehicle_blocked'] = 'All spawn points are blocked!',
['garage_prompt'] = 'Press ~INPUT_CONTEXT~ to choose a ~b~vehicle~s~.',
['garage_title'] = 'Vehicles | 🚗',
['garage_stored'] = 'Stored ✅',
['garage_notstored'] = 'Not in garage ❌',
['garage_storing'] = 'We are trying to store this vehicle, please make sure there aren\'t any other players around.',
['garage_has_stored'] = 'Vehicle is stored',
['garage_has_notstored'] = 'There aren\'t any vehicles nearby',
['garage_notavailable'] = 'Your vehicle is not stored in garage.',
['garage_blocked'] = 'There\'s no available spawn points!',
['garage_empty'] = 'You don\'t have any vehicles in garage.',
['garage_released'] = 'Your car is out.',
['garage_store_nearby'] = 'There aren\' any vehicles nearby.',
['garage_storeditem'] = 'Choose | 🚗',
['garage_storeitem'] = 'Store vehicle | 🚗',
['confirm_no'] = 'Ne ❌',
['confirm_yes'] = 'Da ✅',
-- Radnje
['citizen_interaction'] = 'Citizen interaction | 👨',
['vehicle_interaction'] = 'Vehicle Interaction | 🚗',
['object_spawner'] = 'Object Spawner | 👜',
['id_card'] = 'ID Card | 💳',
['search'] = 'Search | 🔍',
['handcuff'] = 'Cuff / Uncuff | ⛓️',
['drag'] = 'Drag | 👨',
['put_in_vehicle'] = 'Put in vehicle | 🚗',
['out_the_vehicle'] = 'Take out from vehicle | 🚗',
['no_players_nearby'] = 'No players nearby!',
['being_searched'] = '~b~You are being searched~s~ by a mafia',
-- Vozila
['vehicle_info'] = 'Vehicle info | 🚗',
['pick_lock'] = 'Lockpick vehicle | 🔓',
['vehicle_unlocked'] = 'Vehicle is ~g~Unlocked~s~',
['no_vehicles_nearby'] = 'There aren\'t any vehicles',
['search_database'] = 'Vehicle information | 🚗',
['search_database_title'] = 'Information - Search with registration number',
['search_database_error_invalid'] = 'That ~b~is not~s~ valid registration number',
['search_database_error_not_found'] = '~b~That registration number~s~ isn\'t on any vehicle!',
['search_database_found'] = 'That vehicle is ~b~registered~s~ on ~b~%s~s~',
-- Promet
['traffic_interaction'] = 'Upravljanje Prometom | 🚦',
['cone'] = 'Cone | 🛑',
['barrier'] = 'Barrier | 🚧',
['spikestrips'] = 'Spikestrips | ⛏️',
['box'] = 'Box | 📦',
-- Osobna
['name'] = 'Name: %s',
['job'] = 'Job: %s',
['sex'] = 'Sex: %s',
['dob'] = 'DOB: %s',
['height'] = 'Height: %s',
['id'] = 'ID: %s',
['bac'] = 'BAC: %s',
['unknown'] = 'Unknown',
['male'] = 'Male',
['female'] = 'Female',
-- Pretrazivanje
['guns_label'] = '--- Guns ---',
['inventory_label'] = '--- Inventory ---',
['license_label'] = ' --- Licenses ---',
['confiscate'] = 'Confiscate %s',
['confiscate_weapon'] = 'Confiscate %s with %s bullets',
['confiscate_inv'] = 'Confiscate %sx %s',
['confiscate_dirty'] = 'Confiscate dirty money: <span style="color:red;">$%s</span>',
['you_confiscated'] = 'You confiscated ~y~%sx~s~ ~b~%s~s~ from ~b~%s~s~',
['got_confiscated'] = '~y~%sx~s~ ~b~%s~s~ were confiscated by ~y~%s~s~',
['you_confiscated_account'] = 'You confiscated ~g~$%s~s~ (%s) from ~b~%s~s~',
['got_confiscated_account'] = '~g~$%s~s~ (%s) was confiscated by ~y~%s~s~',
['you_confiscated_weapon'] = 'You confiscated ~b~%s~s~ from ~b~%s~s~ with ~o~%s~s~ bullets',
['got_confiscated_weapon'] = 'Your ~b~%s~s~ with ~o~%s~s~ bullets was confiscated by ~y~%s~s~',
-- Boss Meni
['open_bossmenu'] = 'Press ~INPUT_CONTEXT~ to open the menu',
['quantity_invalid'] = 'invalid quantity',
['have_withdrawn'] = 'You have withdrawn ~y~%sx~s~ ~b~%s~s~',
['have_deposited'] = 'You have deposited ~y~%sx~s~ ~b~%s~s~',
['quantity'] = 'Quantity',
['inventory'] = 'Inventory',
['mafia_stock'] = 'Mafia stocks',
-- Misc
['remove_prop'] = 'Press ~INPUT_CONTEXT~ to delete an ~b~object~s~.',
['map_blip'] = 'Mafia'
}
<file_sep>fx_version 'bodacious'
game 'gta5'
description 'Mafia pack by sogolisica | edited, fixed and tweaked by sync'
version '1.0.0'
shared_scripts {
'@es_extended/locale.lua',
'locales/*.lua',
'config.lua'
}
server_scripts {
'@mysql-async/lib/MySQL.lua',
'server/main.lua'
}
client_script 'client/main.lua'
dependency 'sync_utils'<file_sep>ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
local mafijee = 0
for k,v in pairs(Config.Mafije) do
TriggerEvent('esx_society:registerSociety', k, k, 'society_' .. k, 'society_'..k, 'society_'..k, {type = 'public'})
mafijee = mafijee + 1
end
print('[^1sync_mafije^0]: Developed by ^7sogolisica^0 and ^5sync^0 | Loaded ^4' .. mafijee .. '^0 mafias')
-----------------------
-----CALLBACKOVI-------
-----------------------
ESX.RegisterServerCallback('sync_mafije:getOtherPlayerData', function(source, cb, target)
local xPlayer = ESX.GetPlayerFromId(target)
local data = {
name = GetPlayerName(target),
job = xPlayer.job,
inventory = xPlayer.inventory,
accounts = xPlayer.accounts,
weapons = xPlayer.loadout
}
cb(data)
end)
ESX.RegisterServerCallback('sync_mafije:getPlayerInventory', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
local items = xPlayer.inventory
cb({items = items})
end)
-----------------------
-------EVENTOVI--------
-----------------------
RegisterServerEvent('sync_mafije:oduzmiItem')
AddEventHandler('sync_mafije:oduzmiItem', function(target, itemType, itemName, amount)
local _source = source
local sourceXPlayer = ESX.GetPlayerFromId(_source)
local targetXPlayer = ESX.GetPlayerFromId(target)
if itemType == 'item_standard' then
local targetItem = targetXPlayer.getInventoryItem(itemName)
local sourceItem = sourceXPlayer.getInventoryItem(itemName)
if targetItem.count > 0 and targetItem.count <= amount then
if sourceXPlayer.canCarryItem(itemName. amount) then
targetXPlayer.removeInventoryItem(itemName, amount)
sourceXPlayer.addInventoryItem(itemName, amount)
sourceXPlayer.showNotification(_U('you_confiscated', amount, sourceItem.label, targetXPlayer.name))
targetXPlayer.showNotification(_U('got_confiscated', amount, sourceItem.label, sourceXPlayer.name))
--TriggerClientEvent('esx:showNotification', _source, _U('you_confiscated', amount, sourceItem.label, targetXPlayer.name))
--TriggerClientEvent('esx:showNotification', target, _U('got_confiscated', amount, sourceItem.label, sourceXPlayer.name))
else
--TriggerClientEvent('esx:showNotification', _source, _U('quantity_invalid'))
sourceXPlayer.showNotification(_U('quantity_invalid'))
end
else
--TriggerClientEvent('esx:showNotification', _source, _U('quantity_invalid'))
sourceXPlayer.showNotification(_U('quantity_invalid'))
end
elseif itemType == 'item_account' then
targetXPlayer.removeAccountMoney(itemName, amount)
sourceXPlayer.addAccountMoney(itemName, amount)
--TriggerClientEvent('esx:showNotification', _source, _U('you_confiscated_account', amount, itemName, targetXPlayer.name))
sourceXPlayer.showNotification(_U('you_confiscated_account', amount, itemName, targetXPlayer.name))
targetXPlayer.showNotification(_U('got_confiscated_account', amount, itemName, targetXPlayer.name))
--TriggerClientEvent('esx:showNotification', target, _U('got_confiscated_account', amount, itemName, sourceXPlayer.name))
elseif itemType == 'item_weapon' then
if amount == nil then amount = 0 end
targetXPlayer.removeWeapon(itemName, amount)
sourceXPlayer.addWeapon(itemName, amount)
sourceXPlayer.showNotification(_U('you_confiscated_weapon', ESX.GetWeaponLabel(itemName), targetXPlayer.name, amount))
targetXPlayer.showNotification(_U('got_confiscated_weapon', ESX.GetWeaponLabel(itemName), amount, sourceXPlayer.name))
--TriggerClientEvent('esx:showNotification', _source, _U('you_confiscated_weapon', ESX.GetWeaponLabel(itemName), targetXPlayer.name, amount))
--TriggerClientEvent('esx:showNotification', target, _U('got_confiscated_weapon', ESX.GetWeaponLabel(itemName), amount, sourceXPlayer.name))
end
end)
RegisterServerEvent('sync_mafije:vezivanje')
AddEventHandler('sync_mafije:vezivanje', function(target)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('sync_mafije:vezivanje', target)
end)
RegisterServerEvent('sync_mafije:vuci')
AddEventHandler('sync_mafije:vuci', function(target)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('sync_mafije:vuci', target, source)
end)
RegisterServerEvent('sync_mafije:staviUVozilo')
AddEventHandler('sync_mafije:staviUVozilo', function(target)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('sync_mafije:staviUVozilo', target)
end)
RegisterServerEvent('sync_mafije:staviVanVozila')
AddEventHandler('sync_mafije:staviVanVozila', function(target)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('sync_mafije:staviVanVozila', target)
end)
RegisterServerEvent('sync_mafije:poruka')
AddEventHandler('sync_mafije:poruka', function(target, msg)
TriggerClientEvent('esx:showNotification', target, msg)
end)
ESX.RegisterServerCallback('sync_mafije:dbGettajPuske', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
local org = xPlayer.job.name
TriggerEvent('esx_datastore:getSharedDataStore', 'society_' .. org, function(store)
local weapons = store.get('weapons')
if weapons == nil then
weapons = {}
end
cb(weapons)
end)
end)
ESX.RegisterServerCallback('sync_mafije:staviUoruzarnicu', function(source, cb, weaponName, removeWeapon)
local xPlayer = ESX.GetPlayerFromId(source)
local org = xPlayer.job.name
if removeWeapon then
xPlayer.removeWeapon(weaponName)
end
TriggerEvent('esx_datastore:getSharedDataStore', 'society_' .. org, function(store)
local weapons = store.get('weapons') or {}
local foundWeapon = false
for i=1, #weapons, 1 do
if weapons[i].name == weaponName then
weapons[i].count = weapons[i].count + 1
foundWeapon = true
break
end
end
if not foundWeapon then
table.insert(weapons, {
name = weaponName,
count = 1
})
end
store.set('weapons', weapons)
cb()
end)
end)
ESX.RegisterServerCallback('sync_mafije:izvadiIzOruzarnice', function(source, cb, weaponName)
local xPlayer = ESX.GetPlayerFromId(source)
local org = xPlayer.job.name
xPlayer.addWeapon(weaponName, 500)
TriggerEvent('esx_datastore:getSharedDataStore', 'society_' .. org, function(store)
local weapons = store.get('weapons') or {}
local foundWeapon = false
for i=1, #weapons, 1 do
if weapons[i].name == weaponName then
weapons[i].count = (weapons[i].count > 0 and weapons[i].count - 1 or 0)
foundWeapon = true
break
end
end
if not foundWeapon then
table.insert(weapons, {
name = weaponName,
count = 0
})
end
store.set('weapons', weapons)
cb()
end)
end)
ESX.RegisterServerCallback('sync_mafije:kupiOruzje', function(source, cb, weaponName, type, componentNum)
local xPlayer = ESX.GetPlayerFromId(source)
local org = xPlayer.job.name
local authorizedWeapons, selectedWeapon = Config.Oruzje[xPlayer.job.grade_name]
for k,v in ipairs(authorizedWeapons) do
if v.weapon == weaponName then
selectedWeapon = v
break
end
end
if not selectedWeapon then
print(('sync_mafije: %s je pokusao kupiti krivu pusku!'):format(xPlayer.identifier))
xPlayer.kick('You have been kicked from this server for exploiting!')
cb(false)
else
if type == 1 then
if xPlayer.getMoney() >= selectedWeapon.price then
xPlayer.removeMoney(selectedWeapon.price)
xPlayer.addWeapon(weaponName, 100)
cb(true)
else
cb(false)
end
elseif type == 2 then
local price = selectedWeapon.components[componentNum]
local weaponNum, weapon = ESX.GetWeapon(weaponName)
local component = weapon.components[componentNum]
if component then
if xPlayer.getMoney() >= price then
xPlayer.removeMoney(price)
xPlayer.addWeaponComponent(weaponName, component.name)
cb(true)
else
cb(false)
end
else
print(('sync_mafije: %s je pokusao kupiti krivi dodatak.'):format(xPlayer.identifier))
xPlayer.kick('You have been kicked from this server for exploiting!')
end
end
end
end)
<file_sep>Config = {}
Config.DrawDistance = 30.0
Config.MarkerSize = { x = 1.5, y = 1.5, z = 0.5 }
Config.MarkerHelikopter = { x = 6.0, y = 6.0, z = 2.5 }
Config.MarkerAuto = { x = 3.0, y = 3.0, z = 3.0 }
Config.MarkerColor = { r = 50, g = 50, b = 204 }
Config.Locale = 'en'
Config.MarkerTypes = {
Brodovi = 35,
BossMeni = 31,
SpawnAuta = 36,
ObicanMarker = 27,
Helikopteri = 34,
VracanjeAuta = 1,
Oruzarnica = 21
}
Config.Mafije = {
vagos = { -- rijeseno
Armories = {vector3(-1129.65, -1604.64, 4.4)},
Vehicles = {vector3(-1123.79, -1611.55, 4.4)},
MeniVozila = {
Vozilo1 = 'schlagen',
Vozilo2 = 'seminole',
Vozilo3 = 'enduro',
},
BossActions = {vector3(-1119.86, -1624.39, 4.4)},
ParkirajAuto = {vector3(-1108.21, -1602.68, 3.68),},
},
automafija = {-- rijeseno
Armories = {vector3(973.46, -1811.45, 31.27)},
Vehicles = {vector3(969.40, -1824.04, 31.09)},
MeniVozila = {
Vozilo1 = 'schlagen',
Vozilo2 = 'seminole',
Vozilo3 = 'enduro',
},
BossActions = {vector3(967.79, -1828.88, 31.23)},
ParkirajAuto = {vector3(976.14, -1828.74, 30.17),},
},
pinkpanteri = {-- rijeseno
Armories = {vector3(7.96, 530.04, 170.62)},
Vehicles = {vector3(13.95, 548.18, 176.14)},
MeniVozila = {
Vozilo1 = 'buffalo',
Vozilo2 = 'seminole',
Vozilo3 = 'enduro',
},
BossActions = {vector3(-7.03, 530.56, 175.0)},
ParkirajAuto = {vector3(22.49, 544.42, 175.03),},
},
zg80 = {-- rijeseno
Armories = {vector3(1055.13, 216.16, 80.98)},
Vehicles = {vector3(1035.28, 204.96, 80.84)},
MeniVozila = {
Vozilo1 = 'revolter',
Vozilo2 = 'rocoto',
Vozilo3 = 'enduro',
},
BossActions = {vector3(1042.81, 192.81, 80.99)},
ParkirajAuto = {vector3(1038.51, 203.85, 79.00),},
},
crnogorci = {-- rijeseno
Armories = {vector3(-802.88, 184.94, 72.61)},
Vehicles = {vector3(-820.18, 184.51, 72.13)},
MeniVozila = {
Vozilo1 = 'revolter',
Vozilo2 = 'rocoto',
Vozilo3 = 'enduro',
},
BossActions = {vector3(-812.17, 175.16, 76.75)},
ParkirajAuto = {vector3(-811.96, 187.43, 71.47),},
},
cartel = {-- rijeseno
Armories = {vector3(-3007.37, 81.07, 11.60)},
Vehicles = {vector3(-3018.97, 100.32, 11.64)},
MeniVozila = {
Vozilo1 = 'revolter',
Vozilo2 = 'rocoto',
Vozilo3 = 'enduro',
},
Brodovi = {vector3(-3009.32, -3.36, 3.23)},
BrodoviMenu = {
Brod1 = 'dinghy',
Brod2 = 'seashark',
},
BossActions = {vector3(-3004.93, 79.61, 11.60)},
ParkirajAuto = {vector3(-3009.55, 92.32, 10.60),},
},
gsf = {-- rijeseno
Armories = {vector3(-18.13, -1432.57, 31.1)},
Vehicles = {vector3(-25.04, -1437.39, 30.65)},
MeniVozila = {
Vozilo1 = 'revolter',
Vozilo2 = 'rocoto',
Vozilo3 = 'enduro',
},
BossActions = {vector3(-9.9, -1439.02, 31.1)},
ParkirajAuto = {vector3(-25.22, -1428.07, 29.66),},
},
}
Config.Oruzje = {
novak = {
{weapon = 'WEAPON_APPISTOL', components = {5000, 5000, 2000, 4000, nil}, price = 25000}
},
radnik = {
{weapon = 'WEAPON_APPISTOL', components = {2000, 2000, 1000, 4000, nil}, price = 1},
{weapon = 'WEAPON_ADVANCEDRIFLE', components = {2000, 6000, 1000, 4000, 8000, nil}, price = 501000},
{weapon = 'WEAPON_PUMPSHOTGUN', components = {2000, 6000, nil}, price = 1}
},
zamjenik = {
{weapon = 'WEAPON_APPISTOL', components = {2500, 2000, 1000, 4000, nil}, price = 25000},
{weapon = 'WEAPON_ADVANCEDRIFLE', components = {8500, 6000, 1000, 4000, 8000, nil}, price = 125000},
{weapon = 'WEAPON_PUMPSHOTGUN', components = {6500, 6000, nil}, price = 75000}
},
boss = {
{weapon = 'WEAPON_APPISTOL', components = {2500, 2000, 1000, 4000, nil}, price = 25000},
{weapon = 'WEAPON_ADVANCEDRIFLE', components = {8500, 6000, 1000, 4000, 8000, nil}, price = 125000},
{weapon = 'WEAPON_PUMPSHOTGUN', components = {6500, 6000, nil}, price = 75000}
}
}
<file_sep>local PlayerData, CurrentActionData, handcuffTimer, dragStatus, blipsCops, currentTask, spawnedVehicles = {}, {}, {}, {}, {}, {}, {}
local HasAlreadyEnteredMarker, isDead, isHandcuffed = false, false, false
local LastStation, LastPart, LastPartNum, CurrentAction, CurrentActionMsg
dragStatus.isDragged = false
ESX = nil
local poslovi = PlayerData.job.name == 'zg80' or PlayerData.job.name == 'vagos' or PlayerData.job.name == 'automafija' or PlayerData.job.name == 'pinkpanteri' or PlayerData.job.name == 'crnogorci' or PlayerData.job.name == 'cartel' or PlayerData.job.name == 'gsf'
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
while ESX.GetPlayerData().job == nil do
Citizen.Wait(10)
end
PlayerData = ESX.GetPlayerData()
end)
-----------------------
-------FUNKCIJE--------
-----------------------
function ocistiIgraca(playerPed)
SetPedArmour(playerPed, 0)
ClearPedBloodDamage(playerPed)
ResetPedVisibleDamage(playerPed)
ClearPedLastWeaponDamage(playerPed)
ResetPedMovementClipset(playerPed, 0)
end
function ObrisiVozilo()
local playerPed = PlayerPedId()
local vehicleProps = ESX.Game.GetVehicleProperties(CurrentActionData.vehicle)
local igracbrzina = math.floor((GetEntitySpeed(GetVehiclePedIsIn(GetPlayerPed(-1), false))*3.6))
if(igracbrzina > 25) then
ESX.ShowNotification("Voziš pre brzo ~b~vozilo~s~, uspori!")
elseif (igracbrzina < 25) then
ESX.Game.DeleteVehicle(CurrentActionData.vehicle)
ESX.ShowNotification("Uspiješno si parkirao ~b~vozilo~s~ u garažu.")
end
end
function OpenArmoryMenu(station)
local elements = {
{label = 'Kupi oružje | 🔫', value = 'buy_weapons'}
}
table.insert(elements, {label = _U('get_weapon'), value = 'get_weapon'})
table.insert(elements, {label = _U('put_weapon'), value = 'put_weapon'})
--table.insert(elements, {label = _U('remove_object'), value = 'get_stock'})
--table.insert(elements, {label = _U('deposit_object'), value = 'put_stock'})
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'armory', {
title = _U('armory'),
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.value == 'get_weapon' then
OpenGetWeaponMenu()
elseif data.current.value == 'put_weapon' then
OpenPutWeaponMenu()
elseif data.current.value == 'buy_weapons' then
OpenBuyWeaponsMenu()
-- elseif data.current.value == 'put_stock' then
-- OpenPutStocksMenu()
-- elseif data.current.value == 'get_stock' then
-- OpenGetStocksMenu()
end
end, function(data, menu)
menu.close()
CurrentAction = 'menu_armory'
CurrentActionMsg = _U('open_armory')
CurrentActionData = {station = station}
end)
end
function StvoriVozilo(vozilo)
for k,v in pairs(Config.Mafije[PlayerData.job.name]) do
a = (Config.Mafije[PlayerData.job.name]['MeniVozila'][vozilo])
break
end
TriggerEvent('esx:spawnVehicle', a)
end
function OtvoriAutoSpawnMenu(type, station, part, partNum)
ESX.UI.Menu.CloseAll()
local posaoIME = PlayerData.job.name
ESX.UI.Menu.Open(
'default', GetCurrentResourceName(), 'vozila_meni',
{
css = 'vagos',
title = 'Izaberi Vozilo | 🚗',
elements = {
{label = Config.Mafije[posaoIME]['MeniVozila'].Vozilo1..' | 🚗', value = 'primo2'},
{label = Config.Mafije[posaoIME]['MeniVozila'].Vozilo2..' | 🚗', value = 'seminole'},
{label = Config.Mafije[posaoIME]['MeniVozila'].Vozilo3..' | 🚗', value = 'enduro'},
}
},
function(data, menu)
if data.current.value == 'primo2' then
StvoriVozilo('Vozilo1')
ESX.UI.Menu.CloseAll()
elseif data.current.value == 'seminole' then
StvoriVozilo('Vozilo2')
ESX.UI.Menu.CloseAll()
elseif data.current.value == 'enduro' then
StvoriVozilo('Vozilo3')
end
end,
function(data, menu)
menu.close()
end
)
end
function OtvoriHeliSpawnMenu(type, station, part, partNum)
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open(
'default', GetCurrentResourceName(), 'vozila_meni',
{
css = 'vagos',
title = 'Izaberi Brod | ⛵',
elements = {
{label = Config.Mafije[posaoIME]['BrodoviMenu'].Brod1..' | ⛵', value = 'fxho'},
{label = Config.Mafije[posaoIME]['BrodoviMenu'].Brod2..' | ⛵', value = 'seashark'},
}
},
function(data, menu)
local playerPed = PlayerPedId()
if data.current.value == 'fxho' then
ESX.Game.SpawnVehicle("supervolito", vector3(-2320.86, -658.25, 13.48), 266.92, function(vehicle) --
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
end)
Wait(200)
local vehicle = GetVehiclePedIsIn(playerPed, false)
SetVehicleDirtLevel(vehicle, 0.0)
exports["LegacyFuel"]:SetFuel(vehicle, 100)
ESX.UI.Menu.CloseAll()
elseif data.current.value == 'seashark' then
ESX.Game.SpawnVehicle("seasparrow", vector3(-2320.86, -658.25, 13.48), 266.92, function(vehicle) --
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
end)
Wait(200)
local vehicle = GetVehiclePedIsIn(playerPed, false)
SetVehicleDirtLevel(vehicle, 0.0)
exports["LegacyFuel"]:SetFuel(vehicle, 100)
ESX.UI.Menu.CloseAll()
end
end,
function(data, menu)
menu.close()
end
)
end
function OtvoriBrodSpawnMenu(type, station, part, partNum)
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open(
'default', GetCurrentResourceName(), 'vozila_meni',
{
css = 'vagos',
title = 'Izaberi Vozilo | ⛵',
elements = {
{label = Config.Mafije['cartel']['BrodoviMenu'].Brod1..' | ⛵', value = 'fxho'},
{label = Config.Mafije['cartel']['BrodoviMenu'].Brod2..' | ⛵', value = 'seashark'},
}
},
function(data, menu)
local playerPed = PlayerPedId()
if data.current.value == 'fxho' then
ESX.Game.SpawnVehicle("dinghy", vector3(-3036.18, -27.84, 0.80), 159.25, function(vehicle) --
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
end)
Wait(200)
local vehicle = GetVehiclePedIsIn(playerPed, false)
SetVehicleDirtLevel(vehicle, 0.0)
exports["LegacyFuel"]:SetFuel(vehicle, 100)
ESX.UI.Menu.CloseAll()
elseif data.current.value == 'seashark' then
ESX.Game.SpawnVehicle("seashark", vector3(-3036.18, -27.84, 0.80), 159.25, function(vehicle) --
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
end)
Wait(200)
local vehicle = GetVehiclePedIsIn(playerPed, false)
SetVehicleDirtLevel(vehicle, 0.0)
exports["LegacyFuel"]:SetFuel(vehicle, 100)
ESX.UI.Menu.CloseAll()
end
end,
function(data, menu)
menu.close()
end
)
end
function OtvoriPosaoMenu()
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'sync_f6', {
css = 'vagos',
title = 'Meni Mafije | 🎩',
align = 'top-left',
elements = {
{label = _U('citizen_interaction'), value = 'citizen_interaction'},
}}, function(data, menu)
if data.current.value == 'citizen_interaction' then
local elements = {
{label = _U('id_card'), value = 'identity_card'},
{label = _U('search'), value = 'body_search'},
{label = _U('handcuff'), value = 'handcuff'},
{label = _U('drag'), value = 'drag'},
{label = _U('put_in_vehicle'), value = 'put_in_vehicle'},
{label = _U('out_the_vehicle'), value = 'out_the_vehicle'}
}
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'citizen_interaction', {
css = 'vagos',
title = _U('citizen_interaction'),
align = 'top-left',
elements = elements
}, function(data2, menu2)
local closestPlayer, closestDistance = ESX.Game.GetClosestPlayer()
if closestPlayer ~= -1 and closestDistance <= 3.0 then
local action = data2.current.value
if action == 'identity_card' then
OtvoriNjegovMeni(closestPlayer)
elseif action == 'body_search' then
TriggerServerEvent('sync_mafije:poruka', GetPlayerServerId(closestPlayer), _U('being_searched'))
PretrazivanjeIgraca(closestPlayer)
elseif action == 'handcuff' then
TriggerServerEvent('sync_mafije:vezivanje', GetPlayerServerId(closestPlayer))
elseif action == 'drag' then
TriggerServerEvent('sync_mafije:vuci', GetPlayerServerId(closestPlayer))
elseif action == 'put_in_vehicle' then
TriggerServerEvent('sync_mafije:staviUVozilo', GetPlayerServerId(closestPlayer))
elseif action == 'out_the_vehicle' then
TriggerServerEvent('sync_mafije:staviVanVozila', GetPlayerServerId(closestPlayer))
end
else
ESX.ShowNotification(_U('no_players_nearby'))
end
end, function(data2, menu2)
menu2.close()
end)
end
end, function(data, menu)
menu.close()
end)
end
function OtvoriNjegovMeni(player)
ESX.TriggerServerCallback('esx_policejob:getOtherPlayerData', function(data)
local elements = {
{label = _U('name', data.name)},
{label = _U('job', ('%s - %s'):format(data.job, data.grade))}
}
table.insert(elements, {label = _U('sex', _U(data.sex))})
table.insert(elements, {label = _U('dob', data.dob)})
table.insert(elements, {label = _U('height', data.height)})
if data.drunk then
table.insert(elements, {label = _U('bac', data.drunk)})
end
if data.licenses then
table.insert(elements, {label = _U('license_label')})
for i=1, #data.licenses, 1 do
table.insert(elements, {label = data.licenses[i].label})
end
end
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'citizen_interaction', {
title = _U('citizen_interaction'),
align = 'top-left',
elements = elements
}, nil, function(data, menu)
menu.close()
end)
end, GetPlayerServerId(player))
end
function PretrazivanjeIgraca(player)
ESX.TriggerServerCallback('sync_mafije:getOtherPlayerData', function(data)
local elements = {}
for i=1, #data.accounts, 1 do
if data.accounts[i].name == 'black_money' and data.accounts[i].money > 0 then
table.insert(elements, {
label = _U('confiscate_dirty', ESX.Math.Round(data.accounts[i].money)),
value = 'black_money',
itemType = 'item_account',
amount = data.accounts[i].money
})
break
end
end
table.insert(elements, {label = _U('guns_label')})
for i=1, #data.weapons, 1 do
table.insert(elements, {
label = _U('confiscate_weapon', ESX.GetWeaponLabel(data.weapons[i].name), data.weapons[i].ammo),
value = data.weapons[i].name,
itemType = 'item_weapon',
amount = data.weapons[i].ammo
})
end
table.insert(elements, {label = _U('inventory_label')})
for i=1, #data.inventory, 1 do
if data.inventory[i].count > 0 then
table.insert(elements, {
label = _U('confiscate_inv', data.inventory[i].count, data.inventory[i].label),
value = data.inventory[i].name,
itemType = 'item_standard',
amount = data.inventory[i].count
})
end
end
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'body_search', {
css = 'vagos',
title = _U('search'),
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.value then
TriggerServerEvent('sync_mafije:oduzmiItem', GetPlayerServerId(player), data.current.itemType, data.current.value, data.current.amount)
PretrazivanjeIgraca(player)
end
end, function(data, menu)
menu.close()
end)
end, GetPlayerServerId(player))
end
-----------------------------
---------EVENTOVI------------
-----------------------------
AddEventHandler('sync_mafije:hasEnteredMarker', function(station, part, partNum)
if part == 'Cloakroom' then
CurrentAction = 'menu_cloakroom'
CurrentActionMsg = _U('open_cloackroom')
CurrentActionData = {}
elseif part == 'Armory' then
CurrentAction = 'menu_armory'
CurrentActionMsg = _U('open_armory')
CurrentActionData = {station = station}
elseif part == 'Vehicles' then
CurrentAction = 'menu_vehicle_spawner'
CurrentActionMsg = _U('garage_prompt')
CurrentActionData = {station = station, part = part, partNum = partNum}
elseif part == 'Brodovi' then
CurrentAction = 'Brodovi'
CurrentActionMsg = _U('garage_prompt')
CurrentActionData = {station = station, part = part, partNum = partNum}
elseif part == 'BossActions' then
CurrentAction = 'menu_boss_actions'
CurrentActionMsg = _U('open_bossmenu')
CurrentActionData = {}
elseif part == 'ParkirajAuto' then
local playerPed = PlayerPedId()
local vehicle = GetVehiclePedIsIn(playerPed, false)
if IsPedInAnyVehicle(playerPed, false) and GetPedInVehicleSeat(vehicle, -1) == playerPed then
CurrentAction = 'ParkirajAuto'
CurrentActionMsg = 'Pritisni ~INPUT_CONTEXT~ za ~b~parkiranje~s~ vozila u garažu.'
CurrentActionData = { vehicle = vehicle }
end
end
end)
AddEventHandler('sync_mafije:hasExitedMarker', function(station, part, partNum)
ESX.UI.Menu.CloseAll()
CurrentAction = nil
end)
RegisterNetEvent('sync_mafije:vezivanje')
AddEventHandler('sync_mafije:vezivanje', function()
isHandcuffed = not isHandcuffed
local playerPed = PlayerPedId()
Citizen.CreateThread(function()
if isHandcuffed then
RequestAnimDict('mp_arresting')
while not HasAnimDictLoaded('mp_arresting') do
Citizen.Wait(100)
end
TaskPlayAnim(playerPed, 'mp_arresting', 'idle', 8.0, -8, -1, 49, 0, 0, 0, 0)
SetEnableHandcuffs(playerPed, true)
DisablePlayerFiring(playerPed, true)
SetCurrentPedWeapon(playerPed, GetHashKey('WEAPON_UNARMED'), true) -- unarm player
SetPedCanPlayGestureAnims(playerPed, false)
FreezeEntityPosition(playerPed, true)
DisplayRadar(false)
else
ClearPedSecondaryTask(playerPed)
SetEnableHandcuffs(playerPed, false)
DisablePlayerFiring(playerPed, false)
SetPedCanPlayGestureAnims(playerPed, true)
FreezeEntityPosition(playerPed, false)
DisplayRadar(true)
end
end)
end)
RegisterNetEvent('sync_mafije:odvezivanje')
AddEventHandler('sync_mafije:odvezivanje', function()
if isHandcuffed then
local playerPed = PlayerPedId()
isHandcuffed = false
ClearPedSecondaryTask(playerPed)
SetEnableHandcuffs(playerPed, false)
DisablePlayerFiring(playerPed, false)
SetPedCanPlayGestureAnims(playerPed, true)
FreezeEntityPosition(playerPed, false)
DisplayRadar(true)
end
end)
RegisterNetEvent('sync_mafije:vuci')
AddEventHandler('sync_mafije:vuci', function(copId)
if not isHandcuffed then
return
end
dragStatus.isDragged = not dragStatus.isDragged
dragStatus.CopId = copId
end)
Citizen.CreateThread(function()
local playerPed
local targetPed
while true do
Citizen.Wait(1)
if isHandcuffed then
playerPed = PlayerPedId()
if dragStatus.isDragged then
targetPed = GetPlayerPed(GetPlayerFromServerId(dragStatus.CopId))
if not IsPedSittingInAnyVehicle(targetPed) then
AttachEntityToEntity(playerPed, targetPed, 11816, 0.54, 0.54, 0.0, 0.0, 0.0, 0.0, false, false, false, false, 2, true)
else
dragStatus.isDragged = false
DetachEntity(playerPed, true, false)
end
if IsPedDeadOrDying(targetPed, true) then
dragStatus.isDragged = false
DetachEntity(playerPed, true, false)
end
else
DetachEntity(playerPed, true, false)
end
else
Citizen.Wait(500)
end
end
end)
RegisterNetEvent('sync_mafije:staviUVozilo')
AddEventHandler('sync_mafije:staviUVozilo', function()
local playerPed = PlayerPedId()
local coords = GetEntityCoords(playerPed)
if not isHandcuffed then
return
end
if IsAnyVehicleNearPoint(coords, 5.0) then
local vehicle = GetClosestVehicle(coords, 5.0, 0, 71)
if DoesEntityExist(vehicle) then
local maxSeats, freeSeat = GetVehicleMaxNumberOfPassengers(vehicle)
for i=maxSeats - 1, 0, -1 do
if IsVehicleSeatFree(vehicle, i) then
freeSeat = i
break
end
end
if freeSeat then
TaskWarpPedIntoVehicle(playerPed, vehicle, freeSeat)
dragStatus.isDragged = false
end
end
end
end)
RegisterNetEvent('sync_mafije:staviVanVozila')
AddEventHandler('sync_mafije:staviVanVozila', function()
local playerPed = PlayerPedId()
if not IsPedSittingInAnyVehicle(playerPed) then
return
end
local vehicle = GetVehiclePedIsIn(playerPed, false)
TaskLeaveVehicle(playerPed, vehicle, 16)
TriggerEvent('sync_mafije:odvezivanje')
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
local playerPed = PlayerPedId()
if isHandcuffed then
DisableAllControlActions(0) -- Iskljuci sve kontrole
if IsEntityPlayingAnim(playerPed, 'mp_arresting', 'idle', 3) ~= 1 then
ESX.Streaming.RequestAnimDict('mp_arresting', function()
TaskPlayAnim(playerPed, 'mp_arresting', 'idle', 8.0, -8, -1, 49, 0.0, false, false, false)
end)
end
else
Citizen.Wait(500)
end
end
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
PlayerData.job = job
end)
-------MAFIJA DRAWMARKERS i POSLOVI-------
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
local letSleep = true
if PlayerData.job and poslovi then
local playerPed = PlayerPedId()
local coords = GetEntityCoords(playerPed)
local isInMarker, hasExited, letSleep = false, false, false
local currentStation, currentPart, currentPartNum
if Config.Mafije[PlayerData.job.name] == nil then
return
end
for k,v in pairs(Config.Mafije[PlayerData.job.name]) do
if PlayerData.job.grade_name == 'boss' or PlayerData.job.grade_name == 'zamjenik' then
for i=1, #Config.Mafije[PlayerData.job.name]['Armories'], 1 do
local distance = GetDistanceBetweenCoords(coords, Config.Mafije[PlayerData.job.name]['Armories'][i], true)
if distance < Config.DrawDistance then
DrawMarker(Config.MarkerTypes.Oruzarnica, Config.Mafije[PlayerData.job.name]['Armories'][i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, true, false, false, false)
letSleep = false
end
if distance < Config.MarkerSize.x then
isInMarker, currentStation, currentPart, currentPartNum = true, k, 'Armory', i
end
end
end
for i=1, #Config.Mafije[PlayerData.job.name]['ParkirajAuto'], 1 do
local distance = GetDistanceBetweenCoords(coords, Config.Mafije[PlayerData.job.name]['ParkirajAuto'][i], true)
if distance < Config.DrawDistance then
DrawMarker(Config.MarkerTypes.VracanjeAuta, Config.Mafije[PlayerData.job.name]['ParkirajAuto'][i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 255, 0, 0, 100, false, true, 2, true, false, false, false)
letSleep = false
end
if distance < Config.MarkerAuto.x then
isInMarker, currentStation, currentPart, currentPartNum = true, k, 'ParkirajAuto', i
end
end
for i=1, #Config.Mafije[PlayerData.job.name]['Vehicles'], 1 do
local distance = GetDistanceBetweenCoords(coords, Config.Mafije[PlayerData.job.name]['Vehicles'][i], true)
if distance < Config.DrawDistance then
DrawMarker(Config.MarkerTypes.SpawnAuta, Config.Mafije[PlayerData.job.name]['Vehicles'][i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, true, false, false, false)
letSleep = false
end
if distance < Config.MarkerSize.x then
isInMarker, currentStation, currentPart, currentPartNum = true, k, 'Vehicles', i
end
end
if PlayerData.job.name == 'cartel' then
for i=1, #Config.Mafije[PlayerData.job.name]['Brodovi'], 1 do
local distance = GetDistanceBetweenCoords(coords, Config.Mafije[PlayerData.job.name]['Brodovi'][i], true)
if distance < Config.DrawDistance then
DrawMarker(Config.MarkerTypes.Brodovi, Config.Mafije[PlayerData.job.name]['Brodovi'][i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, true, false, false, false)
letSleep = false
end
if distance < Config.MarkerSize.x then
isInMarker, currentStation, currentPart, currentPartNum = true, k, 'Brodovi', i
end
end
end
if PlayerData.job.grade_name == 'boss' then
for i=1, #Config.Mafije[PlayerData.job.name]['BossActions'], 1 do
local distance = GetDistanceBetweenCoords(coords, Config.Mafije[PlayerData.job.name]['BossActions'][i], true)
if distance < Config.DrawDistance then
DrawMarker(Config.MarkerTypes.BossMeni, Config.Mafije[PlayerData.job.name]['BossActions'][i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, true, false, false, false)
letSleep = false
end
if distance < Config.MarkerSize.x then
isInMarker, currentStation, currentPart, currentPartNum = true, k, 'BossActions', i
end
end
end
end
if isInMarker and not HasAlreadyEnteredMarker or (isInMarker and (LastStation ~= currentStation or LastPart ~= currentPart or LastPartNum ~= currentPartNum)) then
if
(LastStation and LastPart and LastPartNum) and
(LastStation ~= currentStation or LastPart ~= currentPart or LastPartNum ~= currentPartNum)
then
TriggerEvent('sync_mafije:hasExitedMarker', LastStation, LastPart, LastPartNum)
hasExited = true
end
HasAlreadyEnteredMarker = true
LastStation = currentStation
LastPart = currentPart
LastPartNum = currentPartNum
TriggerEvent('sync_mafije:hasEnteredMarker', currentStation, currentPart, currentPartNum)
end
if not hasExited and not isInMarker and HasAlreadyEnteredMarker then
HasAlreadyEnteredMarker = false
TriggerEvent('sync_mafije:hasExitedMarker', LastStation, LastPart, LastPartNum)
end
if letSleep then
Citizen.Wait(500)
end
else
Citizen.Wait(500)
end
end
end)
-- Trenutna akcija za markere i kontrole--
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if CurrentAction then
ESX.ShowHelpNotification(CurrentActionMsg)
if IsControlJustReleased(0, 38) then
if CurrentAction == 'menu_cloakroom' then
OpenCloakroomMenu()
elseif CurrentAction == 'menu_armory' then
OpenArmoryMenu(CurrentActionData.station)
elseif CurrentAction == 'menu_vehicle_spawner' then
OtvoriAutoSpawnMenu('car', CurrentActionData.station, CurrentActionData.part, CurrentActionData.partNum)
elseif CurrentAction == 'ParkirajAuto' then
ObrisiVozilo()
elseif CurrentAction == 'Brodovi' then
OtvoriBrodSpawnMenu('car', CurrentActionData.station, CurrentActionData.part, CurrentActionData.partNum)
elseif CurrentAction == 'menu_boss_actions' then
ESX.UI.Menu.CloseAll()
TriggerEvent('esx_society:openBossMenu', PlayerData.job.name, function(data, menu)
menu.close()
CurrentAction = 'menu_boss_actions'
CurrentActionMsg = _U('open_bossmenu')
CurrentActionData = {}
end, { wash = false })
end
CurrentAction = nil
end
end
if PlayerData.job and poslovi then
if IsControlJustReleased(0, 167) and not isDead and not ESX.UI.Menu.IsOpen('default', GetCurrentResourceName(), 'sync_f6') then
OtvoriPosaoMenu()
end
end
end
end)
AddEventHandler('playerSpawned', function(spawn)
isDead = false
end)
AddEventHandler('esx:onPlayerDeath', function(data)
isDead = true
end)
AddEventHandler('onResourceStop', function(resource)
if resource == GetCurrentResourceName() then
TriggerEvent('sync_mafije:odvezivanje')
end
end)
---------------------------------------------------
-- /////////////////////////////////////////////////
-- FUNCKIJE OD POLICEJOBA ZA ARMORYA -
-- ////////////////////////////////////////////////
function OpenGetWeaponMenu()
ESX.TriggerServerCallback('sync_mafije:dbGettajPuske', function(weapons)
local elements = {}
for i=1, #weapons, 1 do
if weapons[i].count > 0 then
table.insert(elements, {
label = 'x' .. weapons[i].count .. ' ' .. ESX.GetWeaponLabel(weapons[i].name),
value = weapons[i].name
})
end
end
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'armory_get_weapon', {
title = 'Uzmi oružje',
align = 'top-left',
elements = elements
}, function(data, menu)
menu.close()
ESX.TriggerServerCallback('sync_mafije:izvadiIzOruzarnice', function()
OpenGetWeaponMenu()
end, data.current.value)
end, function(data, menu)
menu.close()
end)
end)
end
function OpenPutWeaponMenu()
local elements = {}
local playerPed = PlayerPedId()
local weaponList = ESX.GetWeaponList()
for i=1, #weaponList, 1 do
local weaponHash = GetHashKey(weaponList[i].name)
if HasPedGotWeapon(playerPed, weaponHash, false) and weaponList[i].name ~= 'WEAPON_UNARMED' then
table.insert(elements, {
label = weaponList[i].label,
value = weaponList[i].name
})
end
end
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'armory_put_weapon', {
title = 'Ostavi oružje',
align = 'top-left',
elements = elements
}, function(data, menu)
menu.close()
ESX.TriggerServerCallback('sync_mafije:staviUoruzarnicu', function()
OpenPutWeaponMenu()
end, data.current.value, true)
end, function(data, menu)
menu.close()
end)
end
function OpenBuyWeaponsMenu()
local elements = {}
local playerPed = PlayerPedId()
for k,v in ipairs(Config.Oruzje[PlayerData.job.grade_name]) do
local weaponNum, weapon = ESX.GetWeapon(v.weapon)
local components, label = {}
local hasWeapon = HasPedGotWeapon(playerPed, GetHashKey(v.weapon), false)
if v.components then
for i=1, #v.components do
if v.components[i] then
local component = weapon.components[i]
local hasComponent = HasPedGotWeaponComponent(playerPed, GetHashKey(v.weapon), component.hash)
if hasComponent then
label = ('%s: <span style="color:green;">%s</span>'):format(component.label, 'Već imaš taj dodatak')
else
if v.components[i] > 0 then
label = ('%s: <span style="color:green;">%s</span>'):format(component.label, '$'..ESX.Math.GroupDigits(v.components[i]))
else
label = ('%s: <span style="color:green;">%s</span>'):format(component.label, 'Besplatno!')
end
end
table.insert(components, {
label = label,
componentLabel = component.label,
hash = component.hash,
name = component.name,
price = v.components[i],
hasComponent = hasComponent,
componentNum = i
})
end
end
end
if hasWeapon and v.components then
label = ('%s: <span style="color:green;">></span>'):format(weapon.label)
elseif hasWeapon and not v.components then
label = ('%s: <span style="color:green;">%s</span>'):format(weapon.label, 'Već imaš tu pušku!')
else
if v.price > 0 then
label = ('%s: <span style="color:green;">%s</span>'):format(weapon.label, "$"..ESX.Math.GroupDigits(v.price))
else
label = ('%s: <span style="color:green;">%s</span>'):format(weapon.label, 'Besplatno!')
end
end
table.insert(elements, {
label = label,
weaponLabel = weapon.label,
name = weapon.name,
components = components,
price = v.price,
hasWeapon = hasWeapon
})
end
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'armory_buy_weapons', {
title = 'Oružarnica',
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.hasWeapon then
if #data.current.components > 0 then
OpenWeaponComponentShop(data.current.components, data.current.name, menu)
end
else
ESX.TriggerServerCallback('sync_mafije:kupiOruzje', function(bought)
if bought then
if data.current.price > 0 then
ESX.ShowNotification('Kupio si ' .. data.current.weaponLabel .. ' za ~g~$' .. ESX.Math.GroupDigits(data.current.price))
end
menu.close()
OpenBuyWeaponsMenu()
else
ESX.ShowNotification(_U('armory_money'))
end
end, data.current.name, 1)
end
end, function(data, menu)
menu.close()
end)
end
function OpenWeaponComponentShop(components, weaponName, parentShop)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'armory_buy_weapons_components', {
title = _U('armory_componenttitle'),
align = 'top-left',
elements = components
}, function(data, menu)
if data.current.hasComponent then
ESX.ShowNotification(_U('armory_hascomponent'))
else
ESX.TriggerServerCallback('sync_mafije:kupiOruzje', function(bought)
if bought then
if data.current.price > 0 then
ESX.ShowNotification('Kupio si ' .. data.current.componentLabel .. ' za ~g~$' .. ESX.Math.GroupDigits(data.current.price))
end
menu.close()
parentShop.close()
OpenBuyWeaponsMenu()
else
ESX.ShowNotification(_U('armory_money'))
end
end, weaponName, 2, data.current.componentNum)
end
end, function(data, menu)
menu.close()
end)
end
<file_sep># sync_mafije
Please DO NOT rename this script
All credit goes to ESX, sogolisica and me (sync)
## How to add a mafia?
#1. Go in config.lua and copy one of the mafias and edit coordinates
#2. Go in mafia.sql file and copy one of the existing mafias, copy the specific line, and at the end add comma (,) and paste it in another row and edit it by the name of your mafia
#3. Import that sql file
## https://streamable.com/ssoytn <-- VIDEO TUTORIAL
# Better tutorial soon....
| 3e9c060fd8316bec0cd388003e30c915e36d84de | [
"Markdown",
"SQL",
"Lua"
] | 8 | Lua | DamjanPetrovicki/sync_mafije | 11964fdb5a6292e7fba6d82a9b9696e0b5b70d08 | 395108bc21ff6c18b5d0c32fa50da34cf49eb064 |
refs/heads/main | <repo_name>masa-toyama/robust-filter<file_sep>/main.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 11:32:40 2021
@author: user01
"""
import numpy as np
import matplotlib.pyplot as plt
from fmsf_function import fmsf
from ft_fmsf_function import ft_fmsf
#input data is the first row
#sf output is the second row
nyuryoku = np.loadtxt("inputs/input.csv", delimiter=",")
inputs = nyuryoku[:,0]
sf = nyuryoku[:,1]
# fmsf = fmsf(inputs)
# ft_fmsf = ft_fmsf(inputs)
#β-γの値を設定したい場合
beta = sf[0]
ganma = sf[-1]
fmsf = fmsf(inputs, b=beta, rr=ganma)
ft_fmsf = ft_fmsf(inputs,b=beta, rr=ganma)
plt.plot(inputs)
plt.plot(fmsf, label="real")
plt.plot(ft_fmsf, label="ft")
plt.plot(sf, label="SF")
plt.legend()
plt.show()
max_data = max(inputs)
min_data = min(inputs)
gosa_real = (sf - fmsf) / (max_data - min_data)
gosa_imag = (sf - ft_fmsf) / (max_data - min_data)
gosa = (fmsf - ft_fmsf)/(max_data - min_data)
plt.plot(gosa_real[50:150], label="sf-fmsf")
plt.plot(gosa_imag[50:150], label="sf-ft_fmsf")
plt.plot(gosa[50:150], label="fmsf-ft_fmsf")
plt.legend()
plt.show()
plt.plot(gosa_real, label="sf-fmsf")
plt.plot(gosa_imag, label="sf-ft_fmsf")
plt.plot(gosa, label="fmsf-ft_fmsf")
plt.legend()
plt.show()
syutu = np.zeros((200,7))
syutu[:,0] = inputs
syutu[:,1] = sf
syutu[:,2] = fmsf
syutu[:,3] = ft_fmsf
syutu[:,4] = gosa_real
syutu[:,5] = gosa_imag
syutu[:,6] = gosa
np.savetxt("seimitukougakkai.csv", syutu, delimiter=",")
<file_sep>/fmsf_function.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 11:32:25 2021
@author: user01
"""
#実空間FMSF
import numpy as np
import matplotlib.pyplot as plt
from b_r import b_r
def fmsf(inputs_, b=0, rr=0):
#--------------------------------------------
#パラメーター
m = 19
m3 = m + (m-1)*2
z = 100
z_ = z + m3
filter_size = 5 #これだと5λc
#---------------------------------------------
#inputsdata
# nyuryoku = np.loadtxt("inputs/step.csv", delimiter=",")
# inputs_ = nyuryoku[:,0]
# fmsf = nyuryoku[:,1]
len_z = z_
#--------------------------------------------
#2次B-spline
b_spline1 = np.zeros(z_)
b_spline1[:m//2+1] = 1/m
b_spline1[z_-m//2:] = 1/m
ft_b_spline1 = np.fft.fft(b_spline1)
ft_b_spline2 = ft_b_spline1 **2
ft_b_spline3 = ft_b_spline1 * ft_b_spline2
bs1 = np.fft.ifft(ft_b_spline3)
bs = np.zeros(m3)
bs[:m3//2+1] = bs1[:m3//2+1]
bs[m3//2+1:] = bs1[z_-m3//2:]
bs = np.fft.fftshift(bs)
#--------------------------------------------
#b-r
inputs, kk = b_r(inputs_, k=len(inputs_)/5*filter_size/2, b=b, rr=rr)
len_x = len(inputs)
#--------------------------------------------
#SF
sf_y = int(len(inputs_) / 5 * filter_size) + 1 #5λc
sf_x = (int)((sf_y-1)/2 + 1)
ramuda = (sf_y-1)/5/(filter_size/5)
sf = np.zeros(sf_y)
omomi = 0
#フーリエ用SF
for i in range(sf_x):
if i == (sf_x-1):
sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda) / 2
else:
sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda)
if i != 0:
sf[sf_y-i] = sf[i]
omomi += sf[i]*2
else:
omomi += sf[0]
sf /= omomi
print("SF総和:",np.sum(sf))
for i in range(sf_x-1):
if sf[1+i] != sf[sf_y-i-1]:
print("False")
sf = np.fft.fftshift(sf)
plt.plot(sf, label="SF")
plt.legend()
plt.show()
#--------------------------------------------
#離散化
z_data = np.zeros((z_,len(inputs)))
max_data = max(inputs)
min_data = min(inputs)
# max_data = 9
# min_data = 0
step = (max_data - min_data) / z
inputs_after = inputs - min_data + step/2
step_num = inputs_after / step
step_floor = np.floor(step_num)
step_middle = step_floor + 0.5
dif = step_num - step_middle
for i in range(len(inputs)):
# height = (int)(z - step_floor[i] + m3//2)
height = (int)(step_floor[i] + m3//2)
if dif[i] > 0:
z_data[height ,i] = step_floor[i] + 1.5 - step_num[i]
z_data[height+1, i] = 1 - z_data[height ,i]
else:
z_data[height, i] = step_num[i] - step_floor[i] + 0.5
z_data[height-1, i] = 1 - z_data[height ,i]
#------------------------------------------------
#SF,B-Spline 畳み込み
x_, y_ = z_data.shape
fmsf_sf = np.zeros((x_, y_-len(sf)+1))
for k in range(len(fmsf_sf[:,0])):
for i in range(len(fmsf_sf[0,:])):
for j in range(len(sf)):
fmsf_sf[k,i] += z_data[k,i+j] * sf[j]
x_, y_ = fmsf_sf.shape
fmsf_bs = np.zeros((x_-len(bs), y_))
for i in range(len(fmsf_bs[0,:])):
for k in range(len(fmsf_bs[:,0])):
for j in range(len(bs)):
fmsf_bs[k,i] += fmsf_sf[k+j,i] * bs[j]
fmsf_risan = fmsf_bs
#-----------------------------------------------
#Fast M estimation Method
max_num = np.zeros(len(inputs_), dtype=np.int)
fmsf_p = np.zeros(len(inputs_), dtype=np.float64)
for i in range(len(fmsf_risan[0,:])):
max_num[i] = int(fmsf_risan[:,i].argmax())
#最高点計算
fmsf_p[i] = ((fmsf_risan[max_num[i]-1,i] - fmsf_risan[max_num[i],i])
/(fmsf_risan[max_num[i]-1,i] - 2*fmsf_risan[max_num[i],i] + fmsf_risan[max_num[i]+1,i]))# - 0.5)# * step
zz = ((max_num) + fmsf_p)*step + min_data - step/2
#----------------------------------------------
#β-γの拡張文を元に戻す
inputs = inputs[kk:kk+len(inputs_)]
return zz
<file_sep>/b-r.py
# -*- coding: utf-8 -*-
"""
β-γ拡張
20210623-toyama
Created on Wed Jun 23 17:32:40 2021
@author: user01
"""
import numpy as np
import matplotlib.pyplot as plt
#m → 拡張に使うフィルタサイズ
#k → 片側データの拡張サイズ
def b_r(inputs, k=0, b=0, rr=0, m=5, switch=1):
print("β-γ start-------------")
if b==0 and rr==0:
#-----------------------
#parameters
r = int(len(inputs)/m)
filter_len = r*2+1
print("half_filter_size : L/", m, "→",r)
if filter_len >= len(inputs):
print("Error")
if k == 0:
k = len(inputs) / 2
k = int(k)
print("k:", k)
#-----------------------
#filter
sf_y = filter_len
sf_x = (int)((sf_y-1)/2 + 1)
ramuda = (len(inputs)-1)/5
sf = np.zeros(sf_y)
omomi = 0
#SF
for i in range(sf_x):
if i == (sf_x-1):
sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda) / 2
else:
sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda)
if i != 0:
sf[sf_y-i] = sf[i]
omomi += sf[i]*2
else:
omomi += sf[0]
sf /= omomi
print("SF総和 :",np.sum(sf))
for i in range(sf_x-1):
if sf[1+i] != sf[sf_y-i-1]:
print("False")
#-----------------------
#b-r
#20210627 曲げあり
a = 1/(16*((np.sin(np.pi*5/len(inputs)))**4))
print("μ/Δx**3 :", a)
n = len(inputs) - 1
r += 1
#-----------------
#β
b_up = 0
b_down = 0
#分子
for i in range(r):
b1 = sf[i]
b2 = -inputs[i]
t1 = 0
for j in range(i+1, r):
b1 += 2*sf[j]
for j in range(1, r+i):
b2 += sf[j-i] * inputs[j]
for j in range(1, r-i):
b2 -= sf[j+i] * inputs[j]
#T1計算
t1 = (-1) * inputs[0] * (sf[i-1] - sf[i+1])
for j in range(2, r+i):
t1 += sf[j-i] * (inputs[j-1] - 2*inputs[j] + inputs[j+1])
for j in range(2, r-i):
t1 -= sf[j+i] * (inputs[j-1] - 2*inputs[j] + inputs[j+1])
t1 *= (sf[i-1] - sf[i+1])
b_up += b1 * b2 + a*t1
b_up *= (-1)
#分母
for i in range(r):
b3 = sf[i]
for j in range(i+1, r):
b3 += 2*sf[j]
#T2計算
t2 = (sf[i+1] - sf[i-1])**2
b_down += b3**2 + a*t2
b = b_up / b_down
#-------------------
#γ
r_up = 0
r_down = 0
#分子
for i in range(r):
r1 = sf[i]
r2 = -inputs[n-1-i]
for j in range(i+1, r):
r1 += 2*sf[j]
for j in range(1, r+i):
r2 += sf[j-i] * inputs[n-1-j]
for j in range(1, r-i):
r2 -= sf[j+i] * inputs[n-1-j]
#T1計算
t1 = (-1) * inputs[n] * (sf[i-1] - sf[i+1])
for j in range(2, r+i):
t1 += sf[j-i] * (inputs[n-j] - 2*inputs[n-j-1] + inputs[n-j-2])
for j in range(2, r-i):
t1 -= sf[j+i] * (inputs[n-j] - 2*inputs[n-j-1] + inputs[n-j-2])
t1 *= (sf[i-1] - sf[i+1])
r_up += r1 * r2 + a*t1
r_up *= (-1)
#分母
for i in range(r):
r3 = sf[i]
for j in range(i+1, r):
r3 += 2*sf[j]
#T2計算
t2 = (sf[i+1] - sf[i-1])**2
r_down += r3**2 + a*t2
rr = r_up / r_down
print("β :", b)
print("γ :", rr)
else:
print("β,γ is already determined")
if k == 0:
k = len(inputs) / 2
k = int(k)
print("k:", k)
#--------------------------------------
#拡張
inputs[0] = b
inputs[-1] = rr
new_in = np.zeros(len(inputs)+k*2)
b_data = inputs[1:k+1]
b_data = b_data[::-1]
r_data = inputs[-k-1:-1]
r_data = r_data[::-1]
new_in[:k] = 2*b - b_data
new_in[k+len(inputs):] = 2*rr - r_data
new_in[k:k+len(inputs)] = inputs
print("end-------------------\n")
return(new_in, k)
<file_sep>/ft_fmsf_function.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 11:32:39 2021
@author: user01
"""
import numpy as np
import matplotlib.pyplot as plt
from b_r import b_r
def ft_fmsf(inputs_, b=0, rr=0):
#--------------------------------------------
#パラメーター
# m 基本幅
m =21
m3 = m + (m-1)*2
# z 離散化幅
z = 100
z_ = z + m3
#---------------------------------------------
#inputsdata
# nyuryoku = np.loadtxt("inputs/step.csv", delimiter=",")
# inputs_ = nyuryoku[:,0]
# fmsf = nyuryoku[:,1]
len_z = z_
judge = False
if len(inputs_) % 2 == 0:
judge = True
#--------------------------------------------
#2次B-spline
b_spline1 = np.zeros(z_)
b_spline1[:m//2+1] = 1/m
b_spline1[z_-m//2:] = 1/m
ft_b_spline1 = np.fft.fft(b_spline1)
ft_b_spline2 = ft_b_spline1 **2
ft_b_spline3 = ft_b_spline1 * ft_b_spline2
#--------------------------------------------
#b-r
inputs, k = b_r(inputs_, k=0, b=b, rr=rr)
len_x = len(inputs)
#--------------------------------------------
#SF
# sf_y = len(inputs)
# if judge:
# sf_y += 1
# sf_x = (int)((sf_y-1)/2 + 1)
# ramuda = (sf_y-1)/5
# sf = np.zeros(sf_y)
# omomi = 0
# #フーリエ用SF
# for i in range(sf_x):
# if i == (sf_x-1) and judge:
# sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda) / 2
# else:
# sf[i] = np.pi / ramuda * np.sin((np.sqrt(2) * np.pi * i) / ramuda + np.pi / 4) * np.exp((-np.sqrt(2) * np.pi * i) / ramuda)
# if i != 0:
# sf[sf_y-i] = sf[i]
# omomi += sf[i]*2
# else:
# omomi += sf[0]
# sf /= omomi
# print("SF総和:",np.sum(sf))
# for i in range(sf_x-1):
# if sf[1+i] != sf[sf_y-i-1]:
# print("False")
# if judge:
# sf = np.delete(sf, sf_x)
# ft_sf = np.fft.fft(sf)
# # plt.plot(sf)
# # plt.show()
#3次スプライン(SF)
l = len(inputs)
ft_sf = np.zeros(l)
for i in range(l):
ft_sf[i] = (1 + (np.sin(np.pi*i/l) / np.sin(np.pi*5/len(inputs_)))**(2*2))**(-1)
plt.plot(ft_sf, label="ft_sf")
plt.legend()
plt.show()
#--------------------------------------------
#離散化→DFT
z_data = np.zeros((z_,len(inputs)))
max_data = max(inputs)
min_data = min(inputs)
step = (max_data - min_data) / z
inputs_after = inputs - min_data #+ step/2
step_num = inputs_after / step
step_floor = np.floor(step_num)
step_middle = step_floor + 0.5
dif = step_num - step_middle
for i in range(len(inputs)):
# height = (int)(z - step_floor[i] + m3//2)
height = (int)(step_floor[i] + m3//2)
if dif[i] > 0:
z_data[height ,i] = step_floor[i] + 1.5 - step_num[i]
z_data[height+1, i] = 1 - z_data[height ,i]
else:
z_data[height, i] = step_num[i] - step_floor[i] + 0.5
z_data[height-1, i] = 1 - z_data[height ,i]
ft_z_data = np.fft.ifftshift(z_data)
ft_z_data = np.fft.fft2(ft_z_data)
#------------------------------------------------
#DFT-FMSF計算→IDFT
ft_fmsf = np.zeros(z_data.shape, dtype=np.complex)
for i in range(len_z):
ft_fmsf[i,:] = ft_z_data[i,:] * ft_sf
for i in range(len_x):
ft_fmsf[:,i] = ft_fmsf[:,i] * ft_b_spline3
fmsf_risan1 = np.fft.ifft2(ft_fmsf)
fmsf_risan = np.zeros(len_x, dtype=np.float64)
fmsf_risan = np.fft.fftshift(fmsf_risan1)
#-----------------------------------------------
#Fast M estimation Method
max_num = np.zeros(len_x, dtype=np.int)
fmsf_p = np.zeros(len_x, dtype=np.float64)
for i in range(len_x):
max_num[i] = int(fmsf_risan[:,i].argmax())
#最高点計算
fmsf_p[i] = ((fmsf_risan[max_num[i]-1,i] - fmsf_risan[max_num[i],i])
/(fmsf_risan[max_num[i]-1,i] - 2*fmsf_risan[max_num[i],i] + fmsf_risan[max_num[i]+1,i]))# - 0.5)# * step
zz = ((max_num - m3//2) + fmsf_p)*step + min_data #- step/2
#----------------------------------------------
#β-γの拡張文を元に戻す
zzz = zz[k:k+len(inputs_)]
inputs = inputs[k:k+len(inputs_)]
# plt.plot(inputs)
# plt.plot(zzz, label="ft")
# #plt.plot(fmsf, label="fmsf")
# plt.legend()
# plt.show()
# gosa = (zzz - fmsf) / (max_data - min_data)
# plt.plot(gosa[30:170], label="pv")
# plt.legend()
# plt.show()
return zzz
| 584df8ac9776fc1e7fd4da583a63d5bc7541a0ab | [
"Python"
] | 4 | Python | masa-toyama/robust-filter | 38363ca7d421742755e9eae4201a54933cfbabcd | c011d673ac7ae3f37ae88a52d330afafcda6c8a7 |
refs/heads/master | <repo_name>shubham-crux/ipl2020<file_sep>/amdocsipl/score_app/migrations/0001_initial.py
# Generated by Django 3.1 on 2020-09-06 15:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Matches',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('matchtime', models.CharField(max_length=10)),
],
options={
'db_table': 'Matches',
},
),
migrations.CreateModel(
name='Players',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('datejoined', models.DateField()),
],
options={
'db_table': 'Players',
},
),
migrations.CreateModel(
name='Rankings',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rank', models.IntegerField()),
('points', models.IntegerField()),
],
options={
'db_table': 'Rankings',
},
),
]
<file_sep>/amdocsipl/score_app/models.py
from django.db import models
from datetime import date
from django.urls import reverse
# Create your models here.
class Matches(models.Model):
matchname = models.CharField(max_length=256, default="")
matchdate = models.DateField(default=date.today, blank=True)
matchday = models.CharField(max_length=20, blank=True)
matchtime = models.CharField(max_length=10)
def __str__(self):
return str(self.id) + ',' + str(self.matchname) + "," + str(self.matchdate)
class Players(models.Model):
playername = models.CharField(max_length=100, default="")
pointsinvested = models.IntegerField(default=0)
datejoined = models.DateField(default=date.today)
def __str__(self):
return str(self.playername)
class Rankings(models.Model):
rank = models.IntegerField()
points = models.IntegerField()
def __str__(self):
return str(self.rank)
class Wins(models.Model):
matchdetail = models.ManyToManyField(Matches)
playerdetail = models.ManyToManyField(Players)
rankdetail = models.ManyToManyField(Rankings)
pointswon = models.IntegerField()
windate = models.DateField(default=date.today)
def __str__(self):
for player in self.playerdetail.all():
return str(player) +","+ str(self.windate)
class Leaders(models.Model):
distinctplayer = models.ForeignKey('Players', on_delete=models.CASCADE)
totalpoints = models.IntegerField()
class Meta:
ordering = ['-totalpoints']
def __str__(self):
return str(self.distinctplayer)<file_sep>/amdocsipl/score_app/migrations/0002_auto_20200907_1146.py
# Generated by Django 3.1 on 2020-09-07 06:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('score_app', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='matches',
table=None,
),
migrations.AlterModelTable(
name='players',
table=None,
),
migrations.AlterModelTable(
name='rankings',
table=None,
),
]
<file_sep>/amdocsipl/templates/match_leader.html
{% extends "base.html" %}
{% block body_block %}
<div class="jumbotron">
<h2> LeaderBoard!</h2>
<div class="table-condensed">
<table class="table table-striped table-dark">
<thead>
<tr>
<th>Player</th>
<th>PointsWon</th>
</tr>
</thead>
{% for leader in match_leaders %}
<tbody>
<tr style="font-family: 'Enriqueta', arial, serif; line-height: 1.25; margin: 0 0 10px; font-size: 14px; font-weight: bold;">
<td> {{ leader.distinctplayer }} </td>
<td>{{ leader.totalpoints }}</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
</div>
{% endblock %}<file_sep>/amdocsipl/score_app/migrations/0003_auto_20200907_1209.py
# Generated by Django 3.1 on 2020-09-07 06:39
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('score_app', '0002_auto_20200907_1146'),
]
operations = [
migrations.AddField(
model_name='matches',
name='matchdate',
field=models.DateField(blank=True, default=datetime.date.today),
),
migrations.AddField(
model_name='matches',
name='matchday',
field=models.CharField(blank=True, max_length=20),
),
migrations.AddField(
model_name='matches',
name='matchname',
field=models.CharField(default='', max_length=256),
),
migrations.AddField(
model_name='players',
name='playername',
field=models.CharField(default='', max_length=100),
),
migrations.AddField(
model_name='players',
name='pointsinvested',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='players',
name='datejoined',
field=models.DateField(default=datetime.date.today),
),
]
<file_sep>/amdocsipl/score_app/views.py
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, CreateView
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from . import models
from .filters import WinsFilter
from django.db.models import Sum
# from . import models
# from django.urls import reverse_lazy
# Create your views here.
class IndexView(TemplateView):
context_object_name = 'index'
template_name = 'index.html'
@login_required
def user_logout(reqeust):
logout(reqeust)
return HttpResponseRedirect(reverse('index'))
class MatchDetailsView(ListView):
context_object_name = 'matches_detail'
model = models.Matches
template_name = 'match_details.html'
class MatchRulesView(ListView):
context_object_name = 'match_rules'
model = models.Rankings
template_name = 'match_rules.html'
class MatchPlayersView(ListView):
context_object_name = 'match_players'
model = models.Players
template_name = 'match_players.html'
class MatchWinsView(ListView):
model = models.Wins
template_name = 'match_wins.html'
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = WinsFilter(self.request.GET, queryset=self.queryset)
return context
class MatchLeadersView(ListView):
context_object_name = 'match_leaders'
model = models.Leaders
template_name = 'match_leader.html'<file_sep>/amdocsipl/score_app/migrations/0004_wins.py
# Generated by Django 3.1 on 2020-09-08 12:35
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('score_app', '0003_auto_20200907_1209'),
]
operations = [
migrations.CreateModel(
name='Wins',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pointswon', models.IntegerField()),
('windate', models.DateField(default=datetime.date.today)),
('matchdetail', models.ManyToManyField(to='score_app.Matches')),
('playerdetail', models.ManyToManyField(to='score_app.Players')),
('rankdetail', models.ManyToManyField(to='score_app.Rankings')),
],
),
]
<file_sep>/amdocsipl/score_app/filters.py
import django_filters
from .models import Wins
from django import forms
class WinsFilter(django_filters.FilterSet):
class Meta:
model = Wins
fields = ['playerdetail', 'windate']
<file_sep>/amdocsipl/score_app/admin.py
from django.contrib import admin
from score_app.models import Matches, Players, Rankings, Wins, Leaders
# Register your models here.
admin.site.register(Matches)
admin.site.register(Players)
admin.site.register(Rankings)
admin.site.register(Wins)
admin.site.register(Leaders)<file_sep>/amdocsipl/templates/base.html
<!DOCTYPE html>
{% load static %}
{% load socialaccount %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<style>
body {
background-image: url({% static 'images/background.jpg' %});
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-dark">
<div>
<ul class="nav justify-content-end">
<li style="color:white;" > <a class="navbar-brand" style="color:white;" href="{% url 'index' %}">MDOCS IPL2020</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'matches'%}">SCHEDULE</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'rules'%}">RULES</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'players'%}">PLAYERS</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'wins'%}">WINNINGS</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'leaders'%}">LEADERBOARD</a> </li>
<li class="nav-item" style="padding: 20px;"> <a class="navbar-link" href="{% url 'admin:index'%}">ADMIN</a> </li>
{% if user.is_authenticated %}
<li class="nav-item" style="padding: 20px; align:right"> <a class="navbar-link" href="{% url 'logout' %}"> {{ user.username }}, Logout here!</a> </li>
{% else %}
<li class="nav-item" style="padding: 20px; align:right"> <a href="{% provider_login_url 'google' %}">Login with Google</a> </li>
{% endif %}
</ul>
</div>
</nav>
<div class="container">
{% block body_block %}
{% endblock %}
</div>
</body>
</html><file_sep>/amdocsipl/score_app/urls.py
from django.urls import path
from basic_app import views
# Template tagging
app_name = 'score_app'
urlpatterns = [
]<file_sep>/amdocsipl/score_app/apps.py
from django.apps import AppConfig
class ScoreAppConfig(AppConfig):
name = 'score_app'
| 99fcf049aa6f3b9747efb7c01cff4d1b9f9ba4d4 | [
"Python",
"HTML"
] | 12 | Python | shubham-crux/ipl2020 | 478ad65d625a278a5f33678c3835deb56505849e | 9ef48c3f00a372d375bc67337f1f60f7955b52a5 |
refs/heads/master | <file_sep>'use strict';
var _ = require('lodash');
var config = require('../../config/environment');
var twoforone = require('./coupondiscount').coupondiscount;
var MongoClient,
url = config.mongo.uri;
MongoClient = require('mongodb').MongoClient;
// require here other discounts
// var GenericDiscount = require('genericDiscount');
var DiscountChain = function(cblogic) {
this.discount_logic = cblogic;
this.next = null;
};
DiscountChain.prototype = {
calculate: function(cart, discounts, cb) {
var that = this;
this.discount_logic && this.discount_logic(cart, function(ds){
// add the generated discount to the discounts collection
//ds && _.extend(discounts, ds);
ds && discounts.push.apply(discounts, ds);
if(that.next){
that.next.calculate(cart, discounts, cb);
}else{
cb(discounts);
}
});
},
// set the stack that comes next in the chain
setNextDiscount: function(stack) {
this.next = stack;
}
};
/*
* Get the generic discounts, when the cart has pendingDiscounts
* */
function collectgeneric(cart, cb){
if (cart.pendingDiscounts && _.contains(cart.pendingDiscounts, 'BYO')){
MongoClient.connect(url, {}, function(err, db) {
var discounts = db.collection('discounts');
//discounts.find({category: 'generic'}).toArray(function(err, docs){
discounts.findOne({_id: 'BYO'}, function(err, d){
db.close();
if(d){
// buscar en la carta los items que tengan categoria d.applyToCategory
var elems = _.filter(cart.items, function(i){return i.category === d.applyToCategory;});
if (elems.length) {
d.quantity = _.reduce(_.pluck(elems, 'quantity'), function(sum, num){
return sum + num;
});
cb([d]);
}else{
cb([]);
}
}
});
});
}else{
cb([]);
}
}
/*
* Internet Service Discount
* */
function internetdiscount(cart, cb){
if (cart.pendingDiscounts && _.contains(cart.pendingDiscounts, 'internetservice')){
MongoClient.connect(url, {}, function(err, db) {
// first check if there is a discount for internet service in the collection
var discounts = db.collection('discounts'),
ds = [];
discounts.findOne({_id: 'internetservice'}, function(err, discount){
//find the items with category equal to the one in the discount
if(discount && _.some(cart.items, {category: discount.applyToItemCategory})){
// add the discount to the discount chain
ds.push(discount.discount);
}
db.close();
console.log('DEBUG', ds);
cb(ds);
});
});
}else{
cb([]);
}
}
/*
* Chain or responsability entry point
* */
var DiscountsMachine = function () {
// create the chained discounts, add here the imported
// discounts
//add the link for the chain internet discount
var genericDiscount = new DiscountChain(collectgeneric),
internetDiscount = new DiscountChain(internetdiscount),
twoforoneDiscount = new DiscountChain(twoforone);
// byclientDiscount = new ByClientDiscount()
// internetDiscount = new InternetDiscount()
genericDiscount.setNextDiscount(internetDiscount);
internetDiscount.setNextDiscount(twoforoneDiscount);
// Set the top stack as a property
this.discountsStack = genericDiscount;
};
DiscountsMachine.prototype.getDiscounts = function(cart, cb) {
var discounts = [];
this.discountsStack.calculate(cart, discounts, cb);
};
module.exports.DiscountsMachine = DiscountsMachine;
<file_sep># kpos
Punto de Venta (POS) simple usando MEAN
## howto
EndPoint:
yo angular-fullstack:endpoint message
| 1bcf7167904fca2fc3911362b4abc41ca400eee7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | janinatatiana/kpos | 2188832ee91a9c7aed5cecc89deb9ae3ba155972 | 2068e01a299fb6bbf31a0a15c23c244dfe164183 |
refs/heads/main | <repo_name>Saltefanden/Algorithms_Cormen_py<file_sep>/Ch4/test_general.py
import pytest
from generalch4 import myList
def test_add_one():
print('lol')
assert myList([1,2,3]).addone() == [2,3,4]
#Ikke den pæneste opsætning, se om du kan lave det som et dictionary udenfor med test + ids
@pytest.mark.parametrize("test_input, expected",[([-1,-1,1,1,1,-1-1], (3,2,5)), #0Regular test
([13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7], (43,7,11)), #1As per the book with updated indexing
([-1, -1], (-1,0,1)), #2What to return in this case?
([-2,-1], (-1,1,2)), #3Ensure that not just the left sum gets returned
([], (None,None,None)), #4Handle empty lists
([14,14,14,14], (14*4, 0, 4)), #5Handle entire list
([-300,-300,100,-300,-300], (100,2,3)), #6Handle middle only
([140,0,-100,100,40,0, 0],(180,0,5) ), #7Another regular john
([10, 0, 0, 0, 0, 0], (10,0,1)), #8 Are extra zeros added?
([1,2,1,-4,4], (4, 0,3)), #9Right preference? Right over middle at least
([1,2,1,0,0,0,-4,4], (4, 0,3)), #10Right preference? Right over middle at least
([0,-1,2,-3,4,-5],(4,4,5)),#lort
])
@pytest.mark.parametrize("Function", ["myList(test_input).largest_sublist()", "myList(test_input).largest_sublist2()"], ids=['slow', 'fast'])
def test_largest_sub_array(test_input, expected, Function):
assert eval(Function) == expected<file_sep>/Ch4/Code_to_be_tested.py
class myList(list):
def __init__(self, the_list):
super().__init__(the_list)
def insertion_sort(self, reverse = False):
for i in range(1,len(self)):
key = self[i]
j = i-1
if not reverse:
while j>=0 and self[j]>key:
self[j+1] = self[j]
j -= 1
else:
while j>=0 and self[j]<key:
self[j+1] = self[j]
j -= 1
self[j+1] = key
return self
def search(self, val):
"""Searches for a value in the array, if the value is present, return the index"""
for i in range(len(self)):
if self[i] == val:
return i
return None
def selection_sort(self):
for i in range(len(self)-1): # c1 * (n-1)
minidx = i # c2 * (n-2)
minval = self[i] # c3 * (n-2)
for idx, val in enumerate(self[i:]): # c4 * sum( ti , i = 1..n-1), ti = n-i gives n**2 running time
if val < minval: # c5 * --||--
minval, minidx = val, idx+i # c6 * et eller andet hvor ofte det er sandt
self[i], self[minidx] = minval, self[i] # c7 * (n-2)
return self
@staticmethod
def merge(arr1, arr2):
returnlist = []
i = j = 0
while True:
if i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
returnlist.append(arr1[i])
i += 1
else:
returnlist.append(arr2[j])
j += 1
else:
returnlist.extend(arr1[i:] + arr2[j:])
break
return returnlist
def merge_sort(self):
returnarray = []
size = len(self)
if size>1: #såfremt den ikke er hammerkort yo
rhs = myList(self[:size//2]).merge_sort()
lhs = myList(self[size//2:]).merge_sort()
returnarray = myList.merge(rhs, lhs)
else:
returnarray = self
return myList(returnarray)
def bsearch_rec(self, val, enforce=False):
#if enforce and val not in self: #is this step actually linear?!
# return None
n = len(self)
if n == 1 and enforce and val != self[0]:
return None
if n == 0:
if enforce:
return None
return 0
midpoint = self[n//2]
returnval = False
if val == midpoint:
return n//2
elif val < midpoint:
returnval = myList(self[:n//2]).bsearch_rec(val, enforce = enforce)
elif val > midpoint and not returnval:
returnval = myList(self[n//2+1:]).bsearch_rec(val, enforce = enforce)
if returnval is not None:
returnval += n//2 +1
else:
raise Exception("Logic is flawed you absolute nerd")
return returnval
def bsearch(self,val, enforce=False):
"""Will return the element at which the val will fit into the array, but not determine
whether or not the element is present in the array"""
#if enforce and val not in self: #is this step actually linear?!
# return None
returnval = 0
while True:
n = len(self)
if n == 1 and enforce and val != self[0]:
return None
if n == 0:
if enforce:
return None
return returnval
midpoint = self[n//2]
if val == midpoint:
returnval += n//2
return returnval
elif val < midpoint:
self = self[:n//2]
elif val > midpoint:
self = self[n//2 + 1: ]
returnval += n//2+1
else:
raise Exception("logic flawed nerde")
def insertion_sort_b(self):
"""Implementing insertion sort with a binary search to insert key in already sorted list.
Assuming the list still needs to adjust elements at higher indexes when inserting, this
method does not ensure a Th(n lg n) running time """
for i in range(1,len(self)): # ~n *
key = self[i]
del self[i]
idx = myList(self[:i]).bsearch(key) # lg n = n lg n
self.insert(idx, key) # n = n**2 ^[1]
# [1]: https://wiki.python.org/moin/TimeComplexity
return self
def search_sum(self, val):
"""Finds two elements in the arr, (x, y), which sum to val: y = val - x"""
srt_arr = self.merge_sort() # n * lg n
for i in range(len(srt_arr)): # n *
x = srt_arr[i]
y = val - x
# only needs to search from i and up, since x has been checked for
# all values below by previous iterations of loop
returnidx = myList(srt_arr[i:]).bsearch_rec(y, enforce = True) # lg n = n lg n
if returnidx:
return (x,y)
return None
class binarylist(list):
def __init__(self, *args):
super().__init__([*args])
for i in range(len(args)):
if self[i] not in [0,1]:
raise ValueError("Element {} not binary".format(i))
@staticmethod
def _add_element(x,y):
return int((x or y) and not (x and y))
@staticmethod
def _carry_over(x,y):
return int(x and y)
def __add__(self, other):
if self.__len__() >= other.__len__():
longest = self
shortest = other
else:
longest = other
shortest = self
#New array is at most one longer than the longest
resultsize = longest.__len__() +1
resultarray = [0 for i in range(resultsize)]
carry = 0
for i in range(1,resultsize):
if i <= shortest.__len__():
# Add two elements, no carry considered
temp_carry = binarylist._carry_over(self[-i], other[-i])
resultarray[-i] = binarylist._add_element(self[-i], other[-i])
# Finally add the carry and update next carry
resultarray[-i], carry = binarylist._add_element(resultarray[-i], carry), binarylist._carry_over(resultarray[-i], carry) + temp_carry
assert carry < 2, "Miscalculated carry"
else:
resultarray[-i], carry = binarylist._add_element(longest[-i], carry), 0
return binarylist(*resultarray)
def parse(self):
runsum = 0
for i in range(len(self)):
runsum += 2**(len(self)-1 - i) * self[i]
return runsum
<file_sep>/Ch4/learn_to_code_tests_yourself.py
class Test():
def test(func):
def inner():
try:
func()
except Exception as ex:
print(ex.args[0])
print(*ex.args, 'at')
else:
print("Code executed with return value 0")
return inner
@test
def tstfun():
assert 5+8 == 13, "Dillermand"
assert 3+2 == 5, "Dollermand"
assert myList([1,4,2,1]).insertion_sort() == [1,1,2,4,1]
class myList(list):
def __init__(self, the_list):
super().__init__(the_list)
def insertion_sort(self, reverse = False):
for i in range(1,len(self)):
key = self[i]
j = i-1
if not reverse:
while j>=0 and self[j]>key:
self[j+1] = self[j]
j -= 1
else:
while j>=0 and self[j]<key:
self[j+1] = self[j]
j -= 1
self[j+1] = key
return self
def main():
Test.tstfun()
if __name__ == '__main__':
main()<file_sep>/README.md
# Algorithms_Cormen
<file_sep>/Ch2/test.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 13:45:58 2021
@author: nickl
"""
from os import path
import random as rd
class ArrayToSort:
trainingArray = [5, 2, 4, 6, 1, 3]
def __init__(self, array=trainingArray):
self.array = array
self.length = len(self.array)
def insertion_sort(self):
for i in range(1, self.length):
key = self.array[i]
j = i-1
while j+1 and self.array[j] > key:
self.array[j+1] = self.array[j]
j -= 1
self.array[j+1] = key
print(self.array)
# @staticmethod
# def generate_training_datafile(n):
# if not path.exists('Autogenerated_training_data.csv'):
# atd_file = open('Autogenerated_training_data.csv','w')
# for i in range(n-1):
# atd_file.write(str(rd.uniform(0,100)) + ', ' )
# atd_file.write(str(rd.uniform(0,100)))
# atd_file.close()
# else:
# pass
def merge_sort(self):
self.array
def random_array(self, length):
self.length = length
self.array = [rd.randrange(0,100) for i in range(length)]
<file_sep>/main.py
print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
import Ch4.general
#Det virker at starte fra main som har pakken None og så ellers lade moduler importere hinanden som havde de samme path som main<file_sep>/Ch4/test_learning_pytest.py
import Code_to_be_tested as extmod
import pytest
# %% Had tons of boilerplate for each sortmethod
# def test_sort():
# assert extmod.myList([3,2,1]).insertion_sort() == [1,2,3]
# assert extmod.myList([1]).insertion_sort() == [1]
# assert extmod.myList([]).insertion_sort() == []
# %% Reduce some of the boilerplate by using a simple fixture
@pytest.fixture
def input_list():
return [1,2,3,2,1,0,1]
@pytest.fixture
def expected_list():
return [0,1,1,1,2,2,3]
def test_insertionsort(input_list,expected_list):
assert extmod.myList(input_list).insertion_sort() == expected_list
def test_mergesort(input_list,expected_list):
assert extmod.myList(input_list).merge_sort() == expected_list
# %% Reduce more by adding parametrized tests
ids = ["Empty", "Single element", "Multi-same element", "Pre-sorted",
"Unsorted"]
@pytest.fixture(params=[[], [0], [1,1], [1,2,3], [1,2,3,2,1,0,1]], ids=ids)
def inp_list(request):
return request.param
@pytest.fixture
def exp_list(inp_list):
return sorted(inp_list)
def test_inssort(inp_list, exp_list):
assert extmod.myList(inp_list).insertion_sort() == exp_list
def test_mergesrt(inp_list, exp_list):
assert extmod.myList(inp_list).merge_sort() == exp_list
# Fortsæt her: https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session
# as testing two lists for equality is at the worst case Th(n) use
# assert all(array[i-1] <= array[i] for i in range(1,length(array)))
# rather than providing a pre sorted list for checks --- Something about the elements also being present
# Alternatively just do the sorted first check simple, then add the elements present,
# then add full equality of lists.
# %% Used for examples in online material.
class Fruit:
def __init__(self, name):
self.name = name
# def __eq__(self, other): # Ensures that equality tests are based on name only and not memory address
# return self.name == other.name
@pytest.fixture
def my_fruit():
return Fruit("apple")
@pytest.fixture
def fruit_basket(my_fruit):
return [Fruit("banana"), my_fruit]
# Passing fixtures as arguments to testfunctions finds the fixtures, runs them, and inserts any
# return values as the argument to the function. - Thus here we have my_fruit taking the place
# of the fixtures returnvalue: Fruit('apple'). In the fruit_basket fixture we already call the
# my_fruit fixture, where once again the return value of Fruit('apple') is inserted. Thus fruit
# basket in total returns the list [Fruit("banana"), Fruit("apple")] and this is taking the place
# of the fruit_basket fixture name in the test function. We thus check if Fruit("apple") is in
# [Fruit("banana"), Fruit("apple")]. The equality operator of the Fruit class is overloaded such
# that only equality of names are enough to return true. (Somethingsomething about the objects
# themselves might be different instances of the class? Might not, depending on how the fixture
# is called) The fixtures are called each time they are used, so the objects would in fact be
# different instances of the Fruit class - Disproved by removing the overriding of __eq__. This
# would only be the case if different tests had been calling the same fixture.
# The documentation mentions that as well:
# https://docs.pytest.org/en/stable/fixture.html#fixtures-can-be-requested-more-than-once-per-test-return-values-are-cached|
def test_my_fruit_in_basket(my_fruit, fruit_basket):
assert my_fruit in fruit_basket
assert my_fruit == fruit_basket[1]
# class Fruit:
# def __init__(self, name):
# self.name = name
# self.cubed = False
# def cube(self):
# self.cubed = True
# class FruitSalad:
# def __init__(self, *fruit_bowl):
# self.fruit = fruit_bowl
# self._cube_fruit()
# def _cube_fruit(self):
# for fruit in self.fruit:
# fruit.cube()
"""Last idea is to add the unittest to both implementation algorithms following this example https://stackoverflow.com/questions/29939842/how-to-reuse-the-same-tests-to-test-different-implementations
Use parameterized tests with your tested functions as a parameter.
For example, using ddt module for parameterized testing:
def sum1(list1):
return sum(list1)
def sum2(list1):
res = 0
for x in list1:
res += x
return res
import unittest
from ddt import ddt, data
@ddt
class SumTest(unittest.TestCase):
@data(sum1, sum2)
def test_sum(self, param):
self.assertEqual(param([1, 2, 3]), 6)
if __name__ == '__main__':
unittest.main()
In this example, you have two functions "sum1" and "sum2" implementing the same algorithm: summing of list elements. In your test class, you have only one testing method "test_sum" that takes the concrete summing function as a parameter. The two summing functions are specified as a list of values for a parameterized test.
You can install "ddt" with pip:
__________________________________________
Remember you can have multiple parameters in your fixtures, and they will run all combinations of both
SEE last line above this paragraph https://docs.pytest.org/en/stable/parametrize.html#basic-pytest-generate-tests-example
"""<file_sep>/Ch4/generalch4.py
# INTET AF FØLGENDE VIRKER
# print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
# from Ch2 import general as g
# print(g.myList([2,3,5,1,3,6,23,0,-12,1,4,2,5]).merge_sort())
# print("We did it boissss")
# from ..Ch2.general import myList
# print('lol')
#%% Virker sgu nærmest heller ikke
# import sys
# sys.path.append('./Ch2')
# from general import myList
# # Herfra kan vi monkey patche myList.
# # Ydermere fucking pytest virker ikke hvis der er en __init__ fil i samme mappe..... omfg https://stackoverflow.com/questions/41748464/pytest-cannot-import-module-while-python-can
# def addone(my_list):
# returnlist = []
# for i, val in enumerate(my_list):
# returnlist.append(val +1)
# return returnlist
# myList.addone = addone
# if __name__ == '__main__':
# lol = myList([1,2,3])
# lol = lol.addone()
# print(lol)
#%% Det her virker til gengæld på pytest også, så det er muligt at lave monkey patchede tests uden at gøre mere for det.
# from Code_to_be_tested import myList
# def addone(my_list):
# returnlist = []
# for i, val in enumerate(my_list):
# returnlist.append(val +1)
# return returnlist
# myList.addone = addone
# %% Det her er samlet set bedst? Vi har nu fjernet alle tomme __init__ filer som pytest ikke kan lide og som heller ikke gør nogen forskel siden python 3.x tidligt
# For fremtidige moduler der skal bruge denne funktion: https://stackoverflow.com/questions/19545982/monkey-patching-a-class-in-another-module-in-python
import sys
sys.path.insert(1,'../Ch2')
from general import myList
def addone(my_list):
returnlist = []
for i, val in enumerate(my_list):
returnlist.append(val +1)
return returnlist
myList.addone = addone
def largest_cross_array(my_list, start, mid, stop):
sum = 0
leftsum, rightsum = None, None
for i in range(mid-1, start-1, -1): # mid-1
sum += my_list[i]
if leftsum is None or sum > leftsum:
leftsum = sum
startidx = i
if leftsum is None:
leftsum = 0
startidx = mid
sum = 0
for i in range(mid,stop):
sum += my_list[i]
if rightsum is None or sum > rightsum:
rightsum = sum
stopidx = i+1 #As a range will have to give the end of range value.
if rightsum is None:
rightsum = 0
startidx = mid
return leftsum + rightsum, startidx, stopidx
def largest_sublist(my_list, start=0, stop=None):
if stop is None:
stop = len(my_list)
if stop == 0:
return (None, None, None)
if start == stop-1:
return my_list[start], start, stop
mid = (stop + start) //2
#Either the largest sublist is to the left
sumleft, startleft, stopleft = largest_sublist(my_list, start=start, stop=mid)
#or the right
sumright, startright, stopright = largest_sublist(my_list,start=mid, stop=stop)
#or cross the middle
crosssum, startcross, stopcross = largest_cross_array(my_list, start=start, stop=stop, mid=mid)
if sumleft >= sumright and sumleft >= crosssum:
return sumleft, startleft, stopleft
if crosssum >= sumleft and crosssum >= sumright:
return crosssum, startcross, stopcross
if sumright >= sumleft and crosssum <= sumright:
return sumright, startright, stopright
#myList.largest_cross_array = largest_cross_array
myList.largest_sublist = largest_sublist
def largest_sublist2(my_list):
if len(my_list) == 0:
return (None, None, None)
largest_sum, startidx, stopidx = my_list[0], 0, 1
survey_sum, survey_start = 0, 0
for i, val in enumerate(my_list):
survey_sum += val
if survey_sum > largest_sum:
largest_sum = survey_sum
if survey_sum > 0:
stopidx = i+1
startidx = survey_start
elif survey_sum <= 0:
startidx = i
stopidx = i+1
survey_sum = 0
else:
if survey_sum < 0:
survey_sum = 0
survey_start = i+1
return largest_sum, startidx, stopidx
myList.largest_sublist2 = largest_sublist2<file_sep>/Ch4/learn_unittests.py
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('Diller'.upper(), 'DIL2LER')
def main():
unittest.main()
if __name__ == '__main__':
main()
# python -m unittest -v test_module | 0db9ddaf81b9c3769caf985650d5ce1f7f86b324 | [
"Markdown",
"Python"
] | 9 | Python | Saltefanden/Algorithms_Cormen_py | ee88d50069a4c9e604ab269357b9a723b159da88 | 63ee7305edfcb28275f2296fb79bccd2d40f3494 |
refs/heads/master | <repo_name>JFD3D/Coomb-1<file_sep>/Arbytrage/WelcomeViewController.swift
//
// WelcomeViewController.swift
// Arbytrage
//
// Created by <NAME> on 8/16/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
import Alamofire
class WelcomeViewController: UIViewController {
var currency: String! = "BTC" {
didSet {
self.currentLabel.text = "Current \(currency) to USD"
}
}
var currencyValue: Double! {
didSet {
currencyValue = Double(round(1000*currencyValue)/1000)
self.currencyButton.setTitle("$\(currencyValue)", forState: UIControlState.Normal)
self.currencyButton.sizeToFit()
}
}
@IBOutlet weak var currentLabel: UILabel!
@IBOutlet weak var currencyButton: UIButton!
@IBOutlet weak var switchLabel: UILabel!
@IBOutlet weak var `switch`: UISwitch!
@IBOutlet weak var buyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
didSwitch()
currentLabel.text = "Current \(currency) to USD"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
Alamofire.request(.GET, "http://coinmarketcap-nexuist.rhcloud.com/api/\(currency)/price")
.responseJSON {
let usd = $0.2.value!["usd"]
dispatch_async(dispatch_get_main_queue()) {
self.currencyValue = (usd as! NSString).doubleValue
}
}
delay(Double(rand() % 10)) {
TSMessage.showNotificationWithTitle("\(self.currency) now at $\(self.currencyValue)! Time to buy.", type: .Success)
}
}
@IBAction func didSelectPickCurrency(sender: AnyObject) {
self.performSegueWithIdentifier("segueToPicker", sender: nil)
}
@IBAction func didHitManualBuy() {
UIApplication.sharedApplication().openURL(NSURL(string: "https://blockchain.info/wallet/login")!)
}
@IBAction func didSwitch() {
buyButton.hidden = `switch`.on
switchLabel.text = `switch`.on ? "Auto Buy Notifications" : "Manual Selection"
}
@IBAction func unwindToWelcome(sender: UIStoryboardSegue) {}
}
<file_sep>/Arbytrage/UIViewControllerExtension.swift
//
// UIViewControllerExtension.swift
// Arbytrage
//
// Created by <NAME> on 8/16/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
extension UIViewController {
public func performSegueWithIdentifier(identifier: String, sender: AnyObject? = nil) {
self.performSegueWithIdentifier(identifier, sender: sender)
}
}<file_sep>/README.md
# Coomb
:moneybag: iOS Proof of concept for Coomb - Machine Learning approach to profit on cryptocurrency markets
Coomb uses the UCB1 Multi Arm Bandit Algorithm to process inputs of data and graph the potential of reward corresponding with each "arm" (option)!
https://github.com/NicoHinderling/Coomb
<file_sep>/Arbytrage/CurrencyCollectionViewController.swift
//
// CurrencyCollectionViewController.swift
// Arbytrage
//
// Created by <NAME> on 8/16/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
import Alamofire
class CurrencyCollectionViewController: UIViewController {
@IBOutlet weak var lolCollectionView: UICollectionView!
var data: [(String, Double)] = [
("BTC", 0),
("CLAM", 0),
("PRO", 0),
("BANX", 0)
] { didSet {
self.lolCollectionView.reloadData()
}}
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://coinmarketcap-nexuist.rhcloud.com/api/banx/price")
.responseJSON {
let usd = $0.2.value!["usd"]
dispatch_async(dispatch_get_main_queue()) {
self.data[2].1 = (usd as! NSString).doubleValue
}
Alamofire.request(.GET, "http://coinmarketcap-nexuist.rhcloud.com/api/pro/price")
.responseJSON {
let usd = $0.2.value!["usd"]
dispatch_async(dispatch_get_main_queue()) {
self.data[3].1 = (usd as! NSString).doubleValue
}
}
Alamofire.request(.GET, "http://coinmarketcap-nexuist.rhcloud.com/api/clam/price")
.responseJSON {
let usd = $0.2.value!["usd"]
dispatch_async(dispatch_get_main_queue()) {
self.data[1].1 = (usd as! NSString).doubleValue
}
}
Alamofire.request(.GET, "http://coinmarketcap-nexuist.rhcloud.com/api/btc/price")
.responseJSON {
let usd = $0.2.value!["usd"]
dispatch_async(dispatch_get_main_queue()) {
self.data[0].1 = (usd as! NSString).doubleValue
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
print(sender as! String)
if let des = segue.destinationViewController as? WelcomeViewController {
des.currency = sender as! String
}
}
}
extension CurrencyCollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("id", forIndexPath: indexPath) as! CurrencyCollectionViewCell
cell.nameLabel.text = data[indexPath.row].0
// data[indexPath.row].1 = Double(round(1000 * self.data[indexPath.row].1)/1000)
let lol = data[indexPath.row].1 == 0 ? "" : "\(data[indexPath.row].1)"
cell.currencyLabel.text = "$\(lol)"
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("unwindToWelcome", sender: data[indexPath.row].0)
}
}<file_sep>/Arbytrage/PickerTableViewController.swift
//
// PickerTableViewController.swift
// Arbytrage
//
// Created by <NAME> on 8/16/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class PickerTableViewController: UITableViewController {
let data = ["Bitcoin", "Clams", "BanxShares", "Dank", "Weed"]
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
}
}
extension PickerTableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("id")!
cell.textLabel?.text = data[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.performSegueWithIdentifier("unwindBruh", sender: data[indexPath.row])
}
}
<file_sep>/Arbytrage/CurrencyCollectionViewCell.swift
//
// CurrencyCollectionViewCell.swift
// Arbytrage
//
// Created by <NAME> on 8/16/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class CurrencyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var currencyLabel: UILabel!
}
| 83da6d460eb4249d04e21c380102fe8064a00f48 | [
"Swift",
"Markdown"
] | 6 | Swift | JFD3D/Coomb-1 | d3f61987198468c047e99758c288395396967784 | a322a2708a5a9b7a0d9583b4e20aa93a1370217c |
refs/heads/master | <repo_name>1lkin/JavaCourseModule1<file_sep>/src/CyclePractice/Task3.java
/**
* <NAME>
* <p>
* Copyright (c) HASANOV.
*/
package CyclePractice;
/**
* <NAME> response to Homework "Cycle practice", Module 1.
*
* Task:
* Get the area limited by the following functions:
* x = 0 .. 3.14; y = sin(x); y = 0.1 * k, where k is the last cipher
* in your student card. (2 points)
*
* @version 1.10 13-03-2021
* @author <NAME>
*/
public class Task3 {
public static void main(String[] args) {
// initializing the variables
double deltaX = 0.01;
double totalArea = 0;
double y = 0.5;
double sectionArea;
// calculating the area
for (double x = 0; x < Math.PI; x+=deltaX) {
// calculating the section area where the value of y is less than 0.5
if (Math.sin(x) < 0.5){
sectionArea = Math.sin(x) * deltaX;
// calculating the section area where the value of y is 0.5
} else {
sectionArea = y * deltaX;
}
// adding all result together
totalArea += sectionArea;
}
// output the determined result to the console
System.out.println("Area limited by the given functions is: "
+ totalArea);
}
} | 1b90a6143b5094f0e9eef382bc68f13c4a69dce0 | [
"Java"
] | 1 | Java | 1lkin/JavaCourseModule1 | bb4ba2ba948ff09bae9b0a42430d2537787bcd7c | 81494d29c5fbd03ebc86dae5abb7fa62161036ae |
refs/heads/master | <file_sep>#!/usr/bin/env php
<?php
require_once 'vendor/autoload.php';
use Kargin\Bracketeer;
/**
* Prints result based on boolean value
*
* @param $b
* @return string
*/
function printBool($b) {
return $b ? "OK. Brackets in given string ARE balanced.\n": "ERROR. Brackets in given string are NOT balanced.\n";
}
/**
* Handles warnings
*
* @param $errno
* @param $errstr
*/
function warningHandler($errno, $errstr) {
echo "ERROR\n$errstr\nERROR CODE = $errno\n";
}
$bracketeer = new Bracketeer();
echo "Press \"Enter\" for using one of three default tests.\n";
echo "Enter path to file that contains string with bracket problem [tests/test_1]: \n";
$line = readline();
if (empty($line)) {
$line = 'tests/test_1';
}
set_error_handler("warningHandler", E_WARNING);
$testString = file_get_contents($line);
restore_error_handler();
if ($testString !== false) {
try {
echo printBool($bracketeer->isBalanced($testString));
} catch (Exception $e) {
echo get_class($e) . ":\n";
echo $e->getMessage() . "\n";
}
}
<file_sep># OTUS PHP Homework 1
PHP cli script. Asks path to file which contains string with bracketed problem, reads file contents to string and passes it to method "isBalanced" from composer library Bracketeer.
There are 3 tests available inside `tests` directory: `test_1`, `test_2`, `test_3`.
To install composer library Bracketeer follow install instructions at https://github.com/Kargin/bracketeer
| 966de217694259779772562a1ab40a8a13df338a | [
"Markdown",
"PHP"
] | 2 | PHP | Kargin/OTUS_HW1 | 777962d7c9e59c524c57a9b7e43d275b8863baf0 | 6b34a050f5e82db92f8cbb79e819a21e5363fed6 |
refs/heads/master | <file_sep>///LEFT SIDEBAR
(function () {
new Canvi({
content: '.js-canvi-content',
navbar: '.js-canvi-navbar--right',
openButton: '.js-canvi-open-button--right',
position: 'left',
pushContent: true,
responsiveWidths: [{
breakpoint: "320px",
width: "100%"
},{
breakpoint: "375px",
width: "100%"
}, {
breakpoint: "425px",
width: "100%"
}, {
breakpoint: "768px",
width: "100%"
}, {
breakpoint: "1024px",
width: "40%"
},
{
breakpoint: "1440px",
width: "20%"
},{
breakpoint: "1600px",
width: "20%"
}, {
breakpoint: "1920px",
width: "20%"
} ],
isDebug: false
});
openValue({currentTarget: document.getElementsByClassName('tablinks')[0]}, 'Account');
}());
///ACCORDION
var acc = document.getElementsByClassName('accordion');
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener('click', function () {
this.classList.toggle('active');
var panel = this.nextElementSibling;
if (panel.style.display === 'block') {
panel.style.display = 'none';
} else {
panel.style.display = 'block';
}
});
}
////TAB MENU
function openValue(evt, valueName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName('tabcontent');
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = 'none';
}
tablinks = document.getElementsByClassName('tablinks');
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(' active', '');
}
document.getElementById(valueName).style.display = 'block';
evt.currentTarget.className += ' active';
}
| 2fcf365d55940e2d34c6dc520dd68148c6fc1cea | [
"JavaScript"
] | 1 | JavaScript | Lov-art/test-for-merehead | 6b68040d91991e9bb78d831e11de579e03eaf15b | 4cbd984fe6d8c59c1db7e27c0f6cbfca48023c9d |
refs/heads/master | <file_sep><?php
namespace ParkBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class ComputerController extends Controller
{
/**
* @Route("/computer/list")
*/
public function listAction()
{
return $this->render('ParkBundle:Computer:list.html.twig', array(
'computers' => $this->get('park.computer')->getComputersList()
)
);
}
}
<file_sep><?php
namespace ParkBundle\Service;
class ComputerManager
{
public function getComputersList()
{
$computers = array();
array_push($computers, array('id' => 1, 'name' => 'ordinateur 1', 'ip' => '10.69.172.53', 'enabled' => true));
array_push($computers, array('id' => 2, 'name' => 'ordinateur 2', 'ip' => '10.69.172.54', 'enabled' => false));
return $computers;
}
}
| fbf6da2c33b3918ca44ef283d970ed265ffb5ff4 | [
"PHP"
] | 2 | PHP | Ddespres69/formation-symfony-ref | 10026acfbafda316bf48a4e0a7c17be26f0d4c11 | 78be6ab68b02c72c99dc8192fd09c5056ddc8814 |
refs/heads/master | <repo_name>Chika-Okonkwo/health-management-system<file_sep>/AHMS1/UserLogin.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class UserLogin : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
SqlConnection SqlCon = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
SqlCon = new SqlConnection(myCon);
SqlCon.Open();
string com = "select username, password from hmsusers where username = '" + txtUsername.Text.Trim() + "' and password = '" + txtPWord.Text.Trim() + "'";
SqlCommand cmd = new SqlCommand(com, SqlCon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if (dr.HasRows == true)
{
SqlConnection SqlCon2 = new SqlConnection(myCon);
SqlCon2.Open();
string com2 = "select username, password, userid, status, roleid, flag from hmsusers where username = '" + txtUsername.Text.Trim() + "' and password = '" + txtPWord.Text.Trim() + "' and status = 'A' and flag = 0";
SqlCommand cmd2 = new SqlCommand(com2, SqlCon2);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
if (dr2.HasRows == true)
{
Session["username"] = txtUsername.Text.Trim();
Session["userid"] = dr2["userid"].ToString();
Session["roleid"] = dr2["roleid"].ToString();
if (Convert.ToInt32(dr2["roleid"]) == 1)
{
Response.Redirect("DispensaryList.aspx");
}
else
{
Response.Redirect("Home.aspx");
}
}
}
else
{
lblAlrtFail.Text = "Contact Admin!";
alrtFailure.Visible = true;
}
}
}
else
{
lblAlrtFail.Text = "Incorrect Username or Password!";
alrtFailure.Visible = true;
}
}
catch (SqlException)
{
throw;
}
finally
{
SqlCon.Close();
}
}
}
}<file_sep>/AHMS1/AHMS1.Master.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class AHMS1 : System.Web.UI.MasterPage
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
DataTable allMenuData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadMenuData();
LblSession.Text = Session["Username"].ToString();
LblDate.Text = DateTime.Now.ToLongDateString();
}
}
private void LoadMenuData()
{
using (SqlConnection connection = new SqlConnection(myCon))
using (SqlCommand selectCommand = new SqlCommand("getMenuData", connection))
{
if (Session["userid"] == null)
{
Response.Redirect("UserLogin.aspx");
}
else
{
selectCommand.CommandType = CommandType.StoredProcedure;
selectCommand.Parameters.AddWithValue("@roleID", Session["roleid"].ToString());
DataTable dt = new DataTable();
try
{
connection.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
if (reader.HasRows)
{
rptMenuData.DataSource = reader;
rptMenuData.DataBind();
using (SqlConnection SqlCon = new SqlConnection(myCon))
{
SqlCon.Open();
string com = "update hmsusers set flag = 1 where userid = " + Session["userid"];
SqlCommand cmd = new SqlCommand(com, SqlCon);
cmd.ExecuteNonQuery();
SqlCon.Close();
SqlCon.Dispose();
}
}
reader.Close();
}
catch (SqlException)
{
throw;
}
finally
{
connection.Close();
}
}
}
}
protected void btnLogOut_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = null;
try
{
SqlCon = new SqlConnection(myCon);
SqlCon.Open();
string com = "update hmsusers set flag = 0 where userid = " + Session["userid"];
SqlCommand cmd = new SqlCommand(com, SqlCon);
cmd.ExecuteNonQuery();
Response.Redirect("UserLogin.aspx");
}
catch (SqlException)
{
throw;
}
finally
{
SqlCon.Close();
}
}
//public DataTable GetMenuData()
//{
// using (SqlConnection connection = new SqlConnection(myCon))
// using (SqlCommand selectCommand = new SqlCommand("exec getAllMenuData", connection))
// {
// selectCommand.CommandType = CommandType.StoredProcedure;
// selectCommand.Parameters.AddWithValue("@roleID", Session["roleid"]);
// DataTable dt = new DataTable();
// try
// {
// connection.Open();
// SqlDataReader reader = selectCommand.ExecuteReader();
// if (reader.HasRows)
// {
// dt.Load(reader);
// }
// reader.Close();
// }
// catch (SqlException)
// {
// throw;
// }
// finally
// {
// connection.Close();
// }
// }
//}
//private SqlDataReader GetAllMenuData()
//{
// SqlConnection connection = new SqlConnection(myCon);
// SqlCommand selectCommand = new SqlCommand("exec getAllMenuData", connection);
// selectCommand.CommandType = CommandType.StoredProcedure;
// selectCommand.Parameters.AddWithValue("@roleID", Session["roleid"]);
// DataTable dt = new DataTable();
// try
// {
// connection.Open();
// SqlDataReader reader = selectCommand.ExecuteReader();
// if (reader.HasRows)
// {
// dt.Load(reader);
// }
// reader.Close();
// }
// catch (SqlException)
// {
// throw;
// }
// finally
// {
// connection.Close();
// }
//}
//protected void rptMenuData_ItemDataBound(object sender, RepeaterItemEventArgs e)
//{
// if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
// {
// if (allMenuData != null)
// {
// DataRowView drv = e.Item.DataItem as DataRowView;
// string ID = drv["ID"].ToString();
// DataRow[] rows = allMenuData.Select("ParentID=" + ID, "Name");
// if (rows.Length > 0)
// {
// StringBuilder sb = new StringBuilder();
// sb.Append("<ul>");
// foreach (var item in rows)
// {
// sb.Append("<li><a href='#'>" + item["MenuName"] + "</a></li>");
// }
// sb.Append("</ul>");
// (e.Item.FindControl("ltrlSubMenu") as Literal).Text = sb.ToString();
// }
// }
// }
//}
}
}<file_sep>/AHMS1/PatientRecord.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class PatientRecord : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int r = Convert.ToInt32(Request.QueryString["row"]);
if (r > 0)
{
alrtSuccess.Visible = true;
}
Bind();
}
}
public void Bind()
{
SqlConnection SqlCon = new SqlConnection(myCon);
SqlCon.Open();
SqlCommand cmd = new SqlCommand("getPatientList", SqlCon);
SqlDataReader dr = cmd.ExecuteReader();
//if (dr.Read())
//{
// if (dr.HasRows)
// {
// if (dr["status"].ToString() == "Active")
// {
// lbtnStat.CssClass = "btn btn-success width-100";
// }
// else
// {
// lblstat.CssClass = "btn btn-danger width-100";
// }
// }
//}
rptrPatientList.DataSource = dr;
rptrPatientList.DataBind();
}
}
}<file_sep>/AHMS1/UserSettings.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class UserSettings : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
using (SqlConnection connection = new SqlConnection (myCon))
using (SqlCommand cmd = new SqlCommand("getPword", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@uid", Session["userid"]);
cmd.Parameters.AddWithValue("@pword", txtOldPword.Text);
cmd.Connection = connection;
connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
SqlConnection SqlCon = new SqlConnection(myCon);
try
{
SqlCon.Open();
//SqlCommand sqlcom = new SqlCommand("UpdatePword" +Session[""]+", '"+txtNewPword.Text+"'", SqlCon);
SqlCommand sqlcom = new SqlCommand("UpdatePword", SqlCon);
sqlcom.CommandType = CommandType.StoredProcedure;
sqlcom.Parameters.AddWithValue("@uid", Session["userid"]);
sqlcom.Parameters.AddWithValue("@new", txtNewPword.Text.Trim());
sqlcom.ExecuteNonQuery();
// Alert success
alrtSuccess.Visible = true;
// Empty textboxes
txtConPword.Text = null;
txtNewPword.Text = null;
txtOldPword.Text = null;
}
finally
{
dr.Close();
dr.Dispose();
SqlCon.Close();
SqlCon.Dispose();
}
}
else
{
lblMsg.Text = "Password Incorrect!";
}
}
}
}
}<file_sep>/AHMS1/UserRegistration.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class UserRegistration : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(myCon);
try
{
SqlCommand sqlcom = new SqlCommand("select username from hmsusers where username = @uname", connection);
sqlcom.CommandType = CommandType.Text;
sqlcom.Parameters.AddWithValue("@uname", txtUname.Text);
sqlcom.Connection = connection;
connection.Open();
SqlDataReader dr = sqlcom.ExecuteReader();
if (dr.Read())
{
alrtFail.Visible = true;
lblAlrtFail.Text = "Username already exists!";
dr.Close();
}
else
{
SqlConnection connection2 = new SqlConnection(myCon);
SqlCommand sqlcom2 = new SqlCommand("select email from hmsusers where email = @email", connection2);
sqlcom2.CommandType = CommandType.Text;
sqlcom2.Parameters.AddWithValue("@email", txtEmail.Text);
sqlcom2.Connection = connection2;
connection2.Open();
SqlDataReader dr2 = sqlcom2.ExecuteReader();
if (dr2.Read())
{
alrtFail.Visible = true;
lblAlrtFail.Text = "Email already exists!";
dr2.Close();
}
else
{
using (SqlConnection sqlcon = new SqlConnection(myCon))
using (SqlCommand cmd = new SqlCommand("setUserRegistration", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@a", txtUname.Text);
cmd.Parameters.AddWithValue("@b", txtEmail.Text);
cmd.Parameters.AddWithValue("@c", txtPword.Text);
cmd.Parameters.AddWithValue("@d", txtFname.Text);
cmd.Parameters.AddWithValue("@e", txtLname.Text);
cmd.Parameters.AddWithValue("@f", ddlGender.SelectedValue);
cmd.Connection = sqlcon;
sqlcon.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
alrtFail.Visible = false;
alrtSuccess.Visible = true;
clear();
}
else
{
alrtSuccess.Visible = false;
alrtFail.Visible = true;
lblAlrtFail.Text = "Complete all fields!";
}
}
}
dr2.Close();
}
dr.Close();
}
finally
{
connection.Close();
connection.Dispose();
}
}
public void clear()
{
txtUname.Text = null;
txtEmail.Text = null;
txtPword.Text = null;
txtConPword.Text = null;
txtFname.Text = null;
txtLname.Text = null;
ddlGender.SelectedIndex = 0;
}
}
}<file_sep>/AHMS1/PatientVitals.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class PatientVitals : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int r = Convert.ToInt32(Request.QueryString["row"]);
if (r > 0)
{
alrtSuccess.Visible = true;
}
Bind();
}
}
public void Bind()
{
SqlConnection SqlCon = new SqlConnection(myCon);
SqlCon.Open();
SqlCommand cmd = new SqlCommand("getVitals", SqlCon);
SqlDataReader dr = cmd.ExecuteReader();
rptrVitalsList.DataSource = dr;
rptrVitalsList.DataBind();
}
}
}<file_sep>/AHMS1/AddVitals.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class AddVitals : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(myCon);
try
{
using (SqlConnection sqlcon = new SqlConnection(myCon))
using (SqlCommand cmd = new SqlCommand("setVitalsList", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@a", txtPatientNo.Text);
cmd.Parameters.AddWithValue("@b", txtTemp.Text);
cmd.Parameters.AddWithValue("@c", txtWeight.Text);
cmd.Parameters.AddWithValue("@d", txtBP.Text);
cmd.Parameters.AddWithValue("@dt", Convert.ToDateTime(DateTime.Now.ToShortDateString()));
cmd.Connection = sqlcon;
sqlcon.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Redirect("PatientVitals.aspx?row = " + r);
}
else
{
lblMsg.Visible = true;
lblMsg.Text = "complete all fields!";
}
sqlcon.Close();
}
}
finally
{
connection.Close();
connection.Dispose();
}
}
}
}<file_sep>/AHMS1/ConsultationPage.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class ConsultationPage : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
//show Patient Details
SqlConnection SqlCon = new SqlConnection(myCon);
SqlCon.Open();
SqlCommand cmd = new SqlCommand("select * from patientdetails where patientid="+id, SqlCon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtAddress.Text = dr["Address"].ToString();
txtDOB.Text = dr["DOB"].ToString();
txtFName.Text = dr["FirstName"].ToString();
txtLName.Text = dr["LastName"].ToString();
txtMName.Text = dr["Middlename"].ToString();
txtOccupation.Text = dr["Occupation"].ToString();
txtPatientNo.Text = dr["PatientNo"].ToString();
ddlMStatus.SelectedValue = dr["MaritalStatus"].ToString();
ddlReligion.SelectedValue = dr["Religion"].ToString();
ddlSex.SelectedValue = dr["Sex"].ToString();
txtAge.Text = dr["Age"].ToString();
}
dr.Close();
SqlCon.Close();
txtAddress.Enabled = false;
txtAge.Enabled = false;
txtDOB.Enabled = false;
txtFName.Enabled = false;
txtLName.Enabled = false;
txtMName.Enabled = false;
txtOccupation.Enabled = false;
txtPatientNo.Enabled = false;
txtPhoneNo.Enabled = false;
ddlMStatus.Enabled = false;
ddlReligion.Enabled = false;
ddlSex.Enabled = false;
//Show vitals
SqlConnection SqlCon1 = new SqlConnection(myCon);
SqlCon1.Open();
SqlCommand cmd1 = new SqlCommand("select BloodPressure, BodyTemp, Weight from Consultation where patientid="+id, SqlCon1);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
txtBP.Text = dr1["BloodPressure"].ToString();
txtTemp.Text = dr1["BodyTemp"].ToString();
txtWeight.Text = dr1["Weight"].ToString();
}
dr1.Close();
SqlCon1.Close();
txtBP.Enabled = false;
txtTemp.Enabled = false;
txtWeight.Enabled = false;
//show background
SqlConnection SqlCon2 = new SqlConnection(myCon);
SqlCon2.Open();
SqlCommand cmd2 = new SqlCommand("select * from PatientHistory where patientid="+id, SqlCon2);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
txtComHistory.Text = dr2["ComplaintHistory"].ToString();
txtComplaint.Text = dr2["PatientComplaint"].ToString();
txtDHistory.Text = dr2["DrugHistory"].ToString();
txtFsocHistory.Text = dr2["FamSocHistory"].ToString();
}
dr2.Close();
SqlCon2.Close();
}
}
}
}<file_sep>/AHMS1/PatientRegistration.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class PatientRegistration : System.Web.UI.Page
{
string myCon=System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
//On save button click
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(myCon);
try
{
//check if patient number exists
SqlCommand sqlcom = new SqlCommand("select patientno from patientdetails where patientno = @patno", connection);
sqlcom.CommandType = CommandType.Text;
sqlcom.Parameters.AddWithValue("@patno", txtPatientNo.Text);
sqlcom.Connection = connection;
connection.Open();
SqlDataReader dr = sqlcom.ExecuteReader();
//if exists print out error msg
if (dr.Read())
{
lblMsg.Visible = true;
lblMsg.Text = "patient number already exists!";
dr.Close();
}
else
{
//if not exists use stored procedure to insert new details
using (SqlConnection sqlcon = new SqlConnection(myCon))
using (SqlCommand cmd = new SqlCommand("setPatientRegistration", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@a", txtPatientNo.Text);
cmd.Parameters.AddWithValue("@b", txtFName.Text);
cmd.Parameters.AddWithValue("@c", txtLName.Text);
cmd.Parameters.AddWithValue("@d", txtMName.Text);
cmd.Parameters.AddWithValue("@e", ddlSex.SelectedValue);
cmd.Parameters.AddWithValue("@f", txtAddress.Text);
cmd.Parameters.AddWithValue("@g", ddlReligion.SelectedValue);
cmd.Parameters.AddWithValue("@h", txtOccupation.Text);
cmd.Parameters.AddWithValue("@i", ddlMStatus.SelectedValue);
cmd.Parameters.AddWithValue("@j", txtComplaint.Text);
cmd.Parameters.AddWithValue("@k", txtComHistory.Text);
cmd.Parameters.AddWithValue("@l", txtMedHistory.Text);
cmd.Parameters.AddWithValue("@m", txtFsocHistory.Text);
cmd.Parameters.AddWithValue("@n", txtDHistory.Text);
cmd.Parameters.AddWithValue("@o", txtDOB.Text);
cmd.Connection = sqlcon;
//open connection to database
sqlcon.Open();
//execute stored procedure command
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Redirect("PatientRecord.aspx?row = "+r);
}
else
{
lblMsg.Visible = true;
lblMsg.Text = "complete all fields!";
}
sqlcon.Close();
}
}
}
finally
{
//close connection to database
connection.Close();
connection.Dispose();
}
}
}
}<file_sep>/AHMS1/NewQueue.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AHMS1
{
public partial class NewQueue : System.Web.UI.Page
{
string myCon = System.Configuration.ConfigurationManager.ConnectionStrings["HMSConnect"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(myCon);
try
{
using (SqlConnection sqlcon = new SqlConnection(myCon))
using (SqlCommand cmd = new SqlCommand("setQueueList", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@a", txtPatientNo.Text);
cmd.Parameters.AddWithValue("@b", ddlDept.SelectedValue);
cmd.Parameters.AddWithValue("@c", ddlCode.SelectedValue);
cmd.Connection = sqlcon;
sqlcon.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Redirect("AppointmentPage.aspx?row = " + r);
}
else
{
lblMsg.Visible = true;
lblMsg.Text = "complete all fields!";
}
sqlcon.Close();
}
}
finally
{
connection.Close();
connection.Dispose();
}
}
}
}<file_sep>/README.md
# health-management-system
An efficient computer-based database management system (DBMS) for hospitals and clinics to automate manual information processing procedures used in Nigeria
| d14cb8625d559f38270869e6fc6fbc075618e5c9 | [
"Markdown",
"C#"
] | 11 | C# | Chika-Okonkwo/health-management-system | 954bff679bef86faed98ed4f458b7df556227a08 | 05839545d3ae066b3057ca072a6a7d954c66050e |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { Http } from "@angular/http";
import { environment } from "src/environments/environment";
@Component({
selector: 'app-modify-item',
templateUrl: './modify-item.component.html',
styleUrls: ['./modify-item.component.css']
})
export class ModifyItemComponent implements OnInit {
private items:any[];
constructor(private http:Http) {
http.get(environment.getItemUrl).subscribe(response => {
this.items=response.json();
console.log(response.json());
});
}
deleteitem(item){
this.http.delete(environment.getItemUrl+item.id).subscribe(responce=>{
let index = this.items.indexOf(item);
this.items.splice(index,1);
})
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Input } from "@angular/core";
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit {
@Input() name:any;
@Input() discription:any;
@Input() price:any;
@Input() url:any;
//private name:String;
//private description:String;
//private price:String;
//private url:String;
constructor(private route:ActivatedRoute) { }
ngOnInit() {
console.log(this.name);
console.log(this.discription);
console.log(this.price);
console.log(this.url);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Http } from "@angular/http";
import { environment } from "src/environments/environment";
import { Router } from "@angular/router";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
username:String;
password:String;
invalid:Boolean;
router:Router;
private http:Http;
constructor() { }
ngOnInit() {
}
Login(input){
this.username = input.target.elements[0].value;
this.password = input.target.elements[1].value;
console.log(this.username,this.username);
}
ChickAuthontication(){
let body = {id: this.username , password:<PASSWORD>};
return this.http.post(environment.loginUrl,JSON.stringify(body)).map(responce=>{
let result = responce.json();
if(result){
localStorage.setItem('id',result);
this.router.navigate(['/']);
}
this.invalid=true;
//console.log(responce.json());
});
}
}
<file_sep>package com.AllHandmade.config;
import com.AllHandmade.entity.Admin;
import com.AllHandmade.entity.Item;
import com.AllHandmade.repository.AdminRepository;
import com.AllHandmade.repository.ItemRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@EnableMongoRepositories(basePackages = "com.AllHandmade.repository")
@Configuration
public class MongoDBConfig {
@Bean
CommandLineRunner commandLineRunner(AdminRepository userRepository) {
return strings -> {
userRepository.save(new Admin("3", "Smith3","1234", "1","jkjkj@"));
userRepository.save(new Admin("2", "Smith2","1234", "1","jkjkj@"));
};
}
// @Bean
// CommandLineRunner commandLineRunner(ItemRepository userRepository) {
// return strings -> {
// userRepository.save(new Item("mmm", "dsfghj","1234","jhghf"));
// userRepository.save(new Item("nnn", "fdfghbn","1234","tfdfg"));
// };
// }
}
<file_sep>package com.AllHandmade.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.AllHandmade.entity.Admin;
import com.AllHandmade.entity.Item;
import com.AllHandmade.repository.ItemRepository;
import com.AllHandmade.service.ItemResource;
@Controller
@RequestMapping("/items")
public class ItemController {
@Autowired
private ItemResource itemResource ;
@GetMapping("/")
public ResponseEntity<List<Item>> getAll() {
//return new ResponseEntity<>(itemResource.getAll(), HttpStatus.FOUND);
HttpHeaders headers = new HttpHeaders();
headers.add("Responded", "Items");
return ResponseEntity.accepted().headers(headers).body(itemResource.getAll());
}
@RequestMapping(value = "/{id}" , method = RequestMethod.GET)
public Item getItem(@PathVariable("id") String id) {
return itemResource.getItem(id);
}
@RequestMapping(value = "/{id}" , method = RequestMethod.DELETE)
public void deleteItem(@PathVariable("id") String id) {
itemResource.deleteItem(id);
}
@RequestMapping(value = "/Add", method = RequestMethod.POST)
public void AddItem(@RequestParam("name") String name,@RequestParam("discription") String discription , @RequestParam("price") String price , @RequestParam("urls") String url) {
System.out.println("hi"+name+" "+discription+" "+ price+" "+url);
itemResource.AddItem(name, discription, price, url);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { Http } from "@angular/http";
import { HttpClient } from '@angular/common/http';
import { environment } from "src/environments/environment";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
http:HttpClient;
cards:any[];
private router:Router;
constructor(http:Http)
{
http.get(environment.getItemUrl).subscribe(response => {
this.cards=response.json();
console.log(response.json());
});
}
ngOnInit() {
this.getData();
//console.log(this.cards);
}
getData(){
}
trackCard(index,card){
return card? card.id :undefined;
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpModule} from '@angular/http';
import {RouterModule} from '@angular/router';
import {SuiModule} from 'ng2-semantic-ui';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { CardComponent } from './card/card.component';
import { HomeComponent } from './home/home.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { AddItemComponent } from './add-item/add-item.component';
import { HttpClientModule } from "@angular/common/http";
import { ModifyItemComponent } from './modify-item/modify-item.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
CardComponent,
HomeComponent,
NavBarComponent,
AddItemComponent,
ModifyItemComponent
],
imports: [
BrowserModule,
HttpModule,
HttpClientModule,
RouterModule.forRoot([
{
path : 'home',
component : HomeComponent
},
{
path : 'login',
component : LoginComponent
},
{
path : 'additem',
component : AddItemComponent
},
{
path : 'card/:name/:description/:price/:url',
component : CardComponent
},
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>package com.AllHandmade.service;
import java.util.ArrayList;
import java.util.List;
import org.omg.CORBA.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import com.AllHandmade.entity.Item;
import com.AllHandmade.repository.ItemRepository;
@EnableMongoRepositories
@Service
public class ItemResource {
@Autowired
private ItemRepository itemRepository;
public List<Item> getAll() {
try {
return itemRepository.findAll();
//System.out.println(list.size());
}
catch(Exception e) {
System.out.println("Cant get items");
}
return null;
}
public Item getItem(String id) {
try {
return itemRepository.findOne(id);
}
catch(Exception handlerException) {
System.out.println("Cant find item");
return null;
}
}
public void deleteItem(String id) {
try {
itemRepository.delete(id);
}
catch(Exception handlerException) {
System.out.println("Cant delete item");
}
}
public void AddItem(String Name , String Discription , String Price ,String Url)
{
Item item = new Item();
item.setName(Name);
item.setDiscription(Discription);
item.setPrice(Price);
item.setUrl(Url);
//System.out.println("llll"+item.getName()+item.getDiscription()+item.getPrice()+item.getUrl());
//itemRepository.deleteAll();
try {
itemRepository.save(item);
} catch (Exception handlerException) {
System.out.println("Cant save item");
}
}
}
| 6a85f1114d3a80cf9996a58c5f2544d1dac57703 | [
"Java",
"TypeScript"
] | 8 | TypeScript | Nourhann/AllHandmade | bfd8aed0f6e3dd90e3bc291b3c1b951ff5132536 | abab02505f724e5daa8172857d178e3ec816544b |
refs/heads/master | <file_sep><?php
/**
* Klasse für Active Directory Unterstützung Benutzer Kontext
* ADUser.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
require_once './classes/AD.php';
class ADUser{
protected $ad;
protected $Users;
protected $filter;
/**
* @param AD $ad Active Directory Klassen object
*/
function __construct(AD $ad){
$this->ad = $ad;
}
/**
* sucht nach Filter Kriterium im AD
* @param unknown $filter
*/
public function search($filter){
//filter überprüfen
$this->filter = $filter;
$this->Users = ldap_search($this->ad->get_ADConnection(), $this->ad->get_baseDN(), $this->filter) or exit();
}
/**
* liefert das Ergebnis einer Suche
* @return resource
*/
public function get_Users(){
return $this->Users;
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Erstellungszeit: 03. Feb 2016 um 11:49
-- Server Version: 5.5.46-0ubuntu0.14.04.2
-- PHP-Version: 5.5.9-1ubuntu4.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Datenbank: `stadtleser`
--
CREATE DATABASE IF NOT EXISTS `stadtleser` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `stadtleser`;
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `benutzer`
--
CREATE TABLE IF NOT EXISTS `benutzer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`markasdeleted` int(11) NOT NULL,
`name` varchar(64) NOT NULL,
`vorname` varchar(64) NOT NULL,
`geburtsdatum` varchar(64) NOT NULL,
`strasse` varchar(64) NOT NULL,
`plz` int(11) NOT NULL,
`ort` varchar(64) NOT NULL,
`erfassungszustimmung` int(11) NOT NULL,
`passwort` varchar(64) NOT NULL,
`bibliotheksnummer` varchar(64) NOT NULL,
`bibliothek` varchar(10) NOT NULL,
`dauer` int(11) NOT NULL,
`status` varchar(64) NOT NULL,
`zuaccount` varchar(64) NOT NULL,
`datum` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
/**
* Klasse für Active Directory Unterstützung
* AD.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
require_once './classes/ADUser.php';
class AD {
protected $Domain = "MYDOMAIN";
protected $DomainSuffix = "@mydomain.local";
protected $DomainController = "DomainController";
protected $AdminUser;
protected $AdminPassword;
protected $BaseDN;
protected $ADConnection;
protected $ProxyBind = TRUE;
protected $SSL = TRUE;
protected $ADUser;
/**
*
* @param string $DC Domänencontroller
* @param string $BindUser User
* @param string $BindPassword <PASSWORD>
* @param boolean $proxybind <br>
* wenn TRUE dann wird der Benutzer als Proxybenutzer für die Verbindung fest eingetragen anderfalls wird der Bind mit dem Benutzer durchgeführt und nicht im Objekt gespeichert
* @param boolean $ssl <br>
* TRUE use SSL - FALSE not use SSL
*/
function __construct($DC,$BindUser,$BindPassword,$Domain,$BaseDN,$DomainSuffix = NULL,$proxybind = TRUE,$ssl = TRUE) {
//if (array_key_exists("DC", $ADParameter))$this->DomainController = $ADParameter["DC"];
//if (array_key_exists("Binduser", $ADParameter))$this->AdminUser = $ADParameter["Binduser"];
//if (!empty($var))
$this->DomainController = $DC;
if($proxybind){
$this->AdminUser = $BindUser;
$this->AdminPassword = $BindPassword;
}else {
$this->ProxyBind = FALSE;
}
$this->Domain = $Domain;
$this->DomainSuffix = $DomainSuffix;
$this->BaseDN = $BaseDN;
$this->SSL = $ssl;
$this->connect ();
if($this->ProxyBind)$this->bind();
else $this->bind($BindUser,$BindPassword);
}
protected function connect() {
// Mit Server verbinden:
// putenv nur bei SSL --Funktioniert nur mit TLS_REQCERT never in /etc/ldap/ldap.conf
// putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');
if ($this->SSL) {
$this->ADConnection = ldap_connect ( "ldaps://" . $this->DomainController ) or exit ( "Keine SSL Verbindung zum Domain Controller möglich. Fehlermeldung ist: " . $php_errormsg );
} else {
$this->ADConnection = ldap_connect ( "ldap://" . $this->DomainController ) or exit ( "Keine Verbindung zum Domain Controller möglich. Fehlermeldung ist: " . $php_errormsg );
}
// Diese Parameter sind nötig für den Zugriff auf ein Active Directory:
ldap_set_option ( $this->ADConnection, LDAP_OPT_PROTOCOL_VERSION, 3 );
ldap_set_option ( $this->ADConnection, LDAP_OPT_REFERRALS, 0 );
}
/**
* @param string $user
* @param string $password
*/
protected function bind($user=NULL,$password=NULL){
$binduser = NULL;
if (($user != NULL) && ($password != NULL)){
//User Bind
if (stristr($user,"@")){ $binduser = $user;}
else {$binduser = $this->Domain . "\\" . $user;}
ldap_bind($this->ADConnection,$binduser,$password) or exit("User Bind fehlgeschlagen. Fehlermeldung ist: " . $php_errormsg);
}else {
//Proxy Bind
if (stristr($this->AdminUser,"@")){ $binduser = $this->AdminUser;}
else {$binduser = $this->Domain . "\\" . $this->AdminUser;}
ldap_bind($this->ADConnection,$binduser,$this->AdminPassword) or exit("Proxy Bind fehlgeschlagen. Fehlermeldung ist: " . $php_errormsg);
}
}
/**
* @param string $filter LDAP-Filter
*/
public function get_Users($filter){
$this->ADUser = new ADUser($this);
$this->ADUser->search($filter);
return ldap_get_entries($this->ADConnection, $this->ADUser->get_Users());
}
/**
* @return int Anzahl Benutzer
*/
public function get_AnzahlUsers(){
return ldap_count_entries($this->ADConnection, $this->ADUser->get_Users());
}
/**
* @return resource LDAP-Connection
*/
public function get_ADConnection() {
if (isset ( $this->ADConnection ))
return $this->ADConnection;
else
return FALSE;
}
/**
* @return string BaseDN
*/
public function get_baseDN(){
if (isset($this->BaseDN)) return $this->BaseDN;
else return FALSE;
}
/**
* @param string $dn LDAP DN(Distigui--Name)
* @param array $attributes zu ändernde Attribute
* @return boolean <b>
* TRUE bei Erfolg False bei Misserfolg
*/
public function set_UserAttributes($dn,$attributes) {
if (@ldap_mod_replace($this->ADConnection, $dn, $attributes)) {
return TRUE;
} else {
return FALSE;
}
}
/**
* schliest LDAP Connection
*/
public function close(){
ldap_close($this->ADConnection);
}
}<file_sep><?php
/**
* Klasse für Active Directory Unterstützung Hilfsfunktionen
* ADHelper.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
class ADHelper {
/**
*/
function __construct() {
}
/**
* wandelt ein String in ein Active Directory Passwort um
* @param string $plainPassword Passwort
* @return Active Directory unicode password
*/
public function makeADPassword($plainPassword) {
$newPassw = "";
$newPassword = "\"" . $<PASSWORD> . "\"" ;
$len = strlen ( $newPassword ) ;
for($i = 0; $i < $len; $i ++) {
$newPassw .= "{<PASSWORD>" ;
}
return $newPassw ;
}
/**
* wandelt einen Unix Timestamp in eine Windows Timestamp um
* @param timestamp $UnixTimestamp Unix Timestamp
* @return Windows timestamp
*/
public function ConvertUnixToWindowsTimestamp ($UnixTimestamp) {
if ($UnixTimestamp == 0) {
return $UnixTimestamp;
}
//Windows-Timestamp
//Berechnung ab: 01.01.1601 – 00:00:00 UTC
//Angegeben wird die Zeit in 100-Nanosekunden-Intervallen seit Beginn der Rechnung
$WindowsPeriodenBeginn = $UnixTimestamp + 11644473600;
$WindowsTimestamp = $WindowsPeriodenBeginn * (10000000);
return $WindowsTimestamp;
}
/**
* wandelt einen Windows timestamp in einen Unix timestamp um
* @param timstamp $WindowsTimestamp Windows timestamp
* @return Unix Timestamp
*/
function ConvertWindowsToUnixTimestamp ($WindowsTimestamp) {
if ($WindowsTimestamp == 0) {
return $WindowsTimestamp;
}
//Windows-Timestamp
//Berechnung ab: 01.01.1601 – 00:00:00 UTC
//Angegeben wird die Zeit in 100-Nanosekunden-Intervallen seit Beginn der Rechnung
$secsAfterWindowsEpoch = $WindowsTimestamp / (10000000);
$unixTimeStamp=intval($secsAfterWindowsEpoch-11644473600 );
return $unixTimeStamp;
}
}<file_sep>/*
Author: <NAME>
http://
Usage Sample:
<div id="cID">Init<script>countdown(100000,'cID');</script></div>
*/
function cfform() {
// alert('Hallo');
return confirm('Wirklich loeschen?');
}
function cfform2() {
// alert('Hallo');
return confirm('Alle Daten richtig? Speichern?');
}
function checkPLZField(field) {
var regexString = "[0-9]{5}";
// var regexString = "\d{5}";
var regexp = new RegExp(regexString);
if (!regexp.test(field.value)) {
field.style.border = "solid red";
return false;
}
field.style.border = "solid black";
return true;
}
function checkBuchstabenField(field) {
var regexString = "[0-9]";
// var regexString = "\d{5}";
var regexp = new RegExp(regexString);
if (regexp.test(field.value)) {
field.style.border = "solid red";
return false;
}
field.style.border = "solid black";
return true;
}
function checkDatumField(field) {
if (!gueltigesDatum(field.value)) {
field.style.border = "solid red";
return false;
}
field.style.border = "solid black";
return true;
}
function checkBibNrField(field) {
var regexString = "[0-9|x|X]{12}";
// var regexString = "\d{5}";
var regexp = new RegExp(regexString);
if (!regexp.test(field.value)) {
field.style.border = "solid red";
return false;
}
field.style.border = "solid black";
return true;
}
function checkPwdField(field) {
if (!gueltigesPasswort(field.value)) {
field.style.border = "solid red";
return false;
}
field.style.border = "solid black";
return true;
}
function pruefeFormular(f) {
var fehlermeldung = "";
if (!checkPLZField(f.elements["plz"])) {
fehlermeldung += "Fehler im Feld Postleitzahl\n\n";
}
if (!checkDatumField(f.elements["geburtsdatum"])) {
fehlermeldung += "Fehler im Feld Geburtsdatum\n\n";
}
if (!checkBuchstabenField(f.elements["ort"])) {
fehlermeldung += "Fehler im Feld Stadt\n\n";
}
if (!checkBuchstabenField(f.elements["vorname"])) {
fehlermeldung += "Fehler im Feld Vorname\n\n";
}
if (!checkBuchstabenField(f.elements["name"])) {
fehlermeldung += "Fehler im Feld Name\n\n";
}
if (!checkBibNrField(f.elements["bibliotheksnummer"])) {
fehlermeldung += "Fehler im Feld Bibliotheksnummer\n\n";
}
if (!checkPwdField(f.elements["passwort"])) {
fehlermeldung += "Passwort entspricht nicht den Vorgaben\n\n";
}
if (f.elements["passwort"].value != f.elements["passwort2"].value) {
fehlermeldung += "Passwörter sind nicht gleich.\n";
// FehlerMakieren("Absender");
}
if (fehlermeldung == "") {
return confirm('Alle Daten richtig? Speichern?');
} else {
alert("Ihre Eingaben sind Fehlerhaft!\n\n" + fehlermeldung);
return false;
}
}
function FehlerMakieren(Fundort) {
var Formularfeld = Fundort;
if (Fundort == Formularfeld) {
var FomularFeld = document.getElementsByName(Formularfeld)[0];
FomularFeld.className = "FehlerMarkierenFarbe";
}
if (Fundort == "Geschlecht") {
var FomularFeld = document.getElementsByName("Geschlecht")[0];
FomularFeld.className = "FehlerMarkierenFarbe";
var FomularFeld = document.getElementsByName("Geschlecht")[1];
FomularFeld.className = "FehlerMarkierenFarbe";
}
}
function meldeerfolg() {
alert("Daten erfolgreich gespeichert");
}
function nachfragen(datei) {
return confirm("Wollen sie " + datei + " wirklich löschen?");
}
function countdown(time, id) {
// time brauchen wir sp�ter noch
t = time;
// Tage berechnen
d = Math.floor(t / (60 * 60 * 24)) % 24;
// Stunden berechnen
h = Math.floor(t / (60 * 60)) % 24;
// Minuten berechnen
// Sekunden durch 60 ergibt Minuten
// Minuten gehen von 0-59
// also Modulo 60 rechnen
m = Math.floor(t / 60) % 60;
// Sekunden berechnen
s = t % 60;
// Zeiten formatieren
d = (d > 0) ? d + "d " : "";
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
// Ausgabestring generieren
strZeit = d + h + ":" + m + ":" + s;
// Falls der Countdown noch nicht zur�ckgez�hlt ist
if (time > 0) {
// Countdown-Funktion erneut aufrufen
// diesmal mit einer Sekunde weniger
window.setTimeout('countdown(' + --time + ',\'' + id + '\')', 1000);
} else {
// führe eine funktion aus oder refresh die seite
// dieser Teil hier wird genau einmal ausgef�hrt und zwar
// wenn die Zeit um ist.
strZeit = "00:00:00";
document.getElementById('CounterText').firstChild.nodeValue = "Die Reservierung dieser Adressen ist abgelaufen ";
}
// Ausgabestring in Tag mit id="id" schreiben
document.getElementById(id).innerHTML = strZeit;
}
// Helfer Funktion erlaubt Counter auch ohne Timestamp
// countdown2(Tage,Stunden,Minuten,Sekunden,ID)
function countdown2(d, h, m, s, id) {
countdown(d * 60 * 60 * 24 + h * 60 * 60 + m * 60 + s, id);
}
function gueltigesDatum(datum) {
// (Schritt 1) Fehlerbehandlung
if (!datum)
return false;
datum = datum.toString();
// (Schritt 2) Aufspaltung des Datums
datum = datum.split(".");
if (datum.length != 3)
return false;
// (Schritt 3) Entfernung der fuehrenden Nullen und Anpassung des Monats
datum[0] = parseInt(datum[0], 10);
datum[1] = parseInt(datum[1], 10) - 1;
// (Schritt 4) Behandlung Jahr nur zweistellig
if (datum[2].length == 2)
datum[2] = "20" + datum[2];
var heute = new Date();
var aktuellesjahr = heute.getFullYear();
if (datum[0] > 31) {
return false;
}
if (datum[1] > 12) {
return false;
}
if (datum[2] > aktuellesjahr - 15) {
return false;
}
return true;
}
function gueltigesPasswort(pwd) {
if (!pwd) {
return false;
}
pwd = pwd.<PASSWORD>();
if (pwd.length < 8) {
return false;
}
//var regexString = "[\ä\ü\ö\ß\Ä\Ü\Ö\!\"\§\$\%\&\/\(\)\=\*\+\'\#\.\,\;\:\-\_\~\\?]";
var regexString = "[\\W]";
var regexp = new RegExp(regexString);
if (regexp.test(pwd)) {
return false;
}
regexString = "[A-Z]";
regexp = new RegExp(regexString);
if (!regexp.test(pwd)) {
return false;
}
regexString = "[0-9]";
regexp = new RegExp(regexString);
if (!regexp.test(pwd)) {
return false;
}
regexString = "[a-z]";
regexp = new RegExp(regexString);
if (!regexp.test(pwd)) {
return false;
}
return true;
}
<file_sep><?php
/**
* Allgemeine Hilfsfunktionen
* helper.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
/**
* Prüft ob die Regeln für einen Email Alias bei der HAW-HAmburg eingehalten werden
* @param string $alias emailalias
* @return boolean <p>
* TRUE wenn die Regeln für einen gültigen Alias eingehalten sind <p>
* FALSE wenn die Regeln für einen gültigen Alias NICHT eingehalten worden sind
*/
function checkemailsyntax($alias){
$nichterlaubtezeichen = array("_","!","$","%","&","/","=","?","+","*","~","'","#","`","|");
//$ma = filter_var($alias."@haw-hamburg.de", FILTER_VALIDATE_EMAIL);
$ma = validate_email($alias."@haw-hamburg.de");
if (!$ma){
//echo "unvalite email";
return false;
}
//nur einen Punkt ?
if (substr_count($alias,".") != 1){
//echo "mehr als einer oder kein Punkt";
return false;
}
//Punkt nicht erster und nicht letzter buchstabe
//if ((substr_compare($alias, ".", 0, 1) == 0) || (substr_compare($alias, ".", -1, 1) == 0)){
// echo "hier bin ich";
// return false;
//}
//unerlaubte Zeichen ?
foreach ($nichterlaubtezeichen as $zeichen){
if (substr_count($alias, $zeichen) >= 1){
//echo "unerlaubtes zeichen";
return false;
}
}
//alle erlaubten Zahlen entfernen
$nalias = preg_replace("/[0-9]/","", $alias);
$aliasteile = explode(".", $nalias);
$pattern = "/" . $aliasteile[0] . "/i";
if (!preg_match($pattern, stringbereinigen($_SESSION['vorname']))){
echo "vorne stimmt nicht";
return false;
}
$pattern = "/" . $aliasteile[1] . "/i";
if (!preg_match($pattern, stringbereinigen($_SESSION['nachname']))){
echo "hinten stimmt nicht";
return false;
}
//substr_compare($alias, $vorname)
return true;
}
/**
* Prüft ob es sich um ethisch korrekte Emailadresse handelt
* @param string $alias emailalias
* @return boolean <p>
* TRUE bei eingehaltener Ethik
* FALSE bei NICHT eingehaltener Ethik
*/
function checkemailethik($alias){
$verbote = file("blacknames.txt",FILE_IGNORE_NEW_LINES);
foreach ($verbote as $nichterlaubt){
if (strcasecmp($alias, $nichterlaubt)== 0){
//echo $nichterlaubt;
return false;
}
}
return true;
}
/**
* entfernt deutsch Umlaute aus einem String und ersetzt diese durch ae ue usw.
* @param string $str string mit deutschen Umlauten
* @return string <p>
* string mit ersetzten Umlauten
*/
function stringbereinigen ($str){
//lerzeichen raus
$str = preg_replace('/\s/','', $str);
// Umlaute durch Laute ersetzen
$umlaute = Array("/ä/","/ö/","/ü/","/Ä/","/Ö/","/Ü/","/ß/");
$replace = Array("ae","oe","ue","Ae","Oe","Ue","ss");
$str = preg_replace($umlaute,$replace, $str);
return $str;
}
/**
* Prüft ob es sich um einen HAW-Account handelt
* @param string $str HAW-Account
* @return boolean <p>
* TRUE bei gültigem HAW-Account <p>
* FALSE bei ungültigem HAW-Account
*/
function istaacount($str){
//if(! function_exists('ctype_alpha')){ function ctype_alpha($text) { return preg_match("/[A-Za-z]/",$text); }}
$istaacount = false;
//string 6 zeichen lang ? ACHTUNG �NDERUNG F�R PRODUKTIV AUF 6
if (strlen($str) == 6){
//erste zeichen ein a ?
if ((substr($str,0,1)=='a') || substr($str,0,1)=='A'){
//erste drei zeichen Buchstaben ?
//if (ctype_alpha(substr($str,0,3))){
if (preg_match("/[A-Za-z]/",substr($str,0,3))){
//letzte drei Zeichen Zahlen ? ACHTUNG �NDERUNG F�R PRODUKTIV AUF 3
//if (ctype_digit(substr($str,3,3))){
if (preg_match("/[0-9]/",substr($str,3,3))){
$istaacount = true;
}
}
}
}
return $istaacount;
}
/**
* Prüft ob es sich um einen korrekte Emailadresse handelt
* @param string $email emailadresse
* @param boolean $strict
* @return boolean <p>
* TRUE für gültige emailadresse <p>
* FALSe für ungültige emailadress
*/
function validate_email($email, $strict = true) {
$dot_string = $strict ?
'(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/-]|(?<!\\.|\\A)\\.(?!\\.|@))' :
'(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/.-])'
;
$quoted_string = '(?:\\\\\\\\|\\\\"|\\\\?[A-Za-z0-9!#$%&*+=?^_`{|}~()<>[\\]:;@,. \'\\/-])';
$ipv4_part = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
$ipv6_part = '(?:[A-fa-f0-9]{1,4})';
$fqdn_part = '(?:[A-Za-z](?:[A-Za-z0-9-]{0,61}?[A-Za-z0-9])?)';
$ipv4 = "(?:(?:{$ipv4_part}\\.){3}{$ipv4_part})";
$ipv6 = '(?:' .
"(?:(?:{$ipv6_part}:){7}(?:{$ipv6_part}|:))" . '|' .
"(?:(?:{$ipv6_part}:){6}(?::{$ipv6_part}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6_part}:){5}(?:(?::{$ipv6_part}){1,2}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6_part}:){4}(?:(?::{$ipv6_part}){1,3}|(?::{$ipv6_part})?:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6_part}:){3}(?:(?::{$ipv6_part}){1,4}|(?::{$ipv6_part}){0,2}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6_part}:){2}(?:(?::{$ipv6_part}){1,5}|(?::{$ipv6_part}){0,3}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6_part}:){1}(?:(?::{$ipv6_part}){1,6}|(?::{$ipv6_part}){0,4}:{$ipv4}|:))" . '|' .
"(?::(?:(?::{$ipv6_part}){1,7}|(?::{$ipv6_part}){0,5}:{$ipv4}|:))" .
')';
$fqdn = "(?:(?:{$fqdn_part}\\.)+?{$fqdn_part})";
$local = "({$dot_string}++|(\"){$quoted_string}++\")";
$domain = "({$fqdn}|\\[{$ipv4}]|\\[{$ipv6}]|\\[{$fqdn}])";
$pattern = "/\\A{$local}@{$domain}\\z/";
return preg_match($pattern, $email, $matches) &&
(
!empty($matches[2]) && !isset($matches[1][66]) && !isset($matches[0][256]) ||
!isset($matches[1][64]) && !isset($matches[0][254])
)
;
}
/**
* Wandelt ein Windows Date in ein Linux Date um
* @param date $ad_date Microsoft Date
* @return date <p>
* Linux date
*/
function convert_AD_date ($ad_date) {
if ($ad_date == 0) {
return '0000-00-00';
}
$secsAfterADEpoch = $ad_date / (10000000);
$AD2Unix=((1970-1601) * 365 - 3 + round((1970-1601)/4) ) * 86400;
// Why -3 ?
// "If the year is the last year of a century, eg. 1700, 1800, 1900, 2000,
// then it is only a leap year if it is exactly divisible by 400.
// Therefore, 1900 wasn't a leap year but 2000 was."
$unixTimeStamp=intval($secsAfterADEpoch-$AD2Unix);
$myDate = date("d-m-Y H:i:s", $unixTimeStamp); // formatted date
//$myDate = date("Y-m-d H:i:s", $unixTimeStamp); // formatted date
return $myDate;
}
/**
* Addiert Tage, Monate, Jahre zu einem Datum
* @param date $givendate date
* @param number $day zu addierende Tage
* @param number $mth zu addierende Monate
* @param number $yr zu addierende Jahre
* @return date <p>
* neues date
*/
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('d-m-Y h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
/**
* Schreibt HTML Header
* @param string $title Seitentitel
*/
function htmlheader($title){
echo "<html><head>";
echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
echo "<title>".$title."</title>";
echo "<link rel='stylesheet' type='text/css' href='hawmailer.css'>";
echo "<script language='JavaScript' src='javascript.js'></script>";
echo "</head><body>";
}
/**
* Gibt HTML Code für einen zurück Link und Logout Button aus
*/
function schreibezurueckundlogout(){
echo "<table>";
echo "<tr><td width=100><a href='index.php' class='button'>Zurück</a></td>";
echo "<td width=100><a href='login.php?out=1' class='button'>Logout</a></td></tr>";
echo "</table>";
}
?><file_sep><?php
/**
* Config File für Texte innerhalb der Anwendung
* texte.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
// ACHTUNG inerhalb der Texte dürfen auf keinen Fall doppelte Anführungsstriche verwendet werden
$text_anmeldung = "Eine Anmeldung ist nur Mitarbeitern von HIBS möglich. <br>
Als Benutzername bitte den HAW-Account eingeben (aaaxxx)";
$text_vorschlagsliste = "Füllen Sie dieses Formular bitte komplett aus um eine temporäre Benutzerkennung bei der HAW zu erhalten.<br>
Die Felde sind alle Pflichtfelder<br>
Nach dem Absenden des Formulars melden Sie sich bitte am Tresen.";
$text_üeberschrift = "<h1>Bitte geben Sie Ihre Daten für eine temporäre Benutzerkennung hier ein</h1>";
$text_erklärung = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est<p>";
$text_datenspeicherung = "<p>Ich stimme zu, das die in diesem Formular erfassten Daten zum Zweck der Nachverfolgung bei Missbrauch eines temporären Accounts bei der HAW-Hamburg für 30 Tage gespeichert werden. <br>Nach Ablauf dieser Zeit werden die Daten unwiederruflich gelöscht<br> Das Passwort wird verschlüsselt gespeichert und kann somit nicht ausgelesen werden.";
$text_üeberschrift_logon = "<h1>Temporäre HAW Benutzerkennungen freischalten</h1>";
$text_üeberschrift_logon2 = "<h2>Bitte melden Sie sich an</h2>";
$text_üeberschrift_logon3 = "<h2>Liste der registrierten Benutzer</h2>";
$text_logon = "<b>Eine Anmeldung ist nur Mitarbeitern von HIBS möglich</b>.<p><hr>";
?><file_sep><?php
/**
* Seite für die Verwaltung von Stadtlesern
* index.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
session_start ();
require './config/config.php';
require './config/texte.php';
require './helper.php';
require_once './classes/ADHelper.php';
require_once './classes/AD.php';
// ****************************************************************************************
// ist eine gültige Session vorhanden?
// ****************************************************************************************
if (isset ( $_SESSION ['user'] )) {
$aacount = $_SESSION ['user'];
// $filter = "(samaccountname=$aacount*)";
} else {
header ( "Location: login.php" );
exit ();
}
// ****************************************************************************************
// Passwort aus Session holen
// ****************************************************************************************
if (isset ( $_SESSION ['pwd'] )) {
$pwd = $_SESSION ['pwd'];
}
// ****************************************************************************************
// AD Objekt erzeugen
// ****************************************************************************************
$adh = new ADHelper ();
$ad = new AD ( $ad_ldap_server, $ad_auth_user, $ad_auth_pass, $ldap_usr_predom, $stadtleser_dn );
$ldapconn = $ad->get_ADConnection ();
// ****************************************************************************************
// Mysql Connection herstellen und verbinden
// ****************************************************************************************
$mysqlconn = mysql_connect ( $mysqlhost, $mysqluser, $mysqlpwd );
if (! mysql_select_db ( $mysqldb, $mysqlconn )) {
exit ( "SQL Select-DB ist fehlgeschlagen" );
}
$showdetails = 0;
// ****************************************************************************************
// verzweigen wenn Benutzer aktivieren geklickt wurde
// ****************************************************************************************
if (isset ( $_POST ['aktivierebenutzer'] )) {
if ($_POST ['aktivierebenutzer'] == "freischalten") {
// echo "<html><head>";
// echo "<meta http-equiv='refresh' content='6; URL=index.php'>";
// echo "</head><body>";
freischalten ();
exit ();
}
}
// HTML Header erzeugen
htmlheader ( $title );
echo "<div class='logoFreischalten'>";
echo $text_üeberschrift_logon;
echo $text_üeberschrift_logon3 . "<hr>";
echo " </div>";
// ****************************************************************************************
// Ist vorher Details oder Löschen eines Datensatzes gewählt
// ****************************************************************************************
if (isset ( $_POST ['benutzer'] )) {
// Löschen ist gewählt worden
if ($_POST ['benutzer'] == "löschen") {
$sql = "UPDATE benutzer SET markasdeleted='1' WHERE id='" . $_POST ['id'] . "'";
$mysqlres = mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl war nicht erfolgreich" );
}
// Details ist gewählt worden
if ($_POST ['benutzer'] == "Details") {
$showdetails = 1;
}
}
// ****************************************************************************************
// Haupttabelle anzeigen
// ****************************************************************************************
showDaten ();
echo "<p>";
echo "<a href='login.php?out=1' class='button'>Logout</a>";
// LDAP Connection schliesen
$ad->close ();
// MySQL Connection schliesen
mysql_close ( $mysqlconn );
echo "</body></html>";
/**
* Gibt Tabelle mit registrierten Benutzern aus
*/
function showDaten() {
global $mysqlconn, $showdetails, $key;
// ****************************************************************************************
// Alte Daten aus der Datenbank löchen
// ****************************************************************************************
$sql = "DELETE FROM `benutzer` WHERE DATEDIFF(NOW(),datum) >= 14";
mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl alte Daten löschen war nicht erfolgreich" );
echo "<table><tr><td>";
// ****************************************************************************************
// Hole Benutzer die nicht als gelöscht gekennzeichnet sind aus der Datenbank
// ****************************************************************************************
$sql = "SELECT * FROM benutzer WHERE markasdeleted='0'";
$mysqlres = mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl zeige alle Benutzer war nicht erfolgreich" );
echo "<table>";
echo "<tr class=tabtext><th>Erfassungsdatum</th><th>Name</th><th>Vorname</th><th></th><th>freigeschaltet bis</th><th>Fachbibliothek</th><th>Account</th><th>Aktion</th></tr>";
// ****************************************************************************************
// Benutzer Tabelle ausgeben
// ****************************************************************************************
while ( $row = mysql_fetch_array ( $mysqlres, MYSQL_ASSOC ) ) {
// printf("ID: %s Name: %s", $row["id"], $row["name"]);
if ((strtotime ( $row ["datum"] ) > (time () - 604800)) || $row ["status"] == "Nein") {
// echo "<form name='benutzer' method='post' action='" . $_SERVER ["PHP_SELF"] . "' onsubmit='return cfform(this)';>";
echo "<form name='benutzer' method='post' action='" . $_SERVER ["PHP_SELF"] . "' >";
if (isset ( $_POST ['id'] )) {
if ($row ["id"] == $_POST ['id']) {
echo "<tr class=tabtexthigh ><td >";
} else {
echo "<tr><td>";
}
} else {
echo "<tr><td>";
}
echo date ( "d.m.y H:i", strtotime ( $row ["datum"] ) ) . "</td><td>" . $row ["name"] . "</td><td>" . $row ["vorname"] . "</td><td><input type='hidden' name='id' value='" . $row ["id"] . "'></td><td>" . $row ["status"] . "</td><td>" . $row ["bibliothek"] . "</td><td>" . $row ["zuaccount"] . "</td>";
echo "<td><input type='submit' name='benutzer' value='Details' class='button'> <input type='submit' onclick='return cfform(this)'; name='benutzer' value='löschen' class='button'></td></tr>";
echo "</form>";
}
}
echo "</table>";
echo "</td>";
if ($showdetails == 1) {
showDatenDetails ();
}
echo "</tr></table>";
}
/**
* gibt Benutzerdatendetails aus
*/
function showDatenDetails() {
global $mysqlconn, $key;
$sql = "SELECT * FROM benutzer WHERE id='" . $_POST ['id'] . "'";
$mysqlres = mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl war nicht erfolgreich" );
echo "<td>";
echo "<form name='benutzerdetails' method='post' action='" . $_SERVER ["PHP_SELF"] . "' >";
while ( $row = mysql_fetch_array ( $mysqlres, MYSQL_ASSOC ) ) {
$pass = mcrypt_decrypt ( MCRYPT_3DES, $key, $row ['passwort'], MCRYPT_MODE_ECB );
echo "<table>";
echo "<tr class=tabtext><td>Name:</td>";
echo "<td>" . $row ['name'] . "</td></tr>";
echo "<tr class=tabtext><td>Vorname:</td>";
echo "<td>" . $row ["vorname"] . "</td></tr>";
echo "<tr class=tabtext><td>Geburtsdatum:</td>";
echo "<td>" . $row ['geburtsdatum'] . "</td></tr>";
echo "<tr class=tabtext><td>Strasse:</td>";
echo "<td>" . $row ['strasse'] . "</td></tr>";
echo "<tr class=tabtext><td>Postleitzahl - Stadt:</td>";
echo "<td>" . $row ['plz'] . " - " . $row ['ort'] . "</td></tr>";
echo "<tr class=tabtext><td>Bibliotheksnummer:</td>";
echo "<td>" . $row ['bibliotheksnummer'] . "</td></tr>";
echo "<tr class=tabtext><td>Dauer der temporären Benutzerkennung:</td>";
echo "<td>" . $row ['dauer'] . " Tag(e)</td></tr>";
echo "<tr class=tabtext><td>freigeschaltet:</td>";
echo "<td>" . $row ['status'] . "</td></tr>";
echo "<tr class=tabtext><td>zugewiesender Account:</td>";
echo "<td>" . $row ['zuaccount'] . "</td></tr>";
// echo "<tr class=tabtext><td>Passwort:</td>";
// echo "<td>" . $pass . "</td></tr>";
echo "<tr class=tabtext><td><input type='hidden' name='id' value='" . $_POST ['id'] . "'></td></tr>";
// echo "<td>" . $_POST ['id'] . "</td></tr>";
echo "<tr><td class=tabtext width=350>Benutzerkennung freischalten: </td>";
if ($row ['zuaccount'] == "keiner") {
// if(TRUE){
echo "<td><input type='submit' name='aktivierebenutzer' value='freischalten' class='button'></td></tr>";
} else {
echo "<td class=tabtexthigh >Ist schon freigeschaltet</td></tr>";
}
echo "</table>";
}
echo "</form>";
echo "</td>";
}
function freischalten() {
global $ldapconn, $stadtleser_dn, $stadtleserfilter, $LDAPFieldsToFind, $adh, $ad, $mysqlconn, $key;
$i = 0;
$newPassw = "";
$zuaccount = "";
$freierBenutzerGefunden = FALSE;
// Suche starten
$search = $ad->get_Users ( $stadtleserfilter );
// Anzahl gefundener Einträge ermitteln
$anzahl = $ad->get_AnzahlUsers ();
// userAccountControl 512=aktiv 514=deaktiviert
// accountExpires
foreach ( $search as $zeile ) {
htmlheader ( "Stadtleser freischalten" );
// $pwdablaufdate = convert_AD_date ( $zeile ["accountexpires"] [0] );
$pwdablaufdate = $adh->ConvertWindowsToUnixTimestamp ( $zeile ["accountexpires"] [0] );
$dn = $zeile ["distinguishedname"] [0];
if ($zeile ["useraccountcontrol"] [0] == 512) {
if ($pwdablaufdate < time ()) {
// dann setze das passwort und weise benutzer zu benutzer zu
$zuaccount = $zeile ["samaccountname"] [0];
// Benutzerobjekt aus Datenbank holen
$sql = "SELECT * FROM benutzer WHERE id='" . $_POST ['id'] . "'";
$mysqlres = mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl war nicht erfolgreich" );
while ( $row = mysql_fetch_array ( $mysqlres, MYSQL_ASSOC ) ) {
$dPasswort = mcrypt_decrypt ( MCRYPT_3DES, $key, $row ['passwort'], MCRYPT_MODE_ECB );
if ($row ['dauer'] == 1) {
$aktivBis = time () + 86400;
} else {
$aktivBis = time () + 604800;
}
$aktivBis = $adh->ConvertUnixToWindowsTimestamp ( $aktivBis );
$data ["givenname"] [0] = time ();
// var_dump ( $aktivBis );
$ae = sprintf ( '%f', $aktivBis );
$af = substr ( $ae, 0, 18 );
// $data["accountexpires"][0] = "9223372036854775807";
$data ["accountexpires"] [0] = $af;
// var_dump ( $data ["accountexpires"] [0] );
// echo date ( "d-m-Y H:i:s", $adh->ConvertWindowsToUnixTimestamp ( $data ["accountexpires"] [0] ) );
$data ["unicodepwd"] [0] = $adh->makeADPassword ( $dPasswort );
$aktivBis = date ( "d.m.y H:i", $adh->ConvertWindowsToUnixTimestamp ( $aktivBis ) );
// ldap_mod_replace ( $ldapconn, $dn, $data ) or die ( "Setzen des Kennworts nicht möglich. Fehlermeldung ist: " . $php_errormsg );
if (! $ad->set_UserAttributes ( $dn, $data )) {
echo "<b>Schreiben fehlgeschlagen ! AD nicht erreichbar oder Passwort entspricht nicht den Vorgaben ! Bitte kontaktieren Sie Ihren Systemadministrator !</b><br><a href='index.php' class='button'>zurück<a>";
exit ();
}
$sql = "UPDATE benutzer SET zuaccount='" . $zeile ["samaccountname"] [0] . "', status='" . $aktivBis . "', benutzer='" . $_SESSION ['user'] . "' WHERE id='" . $_POST ['id'] . "'";
//echo $sql;
$res = mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl war nicht erfolgreich" );
$freierBenutzerGefunden = TRUE;
}
}
}
if ($freierBenutzerGefunden == TRUE)
break;
if ($anzahl == $i) {
echo "<b>Freischalten NICHT erfolgreich ! KEIN temporärer Account mehr verfügbar. Bitte kontaktieren Sie Ihren Systemadministrator !</b><br><a href='index.php' class='button'>zurück<a>";
exit ();
}
$i ++;
}
echo "Freischalten erfolgreich ! Zugewiesenes Konto ist : <b>" . $zuaccount . "</b><br><a href='index.php' class='button'>zurück<a>";
}
?><file_sep><?php
/**
* Anmeldeseite am Active Directory
* login.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
session_start ();
require './config/config.php';
require './config/texte.php';
require './helper.php';
htmlheader ( $title );
echo "<div class='logo'>";
echo $text_üeberschrift_logon;
echo $text_üeberschrift_logon2;
echo $text_logon;
echo " </div>";
echo "<h3>Login</h3>";
// Seite wurde mit logout aufgerufen
if (isset ( $_GET ['out'] )) {
// destroy session
session_unset ();
$_SESSION = array ();
unset ( $_SESSION ['user'], $_SESSION ['access'] );
session_destroy ();
}
// Seite wurde mit Login aufgerufen
if (isset ( $_POST ['userLogin'] )) {
if (istaacount ( $_POST ['userLogin'] )) {
$anmeldekennung = $ldap_usr_predom . "\\" . $_POST ['userLogin'];
$filter = "(sAMAccountName=" . $_POST ['userLogin'] . ")";
} else {
$anmeldekennung = $_POST ['userLogin'];
$filter = "(userprincipalname=" . $_POST ['userLogin'] . ")";
}
// authenticator aufrufen
if (authenticate ( $anmeldekennung, $_POST ['userPassword'], $ad_ldap_server, $base_dn, $filter )) {
// authentication passed
header ( "Location: index.php" );
exit ();
} else {
// authentication failed
$error = 1;
}
}
// Fehler bei der Anmeldung
if (isset ( $error ))
echo "Login fehlgeschlagen: Falscher Benutzername/Passwort oder keine Berechtigung<br /-->";
// logout erfolgt
if (isset ( $_GET ['out'] ))
echo "Logout erfolgreich";
// ****************************************************************************************
// Anmeldeformular
// ****************************************************************************************
echo "<table><tr><td>";
echo "<form action='" . $_SERVER ["PHP_SELF"] . "' method='post'>";
echo "<table align=left ><tr><td class=tabtext>Benutzer: </td><td><input type='text' name='userLogin'>";
echo "</td></tr>";
echo "<tr><td class=tabtext>Password: </td><td><input type='<PASSWORD>' name='userPassword'></td></tr>";
echo "<tr><td><input type='submit' name='submit' value='Login' class='button'></td></tr>";
echo "</table>";
echo "</form>";
echo "</td><td>";
echo "<div id='ibox'><a href='#'>";
echo "<img src='i3.jpg' width='20' height='20' border='0' alt='Benutzer Informationen'>";
echo "<span>" . $text_anmeldung . "</span></a></div>";
echo "</td></tr></table>";
echo "</body></html>";
function authenticate($user, $password, $ldap_host, $ldap_dn, $filter) {
global $ad_ldap_server, $ldap_user_group, $base_dn, $LDAPFieldsToFind;
$ldap = ldap_connect ( "ldaps://".$ad_ldap_server );
// verify user and password
if (ldap_bind (@$ldap, $user, $password )) {
// check Gruppen Mitgliedschaften
$result = ldap_search ( $ldap, $base_dn, $filter, $LDAPFieldsToFind );
$entries = ldap_get_entries ( $ldap, $result );
ldap_unbind ( $ldap );
// check Mitarbeiter oder Student
// if ((substr($entries[0]['extensionattribute4'][0],0,1) == "M") || (substr($entries[0]['extensionattribute4'][0],0,1) == "m")){
// $access = 1;
// }
foreach ( $entries [0] ['memberof'] as $grps ) {
// ist in Gruppe ?
if (strpos ( $grps, $ldap_user_group ))
$access = 1;
}
if ($access != 0) {
// session variablen setzen
// $_SESSION['user'] = $user;
$_SESSION ['user'] = $entries [0] ['samaccountname'] [0];
$_SESSION ['access'] = $access;
$_SESSION ['pwd'] = <PASSWORD>;
return true;
} else {
// Benutzer hat keine rechte
return false;
}
} else {
// Bind fehlgeschlagen (Benutzername/Passwort falsch)
return false;
}
}
?><file_sep><?php
/**
* Seite für die Erfassung von Stadtlesern
* DatenErfassen.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
require '../config/config.php';
require '../config/texte.php';
require '../helper.php';
// header("Content-Type: text/plain; charset=utf-8");
// header("X-Content-Security-Policy: allow 'self'; img-src stadtleser.hibs.haw-hamburg.de; script-src stadtleser.hibs.haw-hamburg.de;");
if (isset ( $_POST ['benutzerdaten'] )) {
echo "<html><head>";
echo "<meta http-equiv='refresh' content='6; URL=index.php'>";
echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
echo "</head><body>";
// Mysql Connection herstellen und verbinden
$mysqlconn = mysql_connect ( $mysqlhost, $mysqluser, $mysqlpwd ) or exit ( "MySQL Verbindungsversuch fehlgeschlagen" );
mysql_select_db ( $mysqldb, $mysqlconn ) or exit ( "MySQL Select-DB fehlgeschlagen" );
// $newPassword = mb_convert_encoding('"' . $_POST ['passwort'] . '"', 'utf-16le');
$vPassword = mcrypt_encrypt ( MCRYPT_3DES, $key, $_POST ['passwort'], MCRYPT_MODE_ECB );
$vPassword = $vPassword.
// mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
// Daten in DB schreiben
$sql = "INSERT INTO benutzer (markasdeleted,name,vorname,geburtsdatum,strasse,plz,ort,bibliotheksnummer,bibliothek,passwort,dauer,status,zuaccount) VALUES('0','" . $_POST ['name'] . "','" . $_POST ['vorname'] . "','" . $_POST ['geburtsdatum'] . "','" . $_POST ['strasse'] . "','" . $_POST ['plz'] . "','" . $_POST ['ort'] . "','" . $_POST ['bibliotheksnummer'] . "','" . $_POST ['bibliothek'] . "','" . $vPassword . "','" . $_POST ['dauer'] . "','Nein','keiner')";
mysql_query ( $sql, $mysqlconn ) or exit ( "SQL Befehl war nicht erfolgreich" );
// POST array löschen und Seite neu laden
echo "Daten erfolgreich geschrieben :-)<br><b>Die Startseite lädt in 6 Sekunden von allein neu!";
// Mysql Connection schliesen
mysql_close ( $mysqlconn );
// header("'Location: ".$_SERVER["PHP_SELF"]."'");
exit ();
}
if (! isset ( $_POST ['name'] ))
$_POST ['name'] = NULL;
if (! isset ( $_POST ['vorname'] ))
$_POST ['vorname'] = NULL;
if (! isset ( $_POST ['geburtsdatum'] ))
$_POST ['geburtsdatum'] = NULL;
if (! isset ( $_POST ['strasse'] ))
$_POST ['strasse'] = NULL;
if (! isset ( $_POST ['plz'] ))
$_POST ['plz'] = NULL;
if (! isset ( $_POST ['ort'] ))
$_POST ['ort'] = NULL;
if (! isset ( $_POST ['erfassungszustimmung'] ))
$_POST ['erfassungszustimmung'] = NULL;
if (! isset ( $_POST ['passwort'] ))
$_POST ['passwort'] = NULL;
if (! isset ( $_POST ['bibliotheksnummer'] ))
$_POST ['bibliotheksnummer'] = NULL;
if (! isset ( $_POST ['dauer'] ))
$_POST ['dauer'] = NULL;
// HTML Header erzeugen
echo "<html><head>";
echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
echo "<title>" . $title_Datenerfassen . "</title>";
echo "<link rel='stylesheet' type='text/css' href='../hawmailer.css'>";
echo "<script language='JavaScript' src='../javascript.js'></script>";
//echo "<script language='JavaScript' src='../jquery-2.2.1.min.js'></script>";
echo "</head><body>";
echo "<div class='logo'>";
echo $text_üeberschrift;
echo $text_erklärung . "<hr>";
echo " </div>";
// ****************************************************************************************
// Formular ausgeben
// ****************************************************************************************
echo "<table><tr><td>";
echo "<form name='benutzererfassung' method='post' action='" . $_SERVER ["PHP_SELF"] . "' onsubmit='return pruefeFormular(this)';>";
echo "<table>";
echo "<tr class=tabtext><td>Name:</td>";
echo "<td><input type='text' name='name' placeholder='Mustermann' onblur='checkBuchstabenField(this)' required /></td></tr>";
echo "<tr class=tabtext><td>Vorname:</td>";
echo "<td><input type='text' name='vorname' placeholder='Max' onblur='checkBuchstabenField(this)' required /></td></tr>";
echo "<tr class=tabtext><td>Geburtsdatum:</td>";
echo "<td><input type='date' size='10' maxlength= '10' name='geburtsdatum' placeholder='01.01.1992' onblur='checkDatumField(this)' required /></td></tr>";
echo "<tr class=tabtext><td>Strasse:</td>";
echo "<td><input type='text' name='strasse' placeholder='Beispielstrasse 123' required ></td></tr>";
echo "<tr class=tabtext><td>Postleitzahl - Stadt:</td>";
echo "<td><input type='text' size='5' maxlength ='5' name='plz' onblur='checkPLZField(this)' required /> - <input type='text' name='ort' onblur='checkBuchstabenField(this)' required /></td></tr>";
echo "<tr class=tabtext><td>Bibliotheksnummer:</td>";
echo "<td><input type='text' size='12' maxlength ='12' name='bibliotheksnummer' onblur='checkBibNrField(this)' required /></td></tr>";
echo "<tr class=tabtext><td>Fachbibliothek:</td>";
echo "<td><select name='bibliothek' required ><option>Design Medien Information</option><option>Life Sciences</option><option>Soziale Arbeit & Pflege</option><option>Technik Wirtschaft Information</option></select></td></tr>";
echo "<tr class=tabtext><td>Die temporäre Benutzerkennung soll Ein oder Sieben Tage gültig sein:</td>";
echo "<td><input type='radio' required name='dauer' value='1'>1 Tag<input type='radio' name='dauer' Value='7'>7 Tage</td></tr>";
echo "<tr class=tabtext><td>Passwort:</td>";
echo "<td><input type='<PASSWORD>' name='passwort' onblur='checkPwdField(this)' required minlength='8' /></td></tr>";
echo "<tr class=tabtext><td>Passwort wiederholen:</td>";
echo "<td><input type='password' name='passwort2' onblur='checkPwdField(this)' required minlength='8' /></td></tr>";
echo "<tr class=tabtext><td>Ich stimme der Datenspeicherung zu<br> unten finden Sie alle Informationen zur Datenspeicherung</td>";
echo "<td><input type='checkbox' name='erfassungszustimmung' required value='unchecked'></td></tr>";
echo "<tr><td class=tabtext width=350>Daten senden und speichern: </td>";
echo "<td><input type='submit' name='benutzerdaten' value='Speichern' class='button'></td></tr>";
echo "</table>";
echo "</form>";
echo "</td><td>";
echo "<div id='ibox'><a href='#'>";
echo "<img src='../i3.jpg' width='20' height='20' border='0' alt='Benutzer Informationen'>";
echo "<span>" . $text_vorschlagsliste . "</span></a></div>";
echo "</td></tr></table>";
echo $text_datenspeicherung;
echo "</body>";
?>
<file_sep><?php
/**
* Config File der Anwendung
* config.php
*
* PHP Version 5 with SSL and LDAP support
*
* Written by <NAME>
* email: <EMAIL>
*
* @category ToolsAndUtilities
* @package Stadtleser
* @author <NAME>
* @copyright 2016 HAW-Hamburg
* @version 1.0.0
* @link http://
*/
//Anwendungsname
$title = "Freischaltung Externe";
$title_Datenerfassen = "Registrierung Externe";
// *** Parameter für den LDAP-Zugriff ***
// Domänencontroller
$ad_ldap_server = "mdc03.mailcluster.haw-hamburg.de";
// Konto und Passwort für den Zugriff
$ad_auth_user = "hawsch";
$ad_auth_pass = "<PASSWORD>";
// BaseDN für Suche
//$base_dn = "OU=HAW,DC=mailcluster,DC=haw-hamburg,DC=de";
$base_dn = "OU=HAW,DC=mailcluster,DC=haw-hamburg,DC=de";
$stadtleser_dn = "OU=Stadtleser,OU=User,OU=102,OU=100,OU=HAW,DC=mailcluster,DC=haw-hamburg,DC=de";
$stadtleserfilter = "(samaccountname=stadtleser*)";
// Active Directory user group
$ldap_user_group = "HIBS-Stadtleser-Admins";
// Domänenprefixe
$ldap_usr_dom = "@haw-hamburg.de";
$ldap_usr_predom ="HAWMAILCLUSTER";
$LDAPFieldsToFind = array("givenname","sn","displayname","cn","samaccountname","dn","distinguishedname","userprincipalname","useraccountcontrol","accountexpires","memberof","extensionattribute4");
//Mysql Config
$mysqlhost="localhost"; // MySQL-Host angeben
$mysqluser="root"; // MySQL-User angeben
$mysqlpwd=""; // Passwort angeben
$mysqldb="stadtleser"; // Gewuenschte Datenbank angeben
//Verschlüsselungskey
$key = "<KEY>";
?>
| 854dc14446503a6f75f1ab2a0f07aad8fc2cc3b1 | [
"JavaScript",
"SQL",
"PHP"
] | 11 | PHP | schoetty68/Stadtleser | f4d6e6945cc98b0c37b5fb2fd4522d3aea2e5150 | d792407bfc6c18960b5b471252dacac24f6719f4 |
refs/heads/master | <file_sep># bit-docs-prettify
<file_sep>require("./prettify-engine");
require("./prettify.less")
module.exports = function(){
var codes = document.getElementsByTagName("code");
for(var i = 0; i < codes.length; i ++){
var code = codes[i];
if(code.parentNode.nodeName.toUpperCase() === "PRE"){
code.className = code.className +" prettyprint";
}
}
//turn off batching (https://github.com/google/code-prettify/blob/master/src/prettify.js#L142)
window.PR_SHOULD_USE_CONTINUATION = false;
prettyPrint();
}
| 49549b1c44905777bd559f0cc10f3d42c132dd46 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | leoj3n/bit-docs-prettify | c91f7ee8086c5ca7936ce079336e5063b366dcf7 | 971e4aa3561c7182c8a96d54f280cf4646554acf |
refs/heads/master | <file_sep>package com.mine.dao;
import com.mine.pojo.Cart;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface CartMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_cart
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_cart
*
* @mbg.generated
*/
int insert(Cart record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_cart
*
* @mbg.generated
*/
Cart selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_cart
*
* @mbg.generated
*/
List<Cart> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_cart
*
* @mbg.generated
*/
int updateByPrimaryKey(Cart record);
/**
* 根据userId和productId查找购物车
* @param userId
* @param productId
*/
Cart selectByUserIdAndProductId(@Param("userId") Integer userId,@Param("productId") Integer productId);
//查看用户购物车信息
List<Cart> selectCartByUserId(Integer userId);
/**
* 判断是否全选
* 查询的是没有选中的数量
* @param userId
*/
int isCheckedAll(@Param("userId") Integer userId);
/**
* 删除选中的购物车中的商品
* @param userId
* @param stringList
*/
int deleteProduct(@Param("userId") Integer userId ,@Param("productIdList") List<String> stringList);
/**
* 选中购物车中的商品。或者取消选择 全选,或全不选
* @param userId
* @param productId
*/
int selectOrUnselectProduct(@Param("userId") Integer userId, @Param("productId") Integer productId, @Param("check") Integer check);
/**
* 查看购物车中有多少商品
* @param userId
* @return
*/
int get_cart_product_count(Integer userId);
/**
* 查询购物车中用户已选中的商品
* @Param userId
* */
List<Cart> findCartListByUserIdAndChecked(Integer userId);
/**
* 批量删除购物车商品
* */
int batchDelete(List<Cart> cartList);
}<file_sep>package com.mine.controller.portal;
import com.mine.common.ServerResponse;
import com.mine.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 杜晓鹏
* @create 2019-01-09 10:56
*/
@RestController
@RequestMapping("/product")
public class ProductControllerP {
@Autowired
ProductService productService;
/**
* 前台查看商品详情
*
* @param productId id
*/
@RequestMapping("/detail.do")
public ServerResponse detail_portal(Integer productId) {
return productService.detail_portal(productId);
}
/**
* 产品搜索及动态排序
*/
@RequestMapping("/list.do")
public ServerResponse searchAndOrderBy(@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) String keyword,
@RequestParam(required = false, defaultValue = "1") Integer pageNum,
@RequestParam(required = false, defaultValue = "10") Integer pageSize,
@RequestParam(required = false, defaultValue = "") String orderBy) {
return productService.searchAndOrderBy(categoryId, keyword, pageNum, pageSize, orderBy);
}
}
<file_sep>package com.mine.controller.portal;
import com.mine.common.Const;
import com.mine.common.ServerResponse;
import com.mine.pojo.UserInfo;
import com.mine.service.UserService;
import com.mine.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author 杜晓鹏
* @create 2019-01-04 18:50
*
* 前台用户模块
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
/**
* 登陆
*/
@RequestMapping("/login.do")
public ServerResponse login(HttpSession session, String username, String password, HttpServletResponse response) {
ServerResponse serverResponse = userService.login(username, password);
if (serverResponse.isSuccess()) {//登陆成功
UserInfo userInfo = (UserInfo) serverResponse.getData();
//如果登陆成功 将token 保存在cookie中
String token = MD5Utils.getMD5(username+password);
//token保存到数据库
userService.updateToken(token,userInfo.getId());
Cookie cookie = new Cookie(Const.CookieEnum.TOKEN.getDesc(),token);
cookie.setMaxAge(Const.CookieEnum.MIX_AGE.getCode()); //7天
cookie.setHttpOnly(true);
//设置cookie的路径
cookie.setPath("/business");
response.addCookie(cookie);
userInfo.setPassword("");
session.setAttribute(Const.CURRENTUSER, userInfo);
}
return serverResponse;
}
/**
* 注册
*/
@RequestMapping("/register.do")
public ServerResponse register(UserInfo userInfo) {
//调用service中的添加方法
ServerResponse serverResponse = userService.register(userInfo);
return serverResponse;
}
/**
* 根据用户名查找密保问题
*/
@RequestMapping("/forget_get_question.do")
public ServerResponse forget_get_question(String username) {
ServerResponse serverResponse = userService.forget_get_question(username);
return serverResponse;
}
/**
* 提交问题答案
*/
@RequestMapping("/forget_check_answer.do")
public ServerResponse forget_check_answer(String username, String question, String answer) {
ServerResponse serverResponse = userService.forget_check_answer(username, question, answer);
return serverResponse;
}
/**
* 忘记密码的重置密码
*/
@RequestMapping("/forget_reset_password.do")
public ServerResponse forget_reset_password(String username, String passwordNew, String forgetToken) {
ServerResponse serverResponse = userService.forget_reset_password(username, passwordNew, forgetToken);
return serverResponse;
}
/**
* 用户在登陆状态下修改密码
*/
@RequestMapping("/login_reset_password.do")
public ServerResponse login_reset_password(HttpSession session, String passwordOld, String passwordNew) {
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
String username = userInfo.getUsername();
ServerResponse serverResponse = userService.login_reset_password(username, passwordOld, passwordNew);
return serverResponse;
}
/**
* 检查用户名或者邮箱是否有效
*/
@RequestMapping("/check_valied.do")
public ServerResponse check_valied(String str, String type) {
ServerResponse serverResponse = userService.check_valied(str, type);
return serverResponse;
}
/**
* 获取登陆用户的信息
*/
@RequestMapping("/get_user_info.do")
public ServerResponse get_user_info(HttpSession session) {
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
//如果用户为空 说明用户未登陆
if (userInfo == null)
return ServerResponse.serverResponseError("用户未登陆");
userInfo.setPassword("");
return ServerResponse.serverResponseSuccess(userInfo);
}
/**
* 登陆状态更新个人信息
*/
@RequestMapping("/update_user_info.do")
public ServerResponse update_user_info(HttpSession session, UserInfo user) {
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
//如果用户为空 说明用户未登陆
if (user == null) {
return ServerResponse.serverResponseError("用户未登陆");
}
user.setId(userInfo.getId());
ServerResponse serverResponse = userService.update_user_info(user);
if (serverResponse.isSuccess()){
//更新session中的用户信息
UserInfo userInfo1 = userService.selectById(user.getId());
session.setAttribute(Const.CURRENTUSER,userInfo1);
}
return serverResponse;
}
/**
* 退出登陆
*/
@RequestMapping("/logout.do")
public ServerResponse logout(HttpSession session){
session.removeAttribute(Const.CURRENTUSER);
return ServerResponse.serverResponseSuccess("退出成功");
}
}
<file_sep>package com.mine.common;
/**
* @author 杜晓鹏
* @create 2019-01-04 19:56
*/
public class Const {
public static final String CURRENTUSER = "current_user";
public static final String TRADE_SUCCESS= "TRADE_SUCCESS";
public static final String AUTOLOGINTOKEN="autoLoginToken";
/**
* 定义一个枚举 存储状态码 2表示用户未登陆 3表示用户权限不足
*/
public enum ResponseCodeEnum {
NEED_LOGIN(2, "用户未登陆,请登陆"),
NO_PRIVILEGE(3, "用户权限不足");
private int code;
private String descr;
private ResponseCodeEnum(int code, String descr) {
this.code = code;
this.descr = descr;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
}
/**
* 定义一个枚举 存储状态码 1表示已选中 0表示未选中
*/
public enum CartCheckedEnum {
PRODUCT_CHECKED(1,"已选中"),
PRODUCT_UNCHECK(0, "未选中");
private int code;
private String descr;
private CartCheckedEnum(int code, String descr) {
this.code = code;
this.descr = descr;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
}
/**
* 用来存储商品的状态码
*/
public enum ProductCodeEnum {
PRODUCT_ONLINE(1, "上线"),
PRODUCT_OFFLINE(2, "下线"),
PRODUCT_DELETE(3, "删除");
private int code;
private String descr;
private ProductCodeEnum(int code, String descr) {
this.code = code;
this.descr = descr;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
}
/**
* 定义一个枚举 0是管理员 1是普通用户
*/
public enum RoleEnum {
ROLE_ADMIN(0, "管理员"),
ROLE_CUSTOMER(1, "普通用户");
private int code;
private String descr;
private RoleEnum(int code, String descr) {
this.code = code;
this.descr = descr;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
}
public enum OrderStatusEnum{
ORDER_CANCELED(0,"已取消"),
ORDER_UN_PAY(10,"未付款"),
ORDER_PAYED(20,"已付款"),
ORDER_SEND(40,"已发货"),
ORDER_SUCCESS(50,"交易成功"),
ORDER_CLOSED(60,"交易关闭")
;
private int code;
private String desc;
private OrderStatusEnum(int code,String desc){
this.code=code;
this.desc=desc;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static OrderStatusEnum codeOf(Integer code){
for(OrderStatusEnum orderStatusEnum: values()){
if(code==orderStatusEnum.getCode()){
return orderStatusEnum;
}
}
return null;
}
}
public enum PaymentEnum{
ONLINE(1,"线上支付")
;
private int code;
private String desc;
private PaymentEnum(int code,String desc){
this.code=code;
this.desc=desc;
}
public static PaymentEnum codeOf(Integer code){
for(PaymentEnum paymentEnum: values()){
if(code==paymentEnum.getCode()){
return paymentEnum;
}
}
return null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
public enum PaymentPlatformEnum{
ALIPAY(1,"支付宝")
;
private int code;
private String desc;
private PaymentPlatformEnum(int code,String desc){
this.code=code;
this.desc=desc;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
public enum CookieEnum{
TOKEN(0,"token"),
MIX_AGE(60*60*24*7,"mix_age")
;
private int code;
private String desc;
private CookieEnum(int code,String desc){
this.code=code;
this.desc=desc;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
}
<file_sep>package com.mine.service.impl;
import com.mine.common.ServerResponse;
import com.mine.dao.CategoryMapper;
import com.mine.pojo.Category;
import com.mine.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* @author 杜晓鹏
* @create 2019-01-07 14:51
*/
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
CategoryMapper categoryMapper;
@Override
public ServerResponse get_category(Integer categoryId) {
//非空判断
if (categoryId == null || categoryId.equals(""))
return ServerResponse.serverResponseError("类别id不能为空");
// Category category = categoryMapper.selectByPrimaryKey(categoryId);
// if (category == null)
// return ServerResponse.serverResponseError("查询的类别不存在!");
//查询子类别
List<Category> categories = categoryMapper.findChildCategory(categoryId);
if (categories == null || categories.size() == 0)
return ServerResponse.serverResponseError("查询的类别没有子类别");
return ServerResponse.serverResponseSuccess(categories);
}
@Override
public ServerResponse add_category(Integer parentId, String categoryName) {
//非空判断
if (categoryName == null || categoryName.equals(""))
return ServerResponse.serverResponseError("类别名字不能为空");
Category category = new Category();
category.setParentId(parentId);
category.setName(categoryName);
category.setStatus(true);
int result = categoryMapper.insert(category);
if (result > 0)
return ServerResponse.serverResponseSuccess();
return ServerResponse.serverResponseError("添加失败");
}
@Override
public ServerResponse set_category_name(Integer categoryId, String categoryName) {
//非空判断
if (categoryId == null || categoryId.equals(""))
return ServerResponse.serverResponseError("类别id不能为空");
if (categoryName == null || categoryName.equals(""))
return ServerResponse.serverResponseError("类别名字不能为空");
//查找到当前类别
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if (category == null)
return ServerResponse.serverResponseError("要修改的类别不存在");
//修改名字
category.setName(categoryName);
int result = categoryMapper.updateByPrimaryKey(category);
if (result > 0)
return ServerResponse.serverResponseSuccess();
return ServerResponse.serverResponseError("修改失败");
}
@Override
public ServerResponse get_deep_category(Integer categoryId) {
Set<Category> categories = new HashSet<>();
selectAllCategory(categories,categoryId);
//将查出来的所有类别的id加到新的集合中
Set<Integer> integerSet = new HashSet<>();
Iterator<Category> iterator = categories.iterator();
while (iterator.hasNext()){
Category category = iterator.next();
integerSet.add(category.getId());
}
return ServerResponse.serverResponseSuccess(integerSet);
}
//递归查询出所有的类别
private Set<Category> selectAllCategory(Set<Category> categories , Integer categoryId){
//先将当前查找到的category添加到集合中
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if (category != null)
categories.add(category);
//查出当前类别的子类别集合 此时就不需要使用mybatis 的递归查询了
List<Category> childCategory = categoryMapper.findChildCategory(categoryId);
//如果子类别的集合为空那么返回 不为空的话执行
if (childCategory != null && childCategory.size() > 0){
for (Category category1:childCategory){
//拿到当前类别的id作为parentId继续查找
selectAllCategory(categories,category1.getId());
categories.add(category1);
}
}
return categories;
}
}
<file_sep>package com.mine.utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Jedis;
/**
* @author 杜晓鹏
* @create 2019-01-18 11:12
*/
public class RedisPool {
private static JedisPool pool;
//最大连接数
private static Integer maxTotal=Integer.parseInt( PropertiesUtils.getValue("spring.redis.jedis.pool.max-active"));
//最大空闲数
private static Integer maxIdle=Integer.parseInt( PropertiesUtils.getValue("spring.redis.jedis.pool.max-idle"));
//最小空闲数
private static Integer minIdle=Integer.parseInt( PropertiesUtils.getValue("spring.redis.jedis.pool.min-idle"));
private static String redisIp=PropertiesUtils.getValue("spring.redis.host");
private static Integer redisPort=Integer.parseInt(PropertiesUtils.getValue("spring.redis.port"));
static {
initPool();
}
private static void initPool(){
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
//在连接耗尽时,是否阻塞;false:抛出异常,true:等待连接直到超时。默认true
config.setBlockWhenExhausted(true);
pool=new JedisPool(config,redisIp,redisPort,1000*2);
}
public static Jedis getJedis(){
return pool.getResource();
}
public static void returnResource(Jedis jedis){
pool.returnResource(jedis);
}
public static void returnBrokenResource(Jedis jedis){
pool.returnBrokenResource(jedis);
}
public static void main(String[] args) {
Jedis jedis=getJedis();
jedis.set("username","zhangsan");
returnResource(jedis);
pool.destroy();
System.out.println("=====program is end===");
}
}
<file_sep>package com.mine.vo;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* @author 杜晓鹏
* @create 2019-01-11 17:19
*/
@Data
public class CartOrderItemVO implements Serializable {
private List<OrderItemVO> orderItemVOList;
private String imageHost;
private BigDecimal totalPrice;
}
<file_sep>package com.mine.utils;
import lombok.Data;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
/**
* @author 杜晓鹏
* @create 2019-01-10 09:44
*/
@Data
public class FTPUtils {
/**
* ip地址
*/
private static final String FTPIP = PropertiesUtils.getValue("ftp.server.ip");
/**
* 用户名
*/
private static final String FTPUSER = PropertiesUtils.getValue("ftp.server.user");
/**
* 密码
*/
private static final String FTPPASSWORD = PropertiesUtils.getValue("ftp.server.password");
private String ftpIp;
private String ftpUser;
private String ftpPass;
private Integer ftpPort; //端口号
public FTPUtils(String ftpIp, String ftpUser, String ftpPass, Integer ftpPort) {
this.ftpIp = ftpIp;
this.ftpUser = ftpUser;
this.ftpPass = ftpPass;
this.ftpPort = ftpPort;
}
/**
* 图片上传到ftp
*/
public static boolean uploadFile(List<File> files) {
FTPUtils ftpUtils = new FTPUtils(FTPIP, FTPUSER, FTPPASSWORD, 21);
System.out.println("开始连接ftp服务器...");
//默认是 ftpfile目录下 此时 remotePath为img 那么目录就是 /ftpfile/img下面
ftpUtils.uploadFile("img", files);
return false;
}
public boolean uploadFile(String remotePath, List<File> files) {
FileInputStream fileInputStream = null;
//连接ftp服务器 连接时 用到ftpClient
if (connectFTPServer(ftpIp, ftpUser, ftpPass)) {
try {
//设置上传的目录
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(4096);//设置每次读取文件流时缓存数组的大小
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();//打开被动传输模式
for (File file : files){
fileInputStream = new FileInputStream(file);
ftpClient.storeFile(file.getName(),fileInputStream);
}
System.out.println("======图片上传成功======");
return true;
} catch (IOException e) {
e.printStackTrace();
System.out.println("图片上传失败...");
}finally {
try {
fileInputStream.close();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
FTPClient ftpClient = null;
public boolean connectFTPServer(String ip, String user, String password) {
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
return ftpClient.login(user, password);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
<file_sep>package com.mine.controller.backend;
import com.google.common.collect.Lists;
import com.mine.common.Const;
import com.mine.common.ServerResponse;
import com.mine.pojo.Product;
import com.mine.pojo.UserInfo;
import com.mine.service.ProductService;
import com.mine.utils.FTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.io.File;
/**
* @author 杜晓鹏
* @create 2019-01-08 08:51
*/
@RestController
@RequestMapping("/manager/product")
public class ProductController {
@Autowired
ProductService productService;
/**
* 更新或者添加商品
*/
@RequestMapping("/save.do")
public ServerResponse saveOrUpdate(HttpSession session, Product product) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(), Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
return productService.saveOrUpdate(product);
}
/**
* 商品上下架
*/
@RequestMapping("/set_sale_status.do")
public ServerResponse set_sale_status(HttpSession session, Integer productId, Integer status) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(), Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
return productService.set_sale_status(productId, status);
}
/**
* 查看商品详情
*/
@RequestMapping("/detail.do")
public ServerResponse detail(HttpSession session, Integer productId) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(), Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
return productService.detail(productId);
}
/**
* 查看商品详情
*/
@RequestMapping("/list.do")
public ServerResponse detail(HttpSession session,
@RequestParam(required = false,defaultValue = "1") Integer pageNum,
@RequestParam(required = false,defaultValue = "10")Integer pageSize) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(), Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
return productService.findAll(pageNum,pageSize);
}
/**
* 产品搜索
*/
@RequestMapping("/search.do")
public ServerResponse detail(HttpSession session,
@RequestParam(value = "productName",required = false)String productName,
@RequestParam(value = "productId",required = false)Integer productId,
@RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize",required = false,defaultValue = "10")Integer pageSize) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(), Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
return productService.search(productName,productId,pageNum,pageSize);
}
}
<file_sep>package com.mine.dao;
import com.mine.pojo.Product;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Set;
@Mapper
public interface ProductMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_product
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_product
*
* @mbg.generated
*/
int insert(Product record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_product
*
* @mbg.generated
*/
Product selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_product
*
* @mbg.generated
*/
List<Product> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_product
*
* @mbg.generated
*/
int updateByPrimaryKey(Product record);
/**
*更新商品
*/
int update(Product product);
/**
* 根据商品的id或者名字搜索
*/
List<Product> selectByProductIdOrProductName(@Param("productId") Integer productId,@Param("productName") String productName);
List<Product> searchProduct(@Param("integerSet") Set<Integer> integerSet, @Param("keyword") String keyword);
/**
* 按照商品id查询商品库存
* */
Integer findStockByProductId(Integer productId);
}<file_sep>package com.mine.service;
import com.mine.common.ServerResponse;
/**
* @author 杜晓鹏
* @create 2019-01-07 14:50
*/
public interface CategoryService {
/**
* 获取品类之类别(平级)
*/
ServerResponse get_category(Integer categoryId);
/**
* 增加类别
*/
ServerResponse add_category(Integer parentId,String categoryName);
/**
* 修改类别
*/
ServerResponse set_category_name(Integer categoryId, String categoryName);
/**
* 获取当前分类id并递归子节点categoryId
*/
ServerResponse get_deep_category(Integer categoryId);
}
<file_sep>package com.mine.controller.portal;
import com.mine.common.Const;
import com.mine.common.ServerResponse;
import com.mine.pojo.UserInfo;
import com.mine.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
/**
* @author 杜晓鹏
* @create 2019-01-09 19:08
*/
@RestController
@RequestMapping("/cart")
public class CartController {
@Autowired
CartService cartService;
/**
* 购物车中添加商品
*
* @param session
* @param count 商品数量
* @param productId 商品id
* @return
*/
@RequestMapping("/add.do")
public ServerResponse add(HttpSession session, Integer count, Integer productId) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.add(userInfo.getId(), productId, count);
}
/**
* 更新购物车中某个产品的数量
*/
@RequestMapping("/update.do")
public ServerResponse update(HttpSession session, Integer count, Integer productId) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.update(userInfo.getId(), productId, count);
}
/**
* 用户查看自己的购物车
*/
@RequestMapping("/list.do")
public ServerResponse list(HttpSession session) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.list(userInfo.getId());
}
/**
* 移除购物车某个产品
*/
@RequestMapping("/delete_product.do")
public ServerResponse delete_product(HttpSession session, String productIds) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.delete_product(userInfo.getId(), productIds);
}
/**
* 购物车中选中某个商品
*/
@RequestMapping("/select.do")
public ServerResponse select(HttpSession session, Integer productId) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.select(userInfo.getId(), productId,Const.CartCheckedEnum.PRODUCT_CHECKED.getCode());
}
/**
* 购物车中选中某个商品
*/
@RequestMapping("/un_select.do")
public ServerResponse un_select(HttpSession session, Integer productId, Integer check) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.select(userInfo.getId(), productId, Const.CartCheckedEnum.PRODUCT_UNCHECK.getCode());
}
/**
* 购物车中选中某个商品
*/
@RequestMapping("/select_all.do")
public ServerResponse select_all(HttpSession session, Integer productId,Integer check) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.select(userInfo.getId(), productId,Const.CartCheckedEnum.PRODUCT_CHECKED.getCode());
}
/**
* 购物车中选中某个商品
*/
@RequestMapping("/un_select_all.do")
public ServerResponse un_select_all(HttpSession session, Integer productId,Integer check) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.select(userInfo.getId(), productId,Const.CartCheckedEnum.PRODUCT_UNCHECK.getCode());
}
/**
* 查询在购物车里的产品数量
*/
@RequestMapping("/get_cart_product_count.do")
public ServerResponse get_cart_product_count(HttpSession session) {
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(), Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
return cartService.get_cart_product_count(userInfo.getId());
}
}
<file_sep>package com.mine.controller.backend;
import com.mine.common.Const;
import com.mine.common.ServerResponse;
import com.mine.pojo.UserInfo;
import com.mine.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.naming.directory.SearchResult;
import javax.servlet.http.HttpSession;
/**
* @author 杜晓鹏
* @create 2019-01-07 14:11
*/
@RestController
@RequestMapping("/manager/category")
public class CategoryController {
@Autowired
CategoryService categoryService;
/**
* 获取品类之类别(平级)
*/
@RequestMapping("/get_category.do")
public ServerResponse get_category(HttpSession session, Integer categoryId){
//先判断有没有用户登陆
UserInfo userInfo = (UserInfo)session.getAttribute(Const.CURRENTUSER);
if (userInfo == null)
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NEED_LOGIN.getCode(),Const.ResponseCodeEnum.NEED_LOGIN.getDescr());
//判断用户有没有普通管理员的权限
if (userInfo.getRole() != Const.RoleEnum.ROLE_ADMIN.getCode())
return ServerResponse.serverResponseError(Const.ResponseCodeEnum.NO_PRIVILEGE.getCode(),Const.ResponseCodeEnum.NO_PRIVILEGE.getDescr());
ServerResponse service_category = categoryService.get_category(categoryId);
return service_category;
}
/**
* 增加节点
*/
@RequestMapping("/add_category.do")
public ServerResponse add_category(@RequestParam(required = false,defaultValue = "0") Integer parentId, String categoryName){
return categoryService.add_category(parentId,categoryName);
}
/**
* 修改类别
*/
@RequestMapping("/set_category_name.do")
public ServerResponse set_category_name(Integer categoryId, String categoryName){
return categoryService.set_category_name(categoryId,categoryName);
}
/**
* 获取当前分类id并递归子节点categoryId
*/
@RequestMapping("/get_deep_category.do")
public ServerResponse get_deep_category(@RequestParam(required = false,defaultValue = "0") Integer categoryId){
return categoryService.get_deep_category(categoryId);
}
}
| 9d8e254533c035235b6d10dc60dd1c562a1d2a66 | [
"Java"
] | 13 | Java | strive3/shop_4 | 8533fbff846b10793c97353bcef48f7576f7c50c | 0ae0023464c0b64dd5f5b13efa79ed2a6d4205a0 |
refs/heads/master | <repo_name>DimaTrue/ramdaLearn<file_sep>/currying.js
const curry = fn => {
const count = fn.length;
return function f1(...args) {
if (args.length >= count) {
return fn(...args);
} else {
return function(...moreArgs) {
const newArgs = args.concat(moreArgs);
return f1(...newArgs);
};
}
};
};
// const add = (a, b) => a + b;
// // console.log(add(1, 2, "ignore")); // 3
// const curriedAdd = curry(add);
// console.log(curriedAdd(1)(2));
//////////////////////////////////////////////////////////////////////////////////////////////////
// const objects = [
// {
// id: 1
// },
// {
// id: 2
// },
// {
// id: 3
// }
// ];
// // const result = objects.map(obj => obj.id);
// const get = curry((property, object) => {
// return object[property];
// });
// // const result = objects.map(get("id"));
// // const getIds = function(objects) {
// // return objects.map(get("id"));
// // };
// const map = curry(function(fn, values) {
// return values.map(fn);
// });
// const getIds = map(get("id"));
// console.log(getIds(objects));
//////////////////////////////////////////////////////////////////////
const fetchFromServer = function() {
return new Promise(function(resolve) {
resolve({
user: "Jack",
posts: [
{
title: "why curry?"
},
{
title: "functional programming"
}
]
});
});
};
// fetchFromServer()
// .then(data => data.posts)
// .then(posts => posts.map(post => post.title))
// .then(titles => console.log("titles", titles));
const get = curry((property, object) => {
return object[property];
});
const map = curry(function(fn, values) {
return values.map(fn);
});
fetchFromServer()
.then(get("posts"))
.then(map(get("title")))
.then(titles => console.log("titles", titles));
<file_sep>/README.md
https://monsterlessons.com/project/series/funkcionalnyj-javascript-i-ramda
https://habr.com/ru/post/348868/
<file_sep>/lesson4.js
const R = require("ramda");
// const arr = [1, 2, 3];
// const newArr = R.append(4, arr);
// console.log(arr); // immutable data
// console.log(newArr);
//////////////////////////////////////////////////////////
// const users = [
// {
// id: 1,
// name: "Jhon"
// },
// {
// id: 2,
// name: "Alex"
// },
// {
// id: 3,
// name: "Bill"
// }
// ];
// // const alex = users.find(user => user.id === 2);
// // console.log(alex);
// // const test = R.propEq("id", 2, { id: 2 });
// const isAlex = R.propEq("id", 2);
// const alex = R.find(isAlex, users);
// console.log(alex);
/////////////////////////////////////////////////////////////////
// const wasBornInCountry = person => person.birthCountry === "UK";
// const wasNaturalized = person => Boolean(person.naturalizationDate);
// const isOver18 = person => person.age >= 18;
// const isCitizen = person => wasBornInCountry(person) || wasNaturalized(person);
// const isEligibleToVote = person => isOver18(person) && isCitizen(person);
// const testUser = {
// age: 20,
// birthCountry: "UK"
// };
// console.log(isEligibleToVote(testUser));
////////////// SIMPLE JAVASCRIPT /////////////////////////////////////////////////
const wasBornInCountry = R.propEq("birthCountry", "UK");
const wasNaturalized = person => Boolean(person.naturalizationDate);
const isOver18 = person => person.age >= 18;
const isCitizen = R.either(wasBornInCountry, wasNaturalized);
const isEligibleToVote = R.both(isOver18, isCitizen);
const testUser = {
age: 20,
birthCountry: "UK"
};
console.log(isEligibleToVote(testUser));
<file_sep>/curry.js
const curry = fn => {
const count = fn.length;
return function f1(...args) {
if (args.length >= count) {
return fn(...args);
} else {
return function(...moreArgs) {
const newArgs = args.concat(moreArgs);
return f1(...newArgs);
};
}
};
};
const add = (a, b, c) => {
return a + b + c;
};
const curriedAdd = curry(add);
console.log(curriedAdd(1, 2)(3));
module.export = {
curry
};
<file_sep>/index.js
const R = require("ramda");
const x = R.replace("name", R.__, "Hello, name!");
const tasks = [
{
id: 1,
complete: true
},
{
id: 2,
complete: false
},
{
id: 3,
complete: false
},
{
id: 4,
complete: false
}
];
const incomplete = R.filter(R.whereEq({ complete: false }));
// const taken = R.pipe(R.take(2), incomplete, R.project(["complete"]));
const taken = R.compose(R.take(2), incomplete, R.project(["complete"]));
console.log(taken(tasks));
// R.multiply(2, 10);
// const multiplyByTwo = R.multiply(2);
// console.log(multiplyByTwo(5));
| 08908798fea297071e73446f09bfb40cf185b1a4 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | DimaTrue/ramdaLearn | e5b68728fcc44a4337e9f7754f544125eb3eb435 | 95b4211434c70f5f4fcdbab6bc98ad24ad015100 |
refs/heads/master | <file_sep>package privateresearch.emotionrecognition;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.kbeanie.multipicker.api.ImagePicker;
import com.kbeanie.multipicker.api.entity.ChosenImage;
import com.kbeanie.multipicker.utils.IntentUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import com.kbeanie.multipicker.api.CameraImagePicker;
import com.kbeanie.multipicker.api.ImagePicker;
import com.kbeanie.multipicker.api.Picker;
import com.kbeanie.multipicker.api.callbacks.ImagePickerCallback;
import com.kbeanie.multipicker.api.entity.ChosenImage;
import static android.R.id.message;
public class ProcessPhoto extends AppCompatActivity {
private ImageSwitcher imageSwitcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_process_photo);
imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
return myView;
}
});
// imageSwitcher.setImageResource(image);
}
public void onImagesChosen(List<ChosenImage> images) {
// Display Images
Toast toast = Toast.makeText(getApplicationContext(), "Toast!", Toast.LENGTH_SHORT);
toast.show();
}
public void onError(String message) {
// Handle error
}
/**
private void handleMultipleShares() {
if (type.startsWith("image")) {
ImagePicker picker = new ImagePicker(this);
picker.setImagePickerCallback(this);
picker.submit(IntentUtils.getPickerIntentForSharing(getIntent()));
}
}**/
public static void main(String a[]){
try{
String pythonScript = "C:\\Users\\Omkar\\AppData\\Local\\Programs\\Python\\Python35\\label_image.py";
ProcessBuilder pb = new ProcessBuilder("python", pythonScript);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int ret = new Integer(in.readLine()).intValue();
System.out.println("value is : "+ret);
}
catch(Exception e){
System.out.println(e);
}
}
}
<file_sep>package privateresearch.emotionrecognition;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.kbeanie.multipicker.api.CameraImagePicker;
import com.kbeanie.multipicker.api.ImagePicker;
import com.kbeanie.multipicker.api.Picker;
import com.kbeanie.multipicker.api.callbacks.ImagePickerCallback;
import com.kbeanie.multipicker.api.entity.ChosenImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static android.R.attr.data;
import static android.R.attr.path;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MainActivity extends AppCompatActivity {
private static final int PICK_PHOTO_FOR_AVATAR = 1;
private int MY_PERMISSIONS_REQUEST_CAMERA;
private int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE;
private static boolean cameraPermission;
private static boolean readStorage;
private int RESULT_LOAD_IMAGE;
private int PICK_IMAGE_REQUEST;
private ImageView imageView;
ImagePicker imagePicker;
CameraImagePicker imagePicker2;
private ImagePickerCallback imagePickerCallback;
public String outputPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
Toast toast = Toast.makeText(getApplicationContext(), "Toast!", Toast.LENGTH_SHORT);
toast.show();*/
}
/** Called when the user presses the "Use Camera" button **/
public void pictureUseCamera (View view) {
Intent intent = new Intent(this, TakePhoto.class);
/**
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}*/
checkCameraPermission();
openApp(this, "org.tensorflow.demo");
/**
CameraImagePicker imagePicker2 = new CameraImagePicker(this);
imagePicker2.setImagePickerCallback(new ImagePickerCallback(){
@Override
public void onImagesChosen(List<ChosenImage> images) {
// Display images
}
@Override
public void onError(String message) {
// Do error handling
}}
);**/
// imagePicker.shouldGenerateMetadata(false); // Default is true
// imagePicker.shouldGenerateThumbnails(false); // Default is true
outputPath = imagePicker2.pickImage();
}
public void pictureFromFile (View view) {
imagePicker = new ImagePicker(this);
imagePicker.setImagePickerCallback(new ImagePickerCallback(){
@Override
public void onError(String message) {
// Do error handling
}
@Override
public void onImagesChosen(List<ChosenImage> images) {
// Display images
}
}
);
// imagePicker.allowMultiple(); // Default is false
// imagePicker.shouldGenerateMetadata(false); // Default is true
// imagePicker.shouldGenerateThumbnails(false); // Default is true
imagePicker.pickImage();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
if(requestCode == Picker.PICK_IMAGE_DEVICE) {
if(imagePicker == null) {
imagePicker = new ImagePicker(this);
imagePicker.setImagePickerCallback(imagePickerCallback);
}
imagePicker.submit(data);
}
if(requestCode == Picker.PICK_IMAGE_CAMERA) {
if(imagePicker2 == null) {
imagePicker2 = new CameraImagePicker(this);
imagePicker2.reinitialize(outputPath);
// OR in one statement
// imagePicker = new CameraImagePicker(Activity.this, outputPath);
imagePicker2.setImagePickerCallback(imagePickerCallback);
}
imagePicker2.submit(data);
}
}
}
public static void openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
Intent i = manager.getLaunchIntentForPackage(packageName);
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
}
public void checkFileReadPermission() {
int permissionCheckReadPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheckReadPermission == PERMISSION_GRANTED) {
readStorage = true;
} else if (permissionCheckReadPermission != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
}
public void checkCameraPermission() {
int permissionCheckCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (permissionCheckCamera == PERMISSION_GRANTED) {
cameraPermission = true;
} else if (permissionCheckCamera != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
cameraPermission = false;
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// You have to save path in case your activity is killed.
// In such a scenario, you will need to re-initialize the CameraImagePicker
outState.putString("picker_path", outputPath);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// After Activity recreate, you need to re-initialize these
// two values to be able to re-initialize CameraImagePicker
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("picker_path")) {
outputPath = savedInstanceState.getString("picker_path");
}
}
super.onRestoreInstanceState(savedInstanceState);
}
}
| b287326f9dfe1854c8ce4c9267324b7d7259f6a4 | [
"Java"
] | 2 | Java | osavkur/MetroHacks | 652a89dd0a23f1559322c79bef49c80d77125c5e | 91b7b86314694a67f8c0c4d4066c249e05360247 |
refs/heads/master | <repo_name>mbanani/pytorch-clickhere-cnn<file_sep>/datasets/pascal3d_kp.py
import torch
import time
import copy
import random
import pandas
import os
import numpy as np
from PIL import Image
from .vp_util import label_to_probs
from torchvision import transforms
from IPython import embed
class pascal3d_kp(torch.utils.data.Dataset):
"""
Construct a Pascal Dataset.
Inputs:
csv_path path containing instance data
augment boolean for flipping images
"""
def __init__(self, csv_path, dataset_root = None, im_size = 227, transform = None, map_size = 46, num_classes = 12, flip = False):
assert transform != None
start_time = time.time()
# Load instance data from csv-file
im_paths, bbox, kp_loc, kp_cls, obj_cls, vp_labels = self.csv_to_instances(csv_path)
csv_length = len(im_paths)
# dataset parameters
self.root = dataset_root
self.loader = self.pil_loader
self.im_paths = im_paths
self.bbox = bbox
self.kp_loc = kp_loc
self.kp_cls = kp_cls
self.obj_cls = obj_cls
self.vp_labels = vp_labels
self.img_size = im_size
self.map_size = map_size
self.num_classes = num_classes
self.num_instances = len(self.im_paths)
self.transform = transform
# Print out dataset stats
print("================================")
print("Pascal3D (w/ Keypoints) Stats: ")
print("CSV file length : ", len(im_paths))
print("Dataset size : ", self.num_instances)
print("Loading time (s) : ", time.time() - start_time)
"""
__getitem__ method:
Args:
index (int): Index
Returns:
tuple: (image, target) where target is class_index of the target class.
"""
def __getitem__(self, index):
# Load and transform image
if self.root == None:
c = self.im_paths[index]
else:
im_path = os.path.join(self.root, self.im_paths[index])
bbox = list(self.bbox[index])
kp_loc = list(self.kp_loc[index])
kp_cls = self.kp_cls[index]
obj_cls = self.obj_cls[index]
view = self.vp_labels[index]
# Transform labels
azim, elev, tilt = (view + 360.) % 360.
# Load and transform image
img, kp_loc = self.loader(im_path, bbox, kp_loc)
img = self.transform(img)
# Generate keypoint map image, and kp class vector
kpc_vec = np.zeros( (34) )
kpc_vec[kp_cls] = 1
kp_class = torch.from_numpy(kpc_vec).float()
kpm_map = self.generate_kp_map_chebyshev(kp_loc)
kp_map = torch.from_numpy(kpm_map).float()
# construct unique key for statistics -- only need to generate imid and year
_bb = str(bbox[0]) + '-' + str(bbox[1]) + '-' + str(bbox[2]) + '-' + str(bbox[3])
key_uid = self.im_paths[index] + '_' + _bb + '_objc' + str(obj_cls) + '_kpc' + str(kp_cls)
return img, azim, elev, tilt, obj_cls, kp_map, kp_class, key_uid
"""
Retuns the Length of the dataset
"""
def __len__(self):
return self.num_instances
"""
Image loader
Inputs:
path absolute image path
bbox 4-element tuple (x_min, y_min, x_max, y_max)
flip boolean for flipping image horizontally
kp_loc 2-element tuple (x_loc, y_loc)
"""
def pil_loader(self, path, bbox, kp_loc):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
with Image.open(f) as img:
# Calculate relative kp_loc position
kp_loc[0] = float(kp_loc[0]-bbox[0])/float(bbox[2]-bbox[0])
kp_loc[1] = float(kp_loc[1]-bbox[1])/float(bbox[3]-bbox[1])
# Convert to RGB, crop, and resize
img = img.convert('RGB')
# Convert to BGR from RGB
r, g, b = img.split()
img = Image.merge("RGB", (b, g, r))
img = img.crop(box=bbox)
img = img.resize( (self.img_size, self.img_size), Image.LANCZOS)
return img, kp_loc
"""
Convert CSV file to instances
"""
def csv_to_instances(self, csv_path):
# imgPath,bboxTLX,bboxTLY,bboxBRX,bboxBRY,imgKeyptX,imgKeyptY,keyptClass,objClass,azimuthClass,elevationClass,rotationClass
# /z/.../datasets/pascal3d/Images/bus_pascal/2008_000032.jpg,5,117,488,273,9.186347,158.402214,1,4,1756,1799,1443
df = pandas.read_csv(csv_path, sep=',')
data = df.values
data_split = np.split(data, [0, 1, 5, 7, 8, 9, 12], axis=1)
del(data_split[0])
image_paths = np.squeeze(data_split[0]).tolist()
# if self.root != None:
# image_paths = [path.split('pascal3d/')[1] for path in image_paths]
bboxes = data_split[1].tolist()
kp_loc = data_split[2].tolist()
kp_class = np.squeeze(data_split[3]).tolist()
obj_class = np.squeeze(data_split[4]).tolist()
viewpoints = np.array(data_split[5].tolist())
return image_paths, bboxes, kp_loc, kp_class, obj_class, viewpoints
"""
Generate Chbyshev-based map given a keypoint location
"""
def generate_kp_map_chebyshev(self, kp):
assert kp[0] >= 0. and kp[0] <= 1., kp
assert kp[1] >= 0. and kp[1] <= 1., kp
kp_map = np.ndarray( (self.map_size, self.map_size) )
kp[0] = kp[0] * self.map_size
kp[1] = kp[1] * self.map_size
for i in range(0, self.map_size):
for j in range(0, self.map_size):
kp_map[i,j] = max( np.abs(i - kp[0]), np.abs(j - kp[1]))
# Normalize by dividing by the maximum possible value, which is self.IMG_SIZE -1
kp_map = kp_map / (1. * self.map_size)
# kp_map = -2. * (kp_map - 0.5)
return kp_map
<file_sep>/util/torch_utils.py
import torch
import os
import shutil
def save_checkpoint(model, optimizer, curr_epoch, curr_step, args, curr_loss, curr_acc, filename):
"""
Saves a checkpoint and updates the best loss and best weighted accuracy
"""
is_best_loss = curr_loss < args.best_loss
is_best_acc = curr_acc > args.best_acc
args.best_acc = max(args.best_acc, curr_acc)
args.best_loss = min(args.best_loss, curr_loss)
state = { 'epoch':curr_epoch,
'step': curr_step,
'args': args,
'state_dict': model.state_dict(),
'val_loss': args.best_loss,
'val_acc': args.best_acc,
'optimizer' : optimizer.state_dict(),
}
path = os.path.join(args.experiment_path, filename)
torch.save(state, path)
if is_best_loss:
shutil.copyfile(path, os.path.join(args.experiment_path, 'model_best_loss.pkl'))
if is_best_acc:
shutil.copyfile(path, os.path.join(args.experiment_path, 'model_best_acc.pkl'))
return args
def accuracy(output, target, topk=(1,)):
""" From The PyTorch ImageNet example """
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
<file_sep>/util/metrics.py
import numpy as np
import scipy.misc
from scipy import linalg as linAlg
from IPython import embed
def compute_angle_dists(preds, labels):
# Get rotation matrices from prediction and ground truth angles
predR = angle2dcm(preds[0], preds[1], preds[2])
gtR = angle2dcm(labels[0], labels[1], labels[2])
# Get geodesic distance
return linAlg.norm(linAlg.logm(np.dot(predR.T, gtR)), 2) / np.sqrt(2)
def angle2dcm(xRot, yRot, zRot, deg_type='deg'):
if deg_type == 'deg':
xRot = xRot * np.pi / 180.0
yRot = yRot * np.pi / 180.0
zRot = zRot * np.pi / 180.0
xMat = np.array([
[np.cos(xRot), np.sin(xRot), 0],
[-np.sin(xRot), np.cos(xRot), 0],
[0, 0, 1]
])
yMat = np.array([
[np.cos(yRot), 0, -np.sin(yRot)],
[0, 1, 0],
[np.sin(yRot), 0, np.cos(yRot)]
])
zMat = np.array([
[1, 0, 0],
[0, np.cos(zRot), np.sin(zRot)],
[0, -np.sin(zRot), np.cos(zRot)]
])
return np.dot(zMat, np.dot(yMat, xMat))
class kp_dict(object):
def __init__(self, num_classes = 12):
self.keypoint_dict = dict()
self.num_classes = num_classes
self.class_ranges = list(range(0, 360*(self.num_classes + 1), 360))
self.threshold = np.pi / 6.
"""
Updates the keypoint dictionary
params: unique_id unique id of each instance (NAME_objc#_kpc#)
predictions the predictions for each vector
"""
def update_dict(self, unique_id, predictions, labels):
"""Log a scalar variable."""
if type(predictions) == int:
predictions = [predictions]
labels = [labels]
for i in range(0, len(unique_id)):
image = unique_id[i].split('_objc')[0]
obj_class = int(unique_id[i].split('_objc')[1].split('_kpc')[0])
kp_class = int(unique_id[i].split('_objc')[1].split('_kpc')[1])
start_index = self.class_ranges[obj_class]
end_index = self.class_ranges[obj_class + 1]
pred_probs = ( predictions[0][i], predictions[1][i], predictions[2][i])
label_probs = ( labels[0][i], labels[1][i], labels[2][i])
if image in list(self.keypoint_dict.keys()):
self.keypoint_dict[image][kp_class] = pred_probs
else:
self.keypoint_dict[image] = {'class' : obj_class, 'label' : label_probs, kp_class : pred_probs}
def calculate_geo_performance(self):
for image in list(self.keypoint_dict.keys()):
curr_label = self.keypoint_dict[image]['label']
self.keypoint_dict[image]['geo_dist'] = dict()
self.keypoint_dict[image]['correct'] = dict()
for kp in list(self.keypoint_dict[image].keys()):
if type(kp) != str :
curr_pred = [ np.argmax(self.keypoint_dict[image][kp][0]),
np.argmax(self.keypoint_dict[image][kp][1]),
np.argmax(self.keypoint_dict[image][kp][2])]
self.keypoint_dict[image]['geo_dist'][kp] = compute_angle_dists(curr_pred, curr_label)
self.keypoint_dict[image]['correct'][kp] = 1 if (self.keypoint_dict[image]['geo_dist'][kp] <= self.threshold) else 0
def metrics(self, unique = False):
self.calculate_geo_performance()
type_geo_dist = [ [] for x in range(0, self.num_classes)]
type_correct = np.zeros(self.num_classes, dtype=np.float32)
type_total = np.zeros(self.num_classes, dtype=np.float32)
for image in list(self.keypoint_dict.keys()):
object_type = self.keypoint_dict[image]['class']
curr_correct = 0.
curr_total = 0.
curr_geodist = []
for kp in list(self.keypoint_dict[image]['correct'].keys()):
curr_correct += self.keypoint_dict[image]['correct'][kp]
curr_total += 1.
curr_geodist.append(self.keypoint_dict[image]['geo_dist'][kp])
if unique:
curr_correct = curr_correct / curr_total
curr_total = 1.
curr_geodist = [np.median(curr_geodist)]
type_correct[object_type] += curr_correct
type_total[object_type] += curr_total
for dist in curr_geodist:
type_geo_dist[object_type].append(dist)
type_accuracy = np.zeros(self.num_classes, dtype=np.float16)
for i in range(0, self.num_classes):
if type_total[i] > 0:
type_accuracy[i] = float(type_correct[i]) / type_total[i]
self.calculate_performance_baselines()
return type_accuracy, type_total, type_geo_dist
def calculate_performance_baselines(self, mode = 'real'):
mean_baseline = [ [] for x in range(0, self.num_classes)]
total_baseline = [ [] for x in range(0, self.num_classes)]
#iterate over batch
for image in list(self.keypoint_dict.keys()):
obj_cls = self.keypoint_dict[image]['class']
perf = [self.keypoint_dict[image]['geo_dist'][kp] for kp in list(self.keypoint_dict[image]['geo_dist'].keys())]
# Append baselines
mean_baseline[obj_cls ].append(np.mean(perf))
for p in perf:
total_baseline[obj_cls ].append(p )
# embed()
accuracy_mean = np.around([ 100. * np.mean([ num < self.threshold for num in mean_baseline[i] ]) for i in range(0, self.num_classes) ], decimals = 2)
accuracy_total = np.around([ 100. * np.mean([ num < self.threshold for num in total_baseline[i] ]) for i in range(0, self.num_classes) ], decimals = 2)
medError_mean = np.around([ (180. / np.pi ) * np.median(mean_baseline[i] ) for i in range(0, self.num_classes) ], decimals = 2)
medError_total = np.around([ (180. / np.pi ) * np.median(total_baseline[i] ) for i in range(0, self.num_classes) ], decimals = 2)
if np.isnan(accuracy_mean[0]):
accuracy_mean = accuracy_mean[[4,5,8]]
accuracy_total = accuracy_total[[4,5,8]]
medError_mean = medError_mean[[4,5,8]]
medError_total = medError_total[[4,5,8]]
print("--------------------------------------------")
print("Accuracy ")
print("mean : ", accuracy_mean , " -- mean : ", np.round(np.mean(accuracy_mean ), decimals = 2))
print("total : ", accuracy_total , " -- mean : ", np.round(np.mean(accuracy_total ), decimals = 2))
print("")
print("Median Error ")
print("mean : ", medError_mean , " -- mean : ", np.round(np.mean(medError_mean ), decimals = 2))
print("total : ", medError_total , " -- mean : ", np.round(np.mean(medError_total ), decimals = 2))
print("--------------------------------------------")
<file_sep>/util/__init__.py
from .vp_loss import SoftmaxVPLoss
from .metrics import kp_dict
from .load_datasets import *
from . import Paths
<file_sep>/models/clickhere_cnn.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from IPython import embed
class clickhere_cnn(nn.Module):
def __init__(self, renderCNN, weights_path = None, num_classes = 12):
super(clickhere_cnn, self).__init__()
# Image Stream
self.conv4 = renderCNN.conv4
self.conv5 = renderCNN.conv5
self.infer = nn.Sequential(
nn.Linear(9216,4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096,4096),
nn.ReLU(),
nn.Dropout(0.5))
#Keypoint Stream
self.kp_map = nn.Linear(2116,2116)
self.kp_class = nn.Linear(34,34)
self.kp_fuse = nn.Linear(2150,169)
self.pool_map = nn.MaxPool2d( (5,5), (5,5), (1,1), ceil_mode=True)
# Fused layer
self.fusion = nn.Sequential(nn.Linear(4096 + 384, 4096), nn.ReLU(), nn.Dropout(0.5))
# Prediction layers
self.azim = nn.Linear(4096, 12 * 360)
self.elev = nn.Linear(4096, 12 * 360)
self.tilt = nn.Linear(4096, 12 * 360)
if weights_path is not None:
self.init_weights(weights_path)
def init_weights(self, weights_path):
npy_dict = np.load(weights_path, allow_pickle = True, encoding = 'latin1').item()
state_dict = npy_dict
# Convert parameters to torch tensors
for key in list(npy_dict.keys()):
state_dict[key]['weight'] = torch.from_numpy(npy_dict[key]['weight'])
state_dict[key]['bias'] = torch.from_numpy(npy_dict[key]['bias'])
self.conv4[0].weight.data.copy_(state_dict['conv1']['weight'])
self.conv4[0].bias.data.copy_(state_dict['conv1']['bias'])
self.conv4[4].weight.data.copy_(state_dict['conv2']['weight'])
self.conv4[4].bias.data.copy_(state_dict['conv2']['bias'])
self.conv4[8].weight.data.copy_(state_dict['conv3']['weight'])
self.conv4[8].bias.data.copy_(state_dict['conv3']['bias'])
self.conv4[10].weight.data.copy_(state_dict['conv4']['weight'])
self.conv4[10].bias.data.copy_(state_dict['conv4']['bias'])
self.conv5[0].weight.data.copy_(state_dict['conv5']['weight'])
self.conv5[0].bias.data.copy_(state_dict['conv5']['bias'])
self.infer[0].weight.data.copy_(state_dict['fc6']['weight'])
self.infer[0].bias.data.copy_(state_dict['fc6']['bias'])
self.infer[3].weight.data.copy_(state_dict['fc7']['weight'])
self.infer[3].bias.data.copy_(state_dict['fc7']['bias'])
self.fusion[0].weight.data.copy_(state_dict['fc8']['weight'])
self.fusion[0].bias.data.copy_(state_dict['fc8']['bias'])
self.kp_map.weight.data.copy_(state_dict['fc-keypoint-map']['weight'])
self.kp_map.bias.data.copy_(state_dict['fc-keypoint-map']['bias'])
self.kp_class.weight.data.copy_(state_dict['fc-keypoint-class']['weight'])
self.kp_class.bias.data.copy_(state_dict['fc-keypoint-class']['bias'])
self.kp_fuse.weight.data.copy_(state_dict['fc-keypoint-concat']['weight'])
self.kp_fuse.bias.data.copy_(state_dict['fc-keypoint-concat']['bias'])
self.azim.weight.data.copy_( state_dict['pred_azimuth' ]['weight'] )
self.elev.weight.data.copy_( state_dict['pred_elevation']['weight'] )
self.tilt.weight.data.copy_( state_dict['pred_tilt' ]['weight'] )
self.azim.bias.data.copy_( state_dict['pred_azimuth' ]['bias'] )
self.elev.bias.data.copy_( state_dict['pred_elevation']['bias'] )
self.tilt.bias.data.copy_( state_dict['pred_tilt' ]['bias'] )
def forward(self, images, kp_map, kp_cls, obj_class):
# Image Stream
conv4 = self.conv4(images)
im_stream = self.conv5(conv4)
im_stream = im_stream.view(im_stream.size(0), -1)
im_stream = self.infer(im_stream)
# Keypoint Stream
kp_map = kp_map.view(kp_map.size(0), -1)
kp_map = self.kp_map(kp_map)
kp_cls = self.kp_class(kp_cls)
# Concatenate the two keypoint feature vectors
kp_stream = torch.cat([kp_map, kp_cls], dim = 1)
# Softmax followed by reshaping into a 13x13
# Conv4 as shape batch * 384 * 13 * 13
kp_stream = F.softmax(self.kp_fuse(kp_stream), dim=1)
kp_stream = kp_stream.view(kp_stream.size(0) ,1, 13, 13)
# Attention -> Elt. wise product, then summation over x and y dims
kp_stream = kp_stream * conv4 # CHECK IF THIS DOES WHAT I THINK IT DOES!! TODO
kp_stream = kp_stream.sum(3).sum(2)
# Concatenate fc7 and attended features
fused_embed = torch.cat([im_stream, kp_stream], dim = 1)
fused_embed = self.fusion(fused_embed)
# Final inference
azim = self.azim(fused_embed)
elev = self.elev(fused_embed)
tilt = self.tilt(fused_embed)
# mask on class
azim = self.azim(fused_embed)
azim = azim.view(-1, 12, 360)
azim = azim[torch.arange(fused_embed.shape[0]), obj_class, :]
elev = self.elev(fused_embed)
elev = elev.view(-1, 12, 360)
elev = elev[torch.arange(fused_embed.shape[0]), obj_class, :]
tilt = self.tilt(fused_embed)
tilt = tilt.view(-1, 12, 360)
tilt = tilt[torch.arange(fused_embed.shape[0]), obj_class, :]
return azim, tilt, elev
<file_sep>/datasets/__init__.py
from .pascal3d import *
from .pascal3d_kp import *
<file_sep>/data/generate_pascal3d_csv.py
import os
import numpy as np
import scipy.io as spio
from IPython import embed
from util import Paths
INFO_FILE_HEADER = 'imgPath,bboxTLX,bboxTLY,bboxBRX,bboxBRY,imgKeyptX,imgKeyptY,keyptClass,objClass,azimuthClass,elevationClass,rotationClass\n'
synset_name_pairs = [ ('02691156', 'aeroplane'),
('02834778', 'bicycle'),
('02858304', 'boat'),
('02876657', 'bottle'),
('02924116', 'bus'),
('02958343', 'car'),
('03001627', 'chair'),
('04379243', 'diningtable'),
('03790512', 'motorbike'),
('04256520', 'sofa'),
('04468005', 'train'),
('03211117', 'tvmonitor')]
KEYPOINT_TYPES = {
'aeroplane' : ['right_wing', 'tail', 'rudder_upper', 'noselanding',
'left_wing', 'rudder_lower', 'right_elevator', 'left_elevator'],
'bicycle' : ['left_front_wheel', 'left_back_wheel', 'seat_back',
'right_front_wheel', 'left_pedal_center', 'head_center',
'left_handle', 'right_pedal_center', 'right_handle',
'right_back_wheel', 'seat_front'],
'boat' : ['head', 'head_left', 'head_down', 'head_right',
'tail', 'tail_left', 'tail_right'],
'bottle' : ['body', 'body_right', 'body_left', 'bottom_right',
'bottom', 'mouth', 'bottom_left'],
'bus' : ['body_back_left_lower', 'body_back_left_upper', 'body_back_right_lower',
'body_back_right_upper', 'body_front_left_upper', 'body_front_right_upper',
'body_front_left_lower', 'body_front_right_lower', 'left_back_wheel',
'left_front_wheel', 'right_back_wheel', 'right_front_wheel'],
'car' : ['left_front_wheel', 'left_back_wheel', 'right_front_wheel',
'right_back_wheel', 'upper_left_windshield', 'upper_right_windshield',
'upper_left_rearwindow', 'upper_right_rearwindow', 'left_front_light',
'right_front_light', 'left_back_trunk', 'right_back_trunk'],
'chair' : ['seat_upper_right', 'leg_upper_left', 'seat_lower_left', 'leg_upper_right',
'back_upper_left', 'leg_lower_left', 'seat_upper_left', 'leg_lower_right',
'seat_lower_right', 'back_upper_right'],
'diningtable' : ['top_upper_right', 'top_right', 'top_left', 'leg_upper_left',
'top_lower_left', 'top_lower_right', 'top_down', 'leg_upper_right',
'top_upper_left', 'leg_lower_left', 'leg_lower_right', 'top_up'],
'motorbike' : ['back_seat', 'front_seat', 'head_center', 'headlight_center',
'left_back_wheel', 'left_front_wheel', 'left_handle_center',
'right_back_wheel', 'right_front_wheel', 'right_handle_center'],
'sofa' : ['front_bottom_right', 'top_right_corner', 'top_left_corner',
'front_bottom_left', 'seat_bottom_right', 'seat_bottom_left',
'right_bottom_back', 'seat_top_right', 'left_bottom_back', 'seat_top_left'],
'train' : ['mid2_left_top', 'head_left_top', 'head_right_bottom', 'mid2_right_bottom',
'mid1_left_bottom', 'mid1_right_top', 'tail_right_bottom', 'tail_right_top', 'tail_left_top',
'head_right_top', 'head_left_bottom', 'mid2_left_bottom', 'tail_left_bottom', 'head_top',
'mid1_left_top', 'mid2_right_top', 'mid1_right_bottom'],
'tvmonitor' : ['front_bottom_right', 'back_top_left', 'front_top_left', 'front_bottom_left',
'back_bottom_left', 'front_top_right', 'back_top_right', 'back_bottom_right']
}
SYNSET_CLASSIDX_MAP = {}
for i in range(len(synset_name_pairs)):
synset, _ = synset_name_pairs[i]
SYNSET_CLASSIDX_MAP[synset] = i
KEYPOINT_CLASSES = []
for synset, class_name in synset_name_pairs:
keypoint_names = KEYPOINT_TYPES[class_name]
for keypoint_name in keypoint_names:
KEYPOINT_CLASSES.append(class_name + '_' + keypoint_name)
KEYPOINTCLASS_INDEX_MAP = {}
for i in range(len(KEYPOINT_CLASSES)):
KEYPOINTCLASS_INDEX_MAP[KEYPOINT_CLASSES[i]] = i
DATASET_SOURCES = ['pascal', 'imagenet']
PASCAL3D_ROOT = Paths.pascal3d_root
ANNOTATIONS_ROOT = os.path.join(PASCAL3D_ROOT, 'Annotations')
IMAGES_ROOT = os.path.join(PASCAL3D_ROOT, 'Images')
"""
Create pascal image kp dataset for all classes.
Code adapted from (https://github.com/rszeto/click-here-cnn)
"""
def create_pascal_image_kp_csvs(vehicles = False):
# Generate train and test lists and store in file
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if not (os.path.exists('trainImgIds.txt') and os.path.exists('valImgIds.txt')):
matlab_cmd = 'addpath(\'%s\'); getPascalTrainVal' % BASE_DIR
print('Generating MATLAB command: %s' % (matlab_cmd))
os.system('matlab -nodisplay -r "try %s; catch; end; quit;"' % matlab_cmd)
# os.system('matlab -nodisplay -r "%s; quit;"' % matlab_cmd)
# Get training and test image IDs
with open('trainImgIds.txt', 'rb') as trainIdsFile:
trainIds = np.loadtxt(trainIdsFile, dtype='string')
with open('valImgIds.txt', 'rb') as testIdsFile:
testIds = np.loadtxt(testIdsFile, dtype='string')
data_dir = os.path.join(os.path.dirname(BASE_DIR), 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if vehicles:
train_csv = os.path.join(data_dir, 'veh_pascal3d_kp_train.csv')
valid_csv = os.path.join(data_dir, 'veh_pascal3d_kp_valid.csv')
synset_name_pairs = [ ('02924116', 'bus'),
('02958343', 'car'),
('03790512', 'motorbike')]
else:
train_csv = os.path.join(data_dir, 'pascal3d_kp_train.csv')
valid_csv = os.path.join(data_dir, 'pascal3d_kp_valid.csv')
synset_name_pairs = [ ('02691156', 'aeroplane'),
('02834778', 'bicycle'),
('02858304', 'boat'),
('02876657', 'bottle'),
('02924116', 'bus'),
('02958343', 'car'),
('03001627', 'chair'),
('04379243', 'diningtable'),
('03790512', 'motorbike'),
('04256520', 'sofa'),
('04468005', 'train'),
('03211117', 'tvmonitor')]
SYNSET_CLASSIDX_MAP = {}
for i in range(len(synset_name_pairs)):
synset, _ = synset_name_pairs[i]
SYNSET_CLASSIDX_MAP[synset] = i
KEYPOINT_CLASSES = []
for synset, class_name in synset_name_pairs:
keypoint_names = KEYPOINT_TYPES[class_name]
for keypoint_name in keypoint_names:
KEYPOINT_CLASSES.append(class_name + '_' + keypoint_name)
KEYPOINTCLASS_INDEX_MAP = {}
for i in range(len(KEYPOINT_CLASSES)):
KEYPOINTCLASS_INDEX_MAP[KEYPOINT_CLASSES[i]] = i
info_file_train = open(train_csv, 'w')
info_file_train.write(INFO_FILE_HEADER)
info_file_test = open(valid_csv, 'w')
info_file_test.write(INFO_FILE_HEADER)
for synset, class_name in synset_name_pairs:
print("Generating data for %s " % (class_name))
all_zeros = 0
counter = 0
counter_kp = 0
object_class = SYNSET_CLASSIDX_MAP[synset]
for dataset_source in DATASET_SOURCES:
class_source_id = '%s_%s' % (class_name, dataset_source)
for anno_file in sorted(os.listdir(os.path.join(ANNOTATIONS_ROOT, class_source_id))):
anno_file_id = os.path.splitext(os.path.basename(anno_file))[0]
if anno_file_id in trainIds:
anno_file_set = 'train'
elif anno_file_id in testIds:
anno_file_set = 'test'
else:
continue
anno = loadmat(os.path.join(ANNOTATIONS_ROOT, class_source_id, anno_file))['record']
rel_image_path = os.path.join('Images', class_source_id, anno['filename'])
# Make objs an array regardless of how many objects there are
objs = np.array([anno['objects']]) if isinstance(anno['objects'], dict) else anno['objects']
for obj_i, obj in enumerate(objs):
# Only deal with objects in current class
if obj['class'] == class_name:
# Get crop using bounding box from annotation
# Note: Annotations are in MATLAB coordinates (1-indexed), inclusive
# Convert to 0-indexed numpy array
bbox = np.array(obj['bbox']) - 1
# Get visible and in-frame keypoints
keypoints = obj['anchors']
try:
assert set(KEYPOINT_TYPES[class_name]) == set(keypoints.keys())
except:
print("Assertion failed for keypoint types")
embed()
viewpoint = obj['viewpoint']
# Remove erronous KPs
if(viewpoint['azimuth'] == viewpoint['theta'] == viewpoint['elevation'] == 0.0):
all_zeros += 1
else:
counter += 1
azimuth = np.mod(np.round(viewpoint['azimuth']), 360)
elevation = np.mod(np.round(viewpoint['elevation']), 360)
tilt = np.mod(np.round(viewpoint['theta']), 360)
for keypoint_name in KEYPOINT_TYPES[class_name]:
# Get 0-indexed keypoint location
keypoint_loc_full = keypoints[keypoint_name]['location'] - 1
if keypoint_loc_full.size > 0 and insideBox(keypoint_loc_full, bbox):
counter_kp += 1
# Add info for current keypoint
keypoint_class = KEYPOINTCLASS_INDEX_MAP[class_name + '_' + keypoint_name]
if vehicles:
if object_class == 0:
final_label = ( 4, azimuth, elevation, tilt)
elif object_class == 1:
final_label = ( 5, azimuth, elevation, tilt)
elif object_class == 2:
final_label = ( 8, azimuth, elevation, tilt)
else:
print("Error: Object classes do not match expected values!")
keypoint_str = keypointInfo2Str(rel_image_path, bbox, keypoint_loc_full, keypoint_class, final_label)
if anno_file_set == 'train':
info_file_train.write(keypoint_str)
else:
info_file_test.write(keypoint_str)
print("%s : %d images %d image-kp pairs, %d ommited " % (class_name, counter, counter_kp, all_zeros))
info_file_train.close()
info_file_test.close()
"""
Create pascal image kp dataset for all classes.
Code adapted from (https://github.com/rszeto/click-here-cnn)
"""
def create_pascal_image_csvs(easy = False):
# Generate train and test lists and store in file
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if not (os.path.exists('trainImgIds.txt') and os.path.exists('valImgIds.txt')):
matlab_cmd = 'addpath(\'%s\'); getPascalTrainVal' % BASE_DIR
print('Generating MATLAB command: %s' % (matlab_cmd))
os.system('matlab -nodisplay -r "try %s; catch; end; quit;"' % matlab_cmd)
# os.system('matlab -nodisplay -r "%s; quit;"' % matlab_cmd)
# Get training and test image IDs
with open('trainImgIds.txt', 'rb') as trainIdsFile:
trainIds = np.loadtxt(trainIdsFile, dtype='string')
with open('valImgIds.txt', 'rb') as testIdsFile:
testIds = np.loadtxt(testIdsFile, dtype='string')
data_dir = os.path.join(os.path.dirname(BASE_DIR), 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if easy:
train_csv = os.path.join(data_dir, 'pascal3d_train_easy.csv')
valid_csv = os.path.join(data_dir, 'pascal3d_valid_easy.csv')
else:
train_csv = os.path.join(data_dir, 'pascal3d_train.csv')
valid_csv = os.path.join(data_dir, 'pascal3d_valid.csv')
info_file_train = open(train_csv, 'w')
info_file_train.write(INFO_FILE_HEADER)
info_file_test = open(valid_csv, 'w')
info_file_test.write(INFO_FILE_HEADER)
for synset, class_name in synset_name_pairs:
print("Generating data for %s " % (class_name))
all_zeros = 0
hard_images = 0
counter = 0
object_class = SYNSET_CLASSIDX_MAP[synset]
for dataset_source in DATASET_SOURCES:
class_source_id = '%s_%s' % (class_name, dataset_source)
for anno_file in sorted(os.listdir(os.path.join(ANNOTATIONS_ROOT, class_source_id))):
anno_file_id = os.path.splitext(os.path.basename(anno_file))[0]
if anno_file_id in trainIds:
anno_file_set = 'train'
elif anno_file_id in testIds:
anno_file_set = 'test'
else:
continue
anno = loadmat(os.path.join(ANNOTATIONS_ROOT, class_source_id, anno_file))['record']
rel_image_path = os.path.join('Images', class_source_id, anno['filename'])
# Make objs an array regardless of how many objects there are
objs = np.array([anno['objects']]) if isinstance(anno['objects'], dict) else anno['objects']
for obj_i, obj in enumerate(objs):
# Only deal with objects in current class
if obj['class'] == class_name:
# Get crop using bounding box from annotation
# Note: Annotations are in MATLAB coordinates (1-indexed), inclusive
# Convert to 0-indexed numpy array
bbox = np.array(obj['bbox']) - 1
viewpoint = obj['viewpoint']
# Remove erronous KPs
if(viewpoint['azimuth'] == viewpoint['theta'] == viewpoint['elevation'] == 0.0):
all_zeros += 1
elif (easy and (obj['difficult'] == 1 or obj['truncated'] == 1 or obj['occluded'] == 1 )):
hard_images += 1
else:
counter += 1
azimuth = np.mod(np.round(viewpoint['azimuth']), 360)
elevation = np.mod(np.round(viewpoint['elevation']), 360)
tilt = np.mod(np.round(viewpoint['theta']), 360)
final_label = ( object_class, azimuth, elevation, tilt)
viewpoint_str = viewpointInfo2Str(rel_image_path, bbox, final_label)
if anno_file_set == 'train':
info_file_train.write(viewpoint_str)
else:
info_file_test.write(viewpoint_str)
print("%s : %d images, ommitted: all_zeros - %d, difficult - %d " % (class_name, counter, all_zeros,hard_images))
info_file_train.close()
info_file_test.close()
######### Importing .mat files ###############################################
######### Reference: http://stackoverflow.com/a/8832212 ######################
def loadmat(filename):
'''
this function should be called instead of direct spio.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects
'''
data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data)
def _check_keys(dict):
'''
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
'''
for key in dict:
if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):
dict[key] = _todict(dict[key])
return dict
def _todict(matobj):
'''
A recursive function which constructs from matobjects nested dictionaries
'''
dict = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, spio.matlab.mio5_params.mat_struct):
dict[strg] = _todict(elem)
# Handle case where elem is an array of mat_structs
elif isinstance(elem, np.ndarray) and len(elem) > 0 and \
isinstance(elem[0], spio.matlab.mio5_params.mat_struct):
dict[strg] = np.array([_todict(subelem) for subelem in elem])
else:
dict[strg] = elem
return dict
def insideBox(point, box):
return point[0] >= box[0] and point[0] <= box[2] \
and point[1] >= box[1] and point[1] <= box[3]
def keypointInfo2Str(fullImagePath, bbox, keyptLoc, keyptClass, viewptLabel):
return '%s,%d,%d,%d,%d,%f,%f,%d,%d,%d,%d,%d\n' % (
fullImagePath,
bbox[0], bbox[1], bbox[2], bbox[3],
keyptLoc[0], keyptLoc[1],
keyptClass,
viewptLabel[0], viewptLabel[1], viewptLabel[2], viewptLabel[3]
)
def viewpointInfo2Str(fullImagePath, bbox, viewptLabel):
return '%s,%d,%d,%d,%d,%d,%d,%d,%d\n' % (
fullImagePath,
bbox[0], bbox[1], bbox[2], bbox[3],
viewptLabel[0], viewptLabel[1], viewptLabel[2], viewptLabel[3]
)
if __name__ == '__main__':
# create_pascal_image_kp_csvs()
create_pascal_image_kp_csvs(vehicles = True) # Just vehicles
# create_pascal_image_csvs()
# create_pascal_image_csvs(easy = True) # Easy subset
<file_sep>/util/load_datasets.py
import os,sys, math
import torch
import numpy as np
import torchvision.transforms as transforms
from datasets import pascal3d, pascal3d_kp
from IPython import embed
from .Paths import *
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
dataset_root = pascal3d_root
def get_data_loaders(dataset, batch_size, num_workers, model, num_classes = 12):
image_size = 227
train_transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize( mean=(0., 0., 0.),
std=(1./255., 1./255., 1./255.)
),
transforms.Normalize( mean=(104, 116.668, 122.678),
std=(1., 1., 1.)
)
])
test_transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize( mean=(0., 0., 0.),
std=(1./255., 1./255., 1./255.)
),
transforms.Normalize( mean=(104, 116.668, 122.678),
std=(1., 1., 1.)
)
])
# # The New transform for ImageNet Stuff
# new_transform = transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize(mean=(0.485, 0.456, 0.406),
# std=(0.229, 0.224, 0.225))])
if dataset == "pascal":
csv_train = os.path.join(root_dir, 'data/pascal3d_train.csv')
csv_test = os.path.join(root_dir, 'data/pascal3d_valid.csv')
train_set = pascal3d(csv_train, dataset_root= dataset_root, transform = train_transform, im_size = image_size)
test_set = pascal3d(csv_test, dataset_root= dataset_root, transform = test_transform, im_size = image_size)
elif dataset == "pascalEasy":
csv_train = os.path.join(root_dir, 'data/pascal3d_train_easy.csv')
csv_test = os.path.join(root_dir, 'data/pascal3d_valid_easy.csv')
train_set = pascal3d( csv_train, dataset_root= dataset_root,
transform = train_transform, im_size = image_size)
test_set = pascal3d( csv_test, dataset_root= dataset_root,
transform = test_transform, im_size = image_size)
elif dataset == "pascalVehKP":
csv_train = os.path.join(root_dir, 'data/veh_pascal3d_kp_train.csv')
csv_test = os.path.join(root_dir, 'data/veh_pascal3d_kp_valid.csv')
train_set = pascal3d_kp(csv_train,
dataset_root= dataset_root,
transform = train_transform,
im_size = image_size,
num_classes = num_classes)
test_set = pascal3d_kp(csv_test,
dataset_root= dataset_root,
transform = test_transform,
im_size = image_size,
num_classes = num_classes)
elif dataset == "pascalKP":
csv_train = os.path.join(root_dir, 'data/pascal3d_kp_train.csv')
csv_test = os.path.join(root_dir, 'data/pascal3d_kp_valid.csv')
train_set = pascal3d_kp(csv_train, dataset_root= dataset_root, transform = train_transform, im_size = image_size)
test_set = pascal3d_kp(csv_test, dataset_root= dataset_root, transform = test_transform, im_size = image_size)
else:
print("Error in load_datasets: Dataset name not defined.")
# Generate data loaders
train_loader = torch.utils.data.DataLoader( dataset = train_set,
batch_size =batch_size,
shuffle = True ,
num_workers =num_workers,
drop_last = True)
test_loader = torch.utils.data.DataLoader( dataset=test_set,
batch_size=batch_size,
shuffle = False,
num_workers=num_workers,
drop_last = False)
return train_loader, test_loader
<file_sep>/util/vp_loss.py
"""
Multi-class Geometric Viewpoint Aware Loss
A PyTorch implmentation of the geometric-aware softmax view loss as described in
RenderForCNN (link: https://arxiv.org/pdf/1505.05641.pdf)
Caffe implmentation:
https://github.com/charlesq34/caffe-render-for-cnn/blob/view_prediction/
"""
import torch
from torch import nn
from IPython import embed
import torch.nn.functional as F
import numpy as np
class SoftmaxVPLoss(nn.Module):
# Loss parameters taken directly from Render4CNN paper
# azim_band_width = 7 # 15 in paper
# elev_band_width = 2 # 5 in paper
# tilt_band_width = 2 # 5 in paper
# azim_sigma = 5
# elev_sigma = 3
# tilt_sigma = 3
def __init__(self, kernel_size = 7, sigma=25):
super(SoftmaxVPLoss, self).__init__()
self.filter = self.viewloss_filter(kernel_size, sigma)
self.kernel_size = kernel_size
def viewloss_filter(self, size, sigma):
vec = np.linspace(-1*size, size, 1 + 2*size, dtype=np.float)
prob = np.exp(-1 * abs(vec) / sigma)
# # normalize filter because otherwise loss will scale with kernel size
# prob = prob / np.sum(prob)
prob = torch.FloatTensor(prob)[None, None, :] # 1 x 1 x (1 + 2*size)
return prob
def forward(self, preds, labels, size_average=True):
"""
:param preds: Angle predictions (batch_size, 360 x num_classes)
:param targets: Angle labels (batch_size, 360 x num_classes)
:return: Loss. Loss is a variable which may have a backward pass performed.
Apply softmax over the preds, and then apply geometrics loss
"""
# Set absolute minimum for numerical stability (assuming float16 - 6x10^-5)
assert len(labels.shape) == 1
batch_size = labels.shape[0]
# Construct onehot labels -- dimension has to be (batch x 1 x dimension)
"""
I thought that creation of a new tensor might slow down calculations
but it doesn't seem to slow things;
10^4 iterations of scatter to batch of 256 took 0.5 sec
speed test:
scatter is ~25% faster for small batches (32),
indexing is ~25% faster for larger batches (>1024)
both are the same around 256 batch size
"""
labels = labels.long()
labels_oh = torch.zeros(batch_size, 360)
labels_oh[torch.arange(batch_size), labels] = 1.
x = labels_oh.cuda()
# Concat one hot vector and convolve
labels_oh = torch.cat( ( labels_oh[:, -self.kernel_size:],
labels_oh,
labels_oh[:, :self.kernel_size]),
dim = 1)
labels_oh = F.conv1d(labels_oh[:, None, :], self.filter)
# convert labels to CUDA
labels_oh = labels_oh.squeeze(1).cuda()
# calculate loss -- sum from paper
loss = (-1 * labels_oh * preds.log_softmax(1)).sum(1)
#loss = loss / (1 + 2 * self.kernel_size)
# loss = F.mse_loss(preds.softmax(1), labels_oh, reduction = 'sum')
if size_average:
loss = loss.mean()
else:
loss = loss.sum()
return loss
<file_sep>/datasets/vp_util.py
import numpy as np
import os
import sys
def label_to_probs(view_angles, flip):
# extract angles
azim = view_angles[0] % 360
elev = view_angles[1] % 360
tilt = view_angles[2] % 360
if flip:
azim = (360-azim) % 360
tilt = (-1 *tilt) % 360
<file_sep>/models/render4cnn.py
import torch
import torch.nn as nn
from IPython import embed
class render4cnn(nn.Module):
def __init__(self, weights_path = None):
super(render4cnn, self).__init__()
# define model
self.conv4 = nn.Sequential(
nn.Conv2d(3, 96, (11, 11), (4,4)),
nn.ReLU(),
nn.MaxPool2d( (3,3), (2,2), (0,0), ceil_mode=True),
nn.LocalResponseNorm(5, alpha=0.0001, beta=0.75, k=1.),
nn.Conv2d(96, 256, (5, 5), (1,1), (2,2), 1,2),
nn.ReLU(),
nn.MaxPool2d( (3,3), (2,2), (0,0), ceil_mode=True),
nn.LocalResponseNorm(5, alpha=0.0001, beta=0.75, k=1.),
nn.Conv2d(256,384,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(384,384,(3, 3),(1, 1),(1, 1),1,2),
nn.ReLU(),
)
self.conv5 = nn.Sequential(
nn.Conv2d(384,256,(3, 3),(1, 1),(1, 1),1,2),
nn.ReLU(),
nn.MaxPool2d((3, 3),(2, 2),(0, 0),ceil_mode=True),
)
self.infer = nn.Sequential(
nn.Linear(9216,4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096,4096),
nn.ReLU(),
nn.Dropout(0.5),
)
self.azim = nn.Linear(4096, 12 * 360)
self.elev = nn.Linear(4096, 12 * 360)
self.tilt = nn.Linear(4096, 12 * 360)
if weights_path is not None:
self._initialize_weights(weights_path)
# weight initialization from torchvision/models/vgg.py
def _initialize_weights(self, weights_path):
state_dict = torch.load(weights_path)['model_state_dict']
layers = [0, 4, 8, 10]
for l in layers:
self.conv4[l].weight.data.copy_( state_dict['conv4.'+str(l) + '.weight'])
self.conv4[l].bias.data.copy_( state_dict['conv4.'+str(l) + '.bias'])
self.conv5[0].weight.data.copy_( state_dict['conv5.0.weight'])
self.conv5[0].bias.data.copy_( state_dict['conv5.0.bias'])
self.infer[0].weight.data.copy_( state_dict['infer.0.weight'])
self.infer[0].bias.data.copy_( state_dict['infer.0.bias'])
self.infer[3].weight.data.copy_( state_dict['infer.3.weight'])
self.infer[3].bias.data.copy_( state_dict['infer.3.bias'])
self.azim.weight.data.copy_( state_dict['azim.0.weight'])
self.azim.bias.data.copy_( state_dict['azim.0.bias'])
self.elev.weight.data.copy_( state_dict['elev.0.weight'])
self.elev.bias.data.copy_( state_dict['elev.0.bias'])
self.tilt.weight.data.copy_( state_dict['tilt.0.weight'])
self.tilt.bias.data.copy_( state_dict['tilt.0.bias'])
def forward(self, x, obj_class):
# generate output
x = self.conv4(x)
x = self.conv5(x)
x = x.view(x.shape[0], -1)
x = self.infer(x)
# mask on class
azim = self.azim(x)
azim = azim.view(-1, 12,360)
azim = azim[torch.arange(x.shape[0]), obj_class, :]
elev = self.elev(x)
elev = elev.view(-1, 12,360)
elev = elev[torch.arange(x.shape[0]), obj_class, :]
tilt = self.tilt(x)
tilt = tilt.view(-1, 12,360)
tilt = tilt[torch.arange(x.shape[0]), obj_class, :]
return azim, elev, tilt
<file_sep>/data/get_csv.sh
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_kp_train.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_kp_valid.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_train.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_train_easy.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_valid.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/pascal3d_valid_easy.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/veh_pascal3d_kp_train.csv
wget http://www-personal.umich.edu/~mbanani/clickhere/csv/veh_pascal3d_kp_valid.csv
<file_sep>/model_weights/get_weights.sh
wget http://www-personal.umich.edu/~mbanani/clickhere/weights/r4cnn.pkl
wget http://www-personal.umich.edu/~mbanani/clickhere/weights/ch_cnn.npy
<file_sep>/models/__init__.py
from .render4cnn import *
from .clickhere_cnn import *
<file_sep>/train.py
import argparse, os, sys, shutil, time
import numpy as np
from IPython import embed
import torch
from util import SoftmaxVPLoss, Paths, get_data_loaders, kp_dict
from models import clickhere_cnn, render4cnn
from util.torch_utils import save_checkpoint
def main(args):
initialization_time = time.time()
print("############# Read in Database ##############")
train_loader, valid_loader = get_data_loaders( dataset = args.dataset,
batch_size = args.batch_size,
num_workers = args.num_workers,
model = args.model)
print("############# Initiate Model ##############")
if args.model == 'chcnn':
assert Paths.render4cnn_weights != None, "Error: Set render4cnn weights path in util/Paths.py."
model = clickhere_cnn(render4cnn(), weights_path = Paths.clickhere_weights)
args.no_keypoint = False
elif args.model == 'r4cnn':
assert Paths.render4cnn_weights != None, "Error: Set render4cnn weights path in util/Paths.py."
model = render4cnn(weights_path = Paths.render4cnn_weights)
args.no_keypoint = True
else:
assert False, "Error: unknown model choice."
# Loss functions
criterion = SoftmaxVPLoss()
# Parameters to train
if args.just_attention and (not args.no_keypoint):
params = list(model.map_linear.parameters()) +list(model.cls_linear.parameters())
params = params + list(model.kp_softmax.parameters()) +list(model.fusion.parameters())
params = params + list(model.azim.parameters()) + list(model.elev.parameters())
params = params + list(model.tilt.parameters())
else:
params = list(model.parameters())
# Optimizer
optimizer = torch.optim.Adam(params, lr = args.lr)
# train/evaluate on GPU
model.cuda()
print("Time to initialize take: ", time.time() - initialization_time)
print("############# Start Training ##############")
total_step = len(train_loader)
for epoch in range(0, args.num_epochs):
if epoch % args.eval_epoch == 0:
eval_step( model = model,
data_loader = valid_loader,
criterion = criterion,
step = epoch * total_step,
datasplit = "valid")
train_step( model = model,
train_loader = train_loader,
criterion = criterion,
optimizer = optimizer,
epoch = epoch,
step = epoch * total_step)
def train_step(model, train_loader, criterion, optimizer, epoch, step):
model.train()
total_step = len(train_loader)
loss_sum = 0.
for i, (images, azim_label, elev_label, tilt_label, obj_class, kp_map, kp_class, key_uid) in enumerate(train_loader):
# Set mini-batch dataset
images = images.cuda()
azim_label = azim_label.cuda()
elev_label = elev_label.cuda()
tilt_label = tilt_label.cuda()
obj_class = obj_class.cuda()
# Forward, Backward and Optimize
model.zero_grad()
if args.no_keypoint:
azim, elev, tilt = model(images, obj_class)
else:
kp_map = kp_map.cuda()
kp_class = kp_class.cuda()
azim, elev, tilt = model(images, kp_map, kp_class, obj_class)
loss_a = criterion(azim, azim_label)
loss_e = criterion(elev, elev_label)
loss_t = criterion(tilt, tilt_label)
loss = loss_a + loss_e + loss_t
loss.backward()
optimizer.step()
loss_sum += loss.item()
# Print log info
if i % args.log_rate == 0 and i > 0:
print("Epoch [%d/%d] Step [%d/%d]: Training Loss = %2.5f" %( epoch, args.num_epochs, i, total_step, loss_sum / (i + 1)))
def eval_step( model, data_loader, criterion, step, datasplit):
model.eval()
total_step = len(data_loader)
epoch_loss_a = 0.
epoch_loss_e = 0.
epoch_loss_t = 0.
epoch_loss = 0.
results_dict = kp_dict()
for i, (images, azim_label, elev_label, tilt_label, obj_class, kp_map, kp_class, key_uid) in enumerate(data_loader):
if i % args.log_rate == 0:
print("Evaluation of %s [%d/%d] " % (datasplit, i, total_step))
# Set mini-batch dataset
images = images.cuda()
azim_label = azim_label.cuda()
elev_label = elev_label.cuda()
tilt_label = tilt_label.cuda()
obj_class = obj_class.cuda()
if args.no_keypoint:
azim, elev, tilt = model(images, obj_class)
else:
kp_map = kp_map.cuda()
kp_class = kp_class.cuda()
azim, elev, tilt = model(images, kp_map, kp_class, obj_class)
# embed()
epoch_loss_a += criterion(azim, azim_label).item()
epoch_loss_e += criterion(elev, elev_label).item()
epoch_loss_t += criterion(tilt, tilt_label).item()
results_dict.update_dict( key_uid,
[azim.data.cpu().numpy(), elev.data.cpu().numpy(), tilt.data.cpu().numpy()],
[azim_label.data.cpu().numpy(), elev_label.data.cpu().numpy(), tilt_label.data.cpu().numpy()])
type_accuracy, type_total, type_geo_dist = results_dict.metrics()
geo_dist_median = [np.median(type_dist) * 180. / np.pi for type_dist in type_geo_dist if type_dist != [] ]
type_accuracy = [ type_accuracy[i] * 100. for i in range(0, len(type_accuracy)) if type_total[i] > 0]
w_acc = np.mean(type_accuracy)
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("Type Acc_pi/6 : ", type_accuracy, " -> ", w_acc, " %")
print("Type Median : ", [ int(1000 * a_type_med) / 1000. for a_type_med in geo_dist_median ], " -> ", int(1000 * np.mean(geo_dist_median)) / 1000., " degrees")
print("Type Loss : ", [epoch_loss_a/total_step, epoch_loss_e/total_step, epoch_loss_t/total_step], " -> ", (epoch_loss_a + epoch_loss_e + epoch_loss_t ) / total_step)
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# logging parameters
parser.add_argument('--eval_epoch', type=int , default=5)
parser.add_argument('--log_rate', type=int, default=10)
parser.add_argument('--num_workers', type=int, default=7)
# training parameters
parser.add_argument('--num_epochs', type=int, default=100)
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--lr', type=float, default=3e-4)
parser.add_argument('--optimizer', type=str,default='sgd')
# experiment details
parser.add_argument('--dataset', type=str, default='pascal')
parser.add_argument('--model', type=str, default='pretrained_clickhere')
parser.add_argument('--experiment_name', type=str, default= 'Test')
parser.add_argument('--just_attention', action="store_true",default=False)
args = parser.parse_args()
main(args)
<file_sep>/datasets/pascal3d.py
import torch
import numpy as np
import time
import pandas
import os
import numpy as np
import torch.utils.data as data
from PIL import Image
from .vp_util import label_to_probs
from torchvision import transforms
import copy
import random
from IPython import embed
class pascal3d(data.Dataset):
"""
Construct a Pascal Dataset.
Inputs:
csv_path path containing instance data
augment boolean for flipping images
"""
def __init__(self, csv_path, dataset_root = None, im_size = 227, transform = None, just_easy = False, num_classes = 12):
start_time = time.time()
# Load instance data from csv-file
im_paths, bbox, obj_cls, vp_labels = self.csv_to_instances(csv_path)
print("csv file length: ", len(im_paths))
# dataset parameters
self.root = dataset_root
self.loader = self.pil_loader
self.im_paths = im_paths
self.bbox = bbox
self.obj_cls = obj_cls
self.vp_labels = vp_labels
self.flip = [False] * len(im_paths)
self.im_size = im_size
self.num_classes = num_classes
self.num_instances = len(self.im_paths)
assert transform != None
self.transform = transform
# Set weights for loss
class_hist = np.histogram(obj_cls, list(range(0, self.num_classes+1)))[0]
mean_class_size = np.mean(class_hist)
self.loss_weights = mean_class_size / class_hist
# Print out dataset stats
print("Dataset loaded in ", time.time() - start_time, " secs.")
print("Dataset size: ", self.num_instances)
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is class_index of the target class.
"""
# Load and transform image
if self.root == None:
im_path = self.im_paths[index]
else:
im_path = os.path.join(self.root, self.im_paths[index])
bbox = self.bbox[index]
obj_cls = self.obj_cls[index]
view = self.vp_labels[index]
flip = self.flip[index]
# Transform labels
azim, elev, tilt = (view + 360.) % 360.
# Load and transform image
img = self.loader(im_path, bbox = bbox, flip = flip)
if self.transform is not None:
img = self.transform(img)
# construct unique key for statistics -- only need to generate imid and year
_bb = str(bbox[0]) + '-' + str(bbox[1]) + '-' + str(bbox[2]) + '-' + str(bbox[3])
key_uid = self.im_paths[index] + '_' + _bb + '_objc' + str(obj_cls) + '_kpc' + str(0)
return img, azim, elev, tilt, obj_cls, -1, -1, key_uid
def __len__(self):
return self.num_instances
"""
Loads images and applies the following transformations
1. convert all images to RGB
2. crop images using bbox (if provided)
3. resize using LANCZOS to rescale_size
4. convert from RGB to BGR
5. (? not done now) convert from HWC to CHW
6. (optional) flip image
TODO: once this works, convert to a relative path, which will matter for
synthetic data dataset class size.
"""
def pil_loader(self, path, bbox = None ,flip = False):
# open path as file to avoid ResourceWarning
# link: (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
with Image.open(f) as img:
img = img.convert('RGB')
# Convert to BGR from RGB
r, g, b = img.split()
img = Image.merge("RGB", (b, g, r))
img = img.crop(box=bbox)
# verify that imresize uses LANCZOS
img = img.resize( (self.im_size, self.im_size), Image.LANCZOS)
# flip image
if flip:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
return img
def csv_to_instances(self, csv_path):
df = pandas.read_csv(csv_path, sep=',')
data = df.values
data_split = np.split(data, [0, 1, 5, 6, 9], axis=1)
del(data_split[0])
image_paths = np.squeeze(data_split[0]).tolist()
bboxes = data_split[1].tolist()
obj_class = np.squeeze(data_split[2]).tolist()
viewpoints = np.array(data_split[3].tolist())
return image_paths, bboxes, obj_class, viewpoints
def augment(self):
self.im_paths = self.im_paths + self.im_paths
self.bbox = self.bbox + self.bbox
self.obj_cls = self.obj_cls + self.obj_cls
self.vp_labels = self.vp_labels + self.vp_labels
self.flip = self.flip + [True] * self.num_instances
assert len(self.flip) == len(self.im_paths)
self.num_instances = len(self.im_paths)
print("Augmented dataset. New size: ", self.num_instances)
def generate_validation(self, ratio = 0.1):
assert ratio > (2.*self.num_classes/float(self.num_instances)) and ratio < 0.5
random.seed(a = 2741998)
valid_class = copy.deepcopy(self)
valid_size = int(ratio * self.num_instances)
train_size = self.num_instances - valid_size
train_instances = list(range(0, self.num_instances))
valid_instances = random.sample(train_instances, valid_size)
train_instances = [x for x in train_instances if x not in valid_instances]
assert train_size == len(train_instances) and valid_size == len(valid_instances)
valid_class.im_paths = [ self.im_paths[i] for i in sorted(valid_instances) ]
valid_class.bbox = [ self.bbox[i] for i in sorted(valid_instances) ]
valid_class.obj_cls = [ self.obj_cls[i] for i in sorted(valid_instances) ]
valid_class.vp_labels = [ self.vp_labels[i] for i in sorted(valid_instances) ]
valid_class.flip = [ self.flip[i] for i in sorted(valid_instances) ]
valid_class.num_instances = valid_size
self.im_paths = [ self.im_paths[i] for i in sorted(train_instances) ]
self.bbox = [ self.bbox[i] for i in sorted(train_instances) ]
self.obj_cls = [ self.obj_cls[i] for i in sorted(train_instances) ]
self.vp_labels = [ self.vp_labels[i] for i in sorted(train_instances) ]
self.flip = [ self.flip[i] for i in sorted(train_instances) ]
self.num_instances = train_size
return valid_class
<file_sep>/README.md
# pytorch-clickhere-cnn
## Introduction
This is a [PyTorch](http://pytorch.org) implementation of [Clickhere CNN](https://github.com/rszeto/click-here-cnn)
and [Render for CNN](https://github.com/shapenet/RenderForCNN).
We currently provide the model, converted weights, dataset classes, and training/evaluation scripts.
This implementation also includes an implementation of the Geometric Structure Aware loss function first mentioned in Render For CNN.
If you have any questions, please email me at <EMAIL>.
## Getting Started
Add the repository to your python path:
export PYTHONPATH=$PYTHONPATH:$(pwd)
Please be aware that I make use of the following packages:
- Python 3.6
- PyTorch 1.1 and Torch Vision 0.2.2
- scipy
- pandas
### Generating the data
Download the [Pascal 3D+ dataset](http://cvgl.stanford.edu/projects/pascal3d.html) (Release 1.1).
Set the path for the Pascal3D directory in util/Paths.py. Finally, run the following command from the repository's root directory.
cd data/
python generate_pascal3d_csv.py
Please note that this will generate the csv files for 3 variants of the dataset: Pascal 3D+ (full), Pascal 3D+ (easy), and Pascal 3D-Vehicles (with keypoints). Those datasets are needed to obtain different sets of results.
Alternatively, you could directly download the csv files by using `data/get_csv.sh`
### Pre-trained Model Weights
We have converted the RenderForCNN and Clickhere model weights from the respective caffe models.
The converted models are available for download by running the script in `model_weights/get_weights.sh`
The converted models achieve comparable performance to the Caffe for the Render For CNN
model, however, there is a larger error observed for Clickhere CNN.
Updated results coming soon.
### Running Inference
After downloading Pascal 3D+ and the pretrained weights, generating the CSV files, and setting the appropriate paths as mentioned above,
you can run inference on the Pascal 3D+ dataset by running one of the following commands (depending on the model):
python train.py --model chcnn --dataset pascalVehKP
python train.py --model r4cnn --dataset pascalEasy
python train.py --model r4cnn --dataset pascal
#### Results
To be updated soon!
The original Render For CNN paper reported the results on the 'easy' subset of Pascal3D, which removes any truncated and occluded images from the datasets. While Click-Here CNN reports results on an augmented version of the dataset where multiple instances may belong to the same object in the image as each image-keypoint pair corresponds to an instance. Below are the results Obtained from each of the runs above.
### Render For CNN paper results:
We evaluate the converted model on Pascal3D-easy as reported in the original Render For CNN paper,
as well as the full Pascal 3D dataset.
It is worth nothing that the converted model actually exceeds the performance reported in Render For CNN.
# #### Accuracy
ataset | plane | bike | boat | bottle| bus | car | chair |d.table| mbike | sofa | train | tv | mean |
|:---------:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| Full | 76.26 | 69.58 | 59.03 | 87.74 | 84.32 | 69.97 | 74.2 | 66.79 | 77.29 | 82.37 | 75.48 | 81.93 | 75.41 |
| Easy | 80.37 | 85.59 | 62.93 | 95.60 | 94.14 | 84.08 | 82.76 | 80.95 | 85.30 | 84.61 | 84.08 | 93.26 | 84.47 |
| Reported | 74 | 83 | 52 | 91 | 91 | 88 | 86 | 73 | 78 | 90 | 86 | 92 | 82 |
#### Median Error
|dataset | plane | bike | boat | bottle| bus | car | chair |d.table| mbike | sofa | train | tv | mean |
|:---------:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
|Full | 11.52 | 15.33 | 19.33 | 8.51 | 5.54 | 9.39 | 13.83 | 12.87 | 14.90 | 13.03 | 8.96 | 13.72 | 12.24 |
|Easy | 10.32 | 11.66 | 17.74 | 6.66 | 4.52 | 6.65 | 11.21 | 9.75 | 13.11 | 9.76 | 5.52 | 11.93 | 9.90 |
|Reported | 15.4 | 14.8 | 25.6 | 9.3 | 3.6 | 6.0 | 9.7 | 10.8 | 16.7 | 9.5 | 6.1 | 12.6 | 11.7 |
### Pascal3D - Vehicles with Keypoints
We evaluated the converted Render For CNN and Click-Here CNN models on Pascal3D-Vehicle.
It should be noted that the results for Click-Here are lower than those achieved by running the author provided Caffe code.
It seems that there is something incorrect with the current reimplementation and/or weight conversion.
We are working on fixing this problem.
#### Accuracy
| | bus | car | m.bike | mean |
|:-------------------------:|:-----:|:-----:|:------:|:-----:|
| Render For CNN | 89.26 | 74.36 | 81.93 | 81.85 |
| Click-Here CNN | 86.91 | 83.25 | 73.83 | 81.33 |
| Click-Here CNN (reported) | 96.8 | 90.2 | 85.2 | 90.7 |
#### Median Error
| | bus | car | m.bike | mean |
|:-------------------------:|:-----:|:-----:|:------:|:-----:|
| Render For CNN | 5.16 | 8.53 | 13.46 | 9.05 |
| Click-Here CNN | 4.01 | 8.18 | 19.71 | 10.63 |
| Click-Here CNN (reported) | 2.63 | 4.98 | 11.4 | 6.35 |
### Pascal3D - Vehicles with Keypoints (Fine-tuned Models)
We fine-tuned both models on the Pascal 3D+ (Vehicles with Keypoints) dataset.
Since we suspect that the problem with the replication of the Click-Here CNN model
is in the attention section, we conducted an experiment where we only fine-tuned
those weights. As reported below, fine-tuning just the attention model achieves the best performance.
| | bus | car | m.bike | mean |
|:-----------------------------:|:-----:|:-----:|:------:|:-----:|
| Render For CNN FT | 93.55 | 83.98 | 87.30 | 88.28 |
| Click-Here CNN FT | 92.97 | 89.84 | 81.25 | 88.02 |
| Click-Here CNN FT-Attention | 94.48 | 90.77 | 84.91 | 90.05 |
| Click-Here CNN (reported) | 96.8 | 90.2 | 85.2 | 90.7 |
#### Median Error
| | bus | car | m.bike | mean |
|:-----------------------------:|:-----:|:-----:|:------:|:-----:|
| Render For CNN FT | 3.04 | 5.83 | 11.95 | 6.94 |
| Click-Here CNN FT | 2.93 | 5.14 | 13.42 | 7.16 |
| Click-Here CNN FT-Attention | 2.88 | 5.24 | 12.10 | 6.74 |
| Click-Here CNN (reported) | 2.63 | 4.98 | 11.4 | 6.35 |
## Training the model
To train the model, simply run `python train.py` with parameter flags as indicated in train.py.
## Citation
This is an implementation of [Clickhere CNN](https://github.come/rszeto/click-here-cnn) and [Render For CNN](https://github.com/shapenet/RenderForCNN), so please cite the respective papers if you use this code in any published work.
## Acknowledgements
We would like to thank <NAME>, <NAME>, and <NAME> for providing their code, and
for their assistance with questions regarding reimplementing their work. We would also
like to acknowledge [Kenta Iwasaki](https://discuss.pytorch.org/u/dranithix/summary) for
his advice with loss function implementation and [<NAME>an](https://github.com/fanq15) for releasing
[caffe_to_torch_to_pytorch](https://github.com/fanq15/caffe_to_torch_to_pytorch).
This work has been partially supported by DARPA W32P4Q-15-C-0070 (subcontract from SoarTech) and funds from the University of Michigan Mobility Transformation Center.
<file_sep>/util/Paths.py
import os
pascal3d_root = '/home/mbanani/datasets/pascal3d'
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
render4cnn_weights = os.path.join(root_dir, 'model_weights/r4cnn.pkl')
ft_render4cnn_weights = os.path.join(root_dir, 'model_weights/ryan_render.npy')
clickhere_weights = os.path.join(root_dir, 'model_weights/ch_cnn.npy')
| e0f7a7c690622faad35c87740226639a55fe485e | [
"Markdown",
"Python",
"Shell"
] | 18 | Python | mbanani/pytorch-clickhere-cnn | f8988287a9e760a6825f2c91cdf8539fc12a4c6e | 8cca777bfe23036184ec1db3aa99c223859b455b |
refs/heads/master | <repo_name>AlexGarcia2/pizzeria<file_sep>/README.md
# _Friday pizza order_
#### _A webpage to take an order of pizza and give the cost back to the customer_
#### By _**<NAME>**_
## Description
_webpage with basic styling and place to choice and order pizza._
## Specs
* _build pizza constructor_
* _make sizeCrust method_
* _made veggieTopping method _
* _made meatTopping method _
* _made totalAmount method _
* _made doc ready function _
* _made .submit event _
* _made .change event _
## Setup/Installation Requirements
* Clone or Download from Github @
* Run index.html
## Known Bugs
_No known bugs as of 11/2/18_
## Support and contact details
_If any issues or bugs are found please contact Alex @ <EMAIL>.
## Technologies Used
_Bootstrap paired with HTML, Javascript, CSS, and Jquery-3.3.1 is how I was able to create a nice looking website along with functional website_
### License
*MIT*
Copyright (c) 2018 **_<NAME>_**
<file_sep>/js/scripts.js
function Pizza (size,meatTopp,veggieTopp,name) {
// debugger;
console.log("pizza")
this.size = size;
this.meatTopp = meatTopp;
this.veggieTopp = veggieTopp;
this.name = name;
this.total = [];
}
Pizza.prototype.sizeCrust = function() {
// debugger;
var sizes = ["large","medium","small"];
var crust = this.size;
if(crust === sizes[0]){
return 15.00;
}else if(crust === sizes[1]){
return 12.00;
}else if (crust === sizes[2]) {
return 10.00;
}
return false;
}
Pizza.prototype.veggieTopping = function() {
// debugger;
console.log("topping");
if (this.veggieTopp === "bellpepper" || this.veggieTopp === "mushrooms" || this.veggieTopp === "onions"){
return 2.00
}
}
Pizza.prototype.meatTopping = function() {
// debugger;
console.log("topping");
if (this.meatTopp === "ham" || this.meatTopp === "pepperoni" || this.meatTopp === "sausage"){
return 3.00;
}
}
Pizza.prototype.totalAmount = function() {
var meat = this.meatTopping();
var veggie = this.veggieTopping();
var crust = this.sizeCrust();
total = (meat + crust + veggie);
this.total.push(total);
console.log(total);
}
// user interface ----------------
$(document).ready(function(){
$("#form").submit(function(event){
// debugger;
$("#crustSize","#topping").change();
event.preventDefault();
var lar = $("#crust").val();
var pepp = $("#meat").val();
var vegg = $("#vegg").val();
var nam = $("#name").val();
var order = new Pizza(lar,pepp,vegg,nam);
order.totalAmount()
var results = order.total;
$("#total").show();
$("#result").val("total is: " + results +".00" + " dollars.");
});
});
// order.sizeCrust();
// order.topping();
// order.totalAmount();
| 338fe6f6ddf3ed58ebceb20455f744d0d35c4a13 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | AlexGarcia2/pizzeria | fe8ce0add15555eb12daf21b11df46554f040d09 | df18917c340da73888120779300973ed5b1b99ae |
refs/heads/master | <repo_name>chriszumberge/SQLiteORM.Net<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Defaults/DefaultSQLiteConfiguration.cs
using UnityEngine;
public class DefaultSQLiteConfiguration : SQLiteConfiguration
{
public override string DatabaseLocation { get { return Application.persistentDataPath; } }
public override LoggingLevel LoggingLevel { get { return LoggingLevel.WARN; } }
public override ISQLiteLogger SQLiteLogger { get { return new UnityConsoleSQLiteLogger(); } }
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/UniqueAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class UniqueAttribute : Attribute { }<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/SQLiteDbContext.cs
using SQLiteDatabase;
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
public abstract class SQLiteDbContext : ScriptableObject, IDisposable
{
public SQLiteDB Database { get { return _database; } }
readonly SQLiteDB _database = SQLiteDB.Instance;
readonly SQLiteConfiguration _config;
public SQLiteDbContext(string databaseName = "MyDatabase.db", SQLiteConfiguration config = null)
{
_config = config ?? new DefaultSQLiteConfiguration();
_database.DBLocation = _config.DatabaseLocation;
_database.DBName = databaseName.EndsWith(".db") ? databaseName : String.Concat(databaseName, ".db");
InitializeDatabase();
}
void ConnectToDatabase(bool resetDatabase = false)
{
_database.ConnectToDefaultDatabase(_database.DBName, resetDatabase);
}
void CreateDatabase(bool forceCreate = true)
{
_database.CreateDatabase(_database.DBName, forceCreate);
}
void InitializeDatabase()
{
LogHelper.Log(LoggingLevel.TRACE, _config, "Initializing Database");
if (_database.Exists)
{
LogHelper.Log(LoggingLevel.TRACE, _config, "Database exists, connecting");
ConnectToDatabase();
}
else
{
LogHelper.Log(LoggingLevel.TRACE, _config, "Database does not exist, creating");
CreateDatabase();
}
SQLiteEventListener.onError += SQLiteEventListener_onError;
RunMigrations();
}
private void SQLiteEventListener_onError(string err)
{
// TODO have it fire an event from this class that user code can handle
LogHelper.Log(LoggingLevel.ERROR, _config, err);
}
void RunMigrations()
{
// TODO if add/drop migrations or incremental
LogHelper.Log(LoggingLevel.TRACE, _config, "Creating and Migrating");
foreach (var connectionField in this.GetType().GetFields())
{
if (connectionField.FieldType.Name.Equals("SQLiteTable`1"))
{
// rename variable for explicitness, now that it represents something else
FieldInfo tableField = connectionField;
// get the generic type argument that the SQLiteTable is using, as that's the type of the table
Type tableFieldGenericType = tableField.FieldType.GetGenericArguments()[0];
LogHelper.Log(LoggingLevel.TRACE, _config, String.Concat("Considering object of type: " + tableFieldGenericType.Name));
// get the name of the field to be the name of the table, unless it has a custom table name attribute, then use that
string tableName = tableField.Name;
var tableNameAttribute = tableFieldGenericType.GetCustomAttributes(typeof(TableNameAttribute), false).FirstOrDefault() as TableNameAttribute;
if (tableNameAttribute != null)
{
// cleanse by replacing all spaces with underscores
// TODO rip out all symbols and other invalid characters
tableName = tableNameAttribute.TableName.Replace(" ", "_");
}
LogHelper.Log(LoggingLevel.TRACE, _config, String.Concat("Mapping object to database table named: " + tableName));
// Create the schema for the new table to be created
DBSchema schema = new DBSchema(tableName);
// Only supporting a single primary key at the moment
bool schemaHasPrimary = false;
foreach (var tableProperty in tableFieldGenericType.GetProperties())
{
if (tableProperty.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0)
{
string columnName = tableProperty.Name;
var fieldNameAttribute = tableProperty.GetCustomAttributes(typeof(FieldNameAttribute), false).FirstOrDefault() as FieldNameAttribute;
if (fieldNameAttribute != null)
{
// cleanse by replacing all spaces with underscores
// TODO rip out all symbols and other invalid characters
columnName = fieldNameAttribute.FieldName.Replace(" ", "_");
}
SQLiteDB.DB_DataType dataType = 0;
int size = 0;
// If it's an int type...
if (tableProperty.PropertyType.Equals(typeof(Int16)) ||
tableProperty.PropertyType.Equals(typeof(Int32)) ||
tableProperty.PropertyType.Equals(typeof(Int64)))
{
dataType = SQLiteDB.DB_DataType.DB_INT;
}
else
{
// if not an int, then store as text unless a size was specified, then store as varchar
var sizeAttribute = tableProperty.GetCustomAttributes(typeof(SizeAttribute), false).FirstOrDefault() as SizeAttribute;
if (sizeAttribute != null)
{
dataType = SQLiteDB.DB_DataType.DB_VARCHAR;
size = sizeAttribute.FieldSize;
}
else
{
dataType = SQLiteDB.DB_DataType.DB_TEXT;
}
}
bool isPrimary = false;
if (tableProperty.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length != 0)
{
if (schemaHasPrimary)
{
// TODO custom exception
throw new Exception("Multiple primary keys are not supported at this time");
}
isPrimary = true;
schemaHasPrimary = true;
}
bool isNotNull = false;
if (tableProperty.GetCustomAttributes(typeof(NotNullAttribute), false).Length != 0)
{
isNotNull = true;
}
bool isUnique = false;
if (tableProperty.GetCustomAttributes(typeof(UniqueAttribute), false).Length != 0 || isPrimary)
{
isUnique = true;
}
schema.AddField(columnName, dataType, size, isNotNull, isPrimary, isUnique);
}
}
if (_database.IsTableExists(schema.TableName))
{
LogHelper.Log(LoggingLevel.TRACE, _config, "The " + schema.TableName + " table already exists.");
// TODO.. migration update?
}
else
{
LogHelper.Log(LoggingLevel.TRACE, _config, "Creating the " + schema.TableName + " table.");
_database.CreateTable(schema);
}
// Set the value of the table back in this calss
Type typeArgument = tableFieldGenericType;
Type genericClass = typeof(SQLiteTable<>);
Type constructedClass = genericClass.MakeGenericType(typeArgument);
tableField.SetValue(this, Activator.CreateInstance(constructedClass, _database, tableName, _config));
}
}
// Depending on type of migration, seed?
}
#region IDisposable Support
public void Dispose()
{
LogHelper.Log(LoggingLevel.TRACE, _config, "Disposing Database and Context");
Database.Dispose();
}
#endregion
#region Unity Lifecycle Support
private void OnApplicationQuit()
{
Dispose();
}
#endregion
}
<file_sep>/README.md
# SQLiteORM.Net
SQLiteORM.Net is a Code First SQLite ORM written for .NET for use in Unity projects. It is inspired by and attempting to emulate both the syntaxes and architectures of EntityFramework, but for SQLite.
## Getting Started
Download the `SQLiteORM.Net.Core.unitypackage` and import it into your project.
You will also need to download the two dependencies, I unfortunately could not package the SQLite Database
code since it's a paid asset available on the [Unity Asset Store](https://assetstore.unity.com/packages/tools/integration/sqlite-database-40375).
I chose SQLite because it's extremely lightweight and most importantly it supports iOS, Android, PC and Mac.
JsonDotNet is **free** and also available on the [Unity Asset Store](https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347).
The `SQLiteORM.Net.unitypackage` includes the JsonDotNet binaries.
#### Dependencies
- [SQLiteDatabase](https://assetstore.unity.com/packages/tools/integration/sqlite-database-40375) - $10
- [JsonDotNet](https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347) - FREE
#### Roadmap
- Error events
- Foreign keys and Navigations Properties
- Migrations
- Change tracking and SaveChanges()/Rollbacks
## Documentation
### Creating a Database
Databases are represented by the `SQLiteDbContext`{:.language-cs} abstract class.
To create your own database simply create a class inheriting from that base class,
```cs
public class ExampleDbContext : SQLiteDBContext {}
```
Then, in your code, simply create a new instance of your `SQLiteDBContext`.
```cs
using (var dbContext = new ExampleDbContext())
{
// Db Code Here using the dbContext variable
}
```
### Defining Models to Store your Data
As a code-first solution, your tables are represented by models.
Simply create a class for the data that you want to store in your database,
```cs
public class User
{
[PrimaryKey]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
```
By default, the name of the class will be the name of the resulting table.
Additionally, the names of all the properties will be the names of all the columsn in that table.
### Adding Tables for your Models to your Database
Tables are represented by the `SQLiteTable<>`{:.language-cs} generic class.
Simply add a public `SQLiteTable`{:.language-cs} property whose generic argument is the type
of the model you want to create a table for,
```cs
public class ExampleDbContext : SQLiteDBContext
{
public SQLiteTable<User> Users;
}
```
### Interacting with Tables in Code
```cs
using (var dbContext = new ExampleDbContext())
{
string id = Guid.NewGuid().ToString();
// Insert new data
bool successful = dbContext.Users.Insert(new User
{
Id = id,
Age = 26,
FirstName = "Christopher",
LastName = "Zumberge"
});
// Retrieve data
IEnumerable<User> users = dbContext.Users.GetItems();
// Update data
// Delete data
}
```
### Foreign Keys and Navigation Properties
Coming soon....
### Configuring your Database and DbContext
For most all configuration changes to the database and dbcontext, you need to create a subclass
of the abstract `SQLiteConfiguration` class.
This will allow you to change all the parameters that the DbContext uses at runtime.
```cs
public class ExampleSQLiteConfiguration : SQLiteConfiguration
{
public override string DatabaseLocation { get { return Application.persistentDataPath; } }
public override LoggingLevel LoggingLevel { get { return LoggingLevel.TRACE; } }
public override ISQLiteLogger SQLiteLogger { get { return new UnityConsoleSQLiteLogger(); } }
}
```
If you only wish to change a few of the parameters, inherit the `DefaultSQLiteConfiguration`
class instead, since all of the abstract fields are already given default values.
```cs
public class ExampleSQLiteConfiguration : DefaultSQLiteConfiguration
{
public override LoggingLevel LoggingLevel { get { return LoggingLevel.TRACE; } }
}
```
#### Specify Database Name
To specifiy the name of your database, simply pass a database name string to the base
constructor of your `SQLiteDBContext` class,
```cs
public class ExampleDbContext : SQLiteDBContext {
public ExampleDbContext() : base("ExampleDatabase.db"){ }
}
```
### Configuring your Data
#### Specifying a Table Name
To create a table for a model that has a different name than the class, use the `[TableName]` attribute,
```cs
[TableName("User")]
public class TestUser
{
// ...
// ...
}
```
This will create a table named "User" instead of "TestUser", as it would do by default.
#### Specifying a Field Name
To create a column in a table that has a different name than the property it maps to, use the `[FieldName]` attribute,
```cs
public class User
{
// ...
[FieldName("UserAge")]
public int Age { get; set; }
// ...
}
```
#### Ignore a Property on your Model
To **not** map a property to a table column, use the `[ColumnIgnore]` attribute,
```cs
public class User
{
// ...
public string FirstName { get; set; }
public string LastName { get; set; }
// ...
[ColumnIgnore]
public string Name => $"{FirstName} {LastName}"
}
```
### Setting Not Null, Primary Key, Unique, Required Flags
All of the above have attributes that you can decorate the intended properties with
```cs
public class User
{
[PrimaryKey]
public string Id { get; set; }
[Unique]
public sting SSN { get; set; }
[NotNull]
public string FirstName { get; set; }
[NotNull]
public string LastName { get; set; }
}
```
### Restricting Data Size
There is a Size Attribute that allows you to specify the size of a field that will be mapped
back to varchar,
```cs
public class User
{
// ...
[Size(16)]
[Unique]
public string IdentificationNumber { get; set; }
// ...
}
```
### Composite Primary Keys
Not yet supported...
### Default Values
Since the ORM is Code-First, provide a default value just by setting the class property
equal to a value.
```cs
public class User
{
// ...
public string FirstName { get; set; } = String.Empty;
// ...
}
```
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/ISQLiteLogger.cs
using System;
public interface ISQLiteLogger
{
void Log(string logMessage);
void Warn(string logMessage);
void Error(string logMessage);
void Fatal(string logMessage);
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/Models/TestData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[TableName("TestDataCustomeTableName")]
public class TestData
{
[PrimaryKey]
public int Id { get; set; }
public bool IsSomething { get; set; }
public TestNestedData NestedData { get; set; }
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/TableNameAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class TableNameAttribute : Attribute
{
public string TableName { get; private set; }
public TableNameAttribute(string name)
{
TableName = name;
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Exceptions/DatabaseDoesNotExistException.cs
using System;
using System.Runtime.Serialization;
public class DatabaseDoesNotExistException : Exception
{
public DatabaseDoesNotExistException()
{
}
public DatabaseDoesNotExistException(string message) : base(message)
{
}
public DatabaseDoesNotExistException(string message, Exception innerException) : base(message, innerException)
{
}
protected DatabaseDoesNotExistException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/DataAccess/ExampleSQLiteDbContext.cs
public class ExampleSQLiteDbContext : SQLiteDbContext {
public ExampleSQLiteDbContext() : base("ExampleDatabase.db", new ExampleSQLiteConfiguration()) { }
public SQLiteTable<TestUser> Users;
public SQLiteTable<TestData> Data;
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Models/LoggingLevel.cs
public enum LoggingLevel
{
TRACE = 1,
LOG = 2,
WARN = 3,
ERROR = 4,
FATAL = 5,
OFF = 10
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/SQLiteConfiguration.cs
/// <summary>
///
/// </summary>
public abstract class SQLiteConfiguration
{
// Loaded event?
public abstract string DatabaseLocation { get; }
// https://msdn.microsoft.com/en-us/library/system.data.entity.dbconfiguration(v=vs.113).aspx
// Set Interceptors
// Set Logs and Log Formatters
public abstract ISQLiteLogger SQLiteLogger { get; }
public abstract LoggingLevel LoggingLevel { get; }
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Helpers/LogHelper.cs
public static class LogHelper {
public static void Log(LoggingLevel level, SQLiteConfiguration config, string message)
{
if (((int)level) >= (int)config.LoggingLevel)
{
switch(level)
{
case LoggingLevel.TRACE:
case LoggingLevel.LOG:
config.SQLiteLogger.Log(message);
break;
case LoggingLevel.WARN:
config.SQLiteLogger.Warn(message);
break;
case LoggingLevel.ERROR:
config.SQLiteLogger.Error(message);
break;
case LoggingLevel.FATAL:
config.SQLiteLogger.Fatal(message);
break;
default:
break;
}
}
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/ColumnIgnoreAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ColumnIgnoreAttribute : Attribute { }<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/UsageExample.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class UsageExample : MonoBehaviour {
// Use this for initialization
void Start () {
using (var dbContext = new ExampleSQLiteDbContext())
{
Debug.Log(dbContext != null);
Debug.Log(dbContext.Data.GetType().FullName);
Debug.Log(dbContext.Users.GetType().FullName);
bool successful = dbContext.Users.Insert(new TestUser
{
Age = 26,
Id = Guid.NewGuid().ToString(),
FirstName = "Christopher",
LastName = "Zumberge"
});
Debug.Log("User insert success? " + successful);
foreach (TestUser user in dbContext.Users.GetItems())
{
Debug.Log(String.Concat(user.Id, " | ", user.Name, " | ", user.Age));
}
TestData newData = new TestData
{
Id = 12,
IsSomething = true,
NestedData = new TestNestedData
{
Something = "One thing",
SomethingElse = 32,
Data = BitConverter.GetBytes(15)
}
};
successful = dbContext.Data.Insert(newData);
Debug.Log("Data insert success? " + successful);
foreach (TestData data in dbContext.Data.GetItems())
{
Debug.Log(String.Concat(data.Id, " | ", data.IsSomething, " | ", data.NestedData.Something, " | ", data.NestedData.SomethingElse, " | ",
String.Join("", data.NestedData.Data.Select(x => x.ToString()).ToArray())));
}
}
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Exceptions/RequiredFieldException.cs
using System;
public class RequiredFieldException : Exception {
public RequiredFieldException(string fieldName) : base(String.Concat("No value was provided for Required field '" + fieldName + "'"))
{
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/Models/TestNestedData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestNestedData {
public string Something { get; set; }
public int SomethingElse { get; set; }
public byte[] Data { get; set; }
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Defaults/UnityConsoleSQLiteLogger.cs
using System;
using UnityEngine;
public class UnityConsoleSQLiteLogger : ISQLiteLogger {
public void Error(string logMessage)
{
Debug.LogError(logMessage);
}
public void Fatal(string logMessage)
{
Debug.LogError(String.Concat("FATAL", Environment.NewLine, logMessage));
}
public void Log(string logMessage)
{
Debug.Log(logMessage);
}
public void Warn(string logMessage)
{
Debug.LogWarning(logMessage);
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/SQLiteTable.cs
using Newtonsoft.Json;
using SQLiteDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
public class SQLiteTable<T> where T : new()
{
readonly SQLiteDB _db;
readonly string _tableIdentifier;
readonly SQLiteConfiguration _config;
readonly System.Reflection.PropertyInfo[] _itemProperties;
readonly System.Reflection.PropertyInfo _primaryKeyProperty;
public SQLiteTable(SQLiteDB db, string tableIdentifier, SQLiteConfiguration config)
{
_db = db;
_tableIdentifier = tableIdentifier;
_config = config;
_itemProperties = typeof(T).GetProperties();
foreach (var property in _itemProperties)
{
if (property.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length != 0)
{
_primaryKeyProperty = property;
break;
}
}
}
public IEnumerable<T> GetItems()
{
return AggregateDbReaderItems(_db.GetAllData(_tableIdentifier));
}
//public T GetItem(string primaryKeyValue)
//{
//}
public IEnumerable<T> Query(string query)
{
return AggregateDbReaderItems(_db.Select(query));
}
//public IEnumerable<T> Query(Expression<Func<T, bool>> queryPredicate)
//{
//}
public bool Insert(T item)
{
bool successful = false;
try
{
List<SQLiteDB.DB_DataPair> dataPairList = new List<SQLiteDB.DB_DataPair>();
SQLiteDB.DB_DataPair data = new SQLiteDB.DB_DataPair();
LogHelper.Log(LoggingLevel.TRACE, _config, "Creating new " + typeof(T).Name);
foreach (var property in _itemProperties)
{
if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0)
{
// If the property is marked as required and is null, throw an exception
if (property.GetCustomAttributes(typeof(RequiredAttribute), false).Length != 0 &&
//!property.PropertyType.IsValueType &&
property.GetValue(item) == null)
{
throw new RequiredFieldException(property.Name);
}
string fieldName = property.Name;
var fieldNameAttribute = property.GetCustomAttributes(typeof(FieldNameAttribute), false).FirstOrDefault() as FieldNameAttribute;
if (fieldNameAttribute != null)
{
// cleanse by replacing all spaces with underscores
// TODO rip out all symbols and other invalid characters
fieldName = fieldNameAttribute.FieldName.Replace(" ", "_");
}
data.fieldName = fieldName;
data.value = ConvertValueToString(item, property);
dataPairList.Add(data);
LogHelper.Log(LoggingLevel.TRACE, _config, "Added {" + data.fieldName + ", " + data.value + "} to object.");
}
}
int changeCount = _db.Insert(_tableIdentifier, dataPairList);
LogHelper.Log(LoggingLevel.LOG, _config, changeCount + " change(s) on insert to " + _tableIdentifier);
if (changeCount > 0)
{
successful = true;
}
}
catch (Exception ex)
{
LogHelper.Log(LoggingLevel.ERROR, _config, ex.ToString());
}
return successful;
}
public bool Update(T item)
{
bool successful = false;
List<SQLiteDB.DB_DataPair> dataPairList = new List<SQLiteDB.DB_DataPair>();
SQLiteDB.DB_DataPair data = new SQLiteDB.DB_DataPair();
SQLiteDB.DB_ConditionPair condition = new SQLiteDB.DB_ConditionPair();
foreach (var property in _itemProperties)
{
// if the property isn't being ignored
if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0)
{
// if isn't primary key
if (property.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length == 0)
{
data.fieldName = property.Name;
data.value = ConvertValueToString(item, property);
dataPairList.Add(data);
}
// else is, it can't be updated but instead used for finding record to update
else
{
condition.fieldName = property.Name;
condition.value = ConvertValueToString(item, property);
condition.condition = SQLiteDB.DB_Condition.EQUAL_TO;
}
}
}
if (_db.Update(_tableIdentifier, dataPairList, condition) > 0)
{
successful = true;
}
return successful;
}
public bool Delete(string primaryKeyValue)
{
bool successful = false;
SQLiteDB.DB_ConditionPair condition = new SQLiteDB.DB_ConditionPair();
condition.fieldName = _primaryKeyProperty.Name;
condition.value = primaryKeyValue;
condition.condition = SQLiteDB.DB_Condition.EQUAL_TO;
if (_db.DeleteRow(_tableIdentifier, condition) > 0)
{
successful = true;
}
return successful;
}
public void Truncate()
{
_db.ClearTable(_tableIdentifier);
}
private static string ConvertValueToString(T item, System.Reflection.PropertyInfo property)
{
string strValue;
if (property.PropertyType.Equals(typeof(double)) ||
property.PropertyType.Equals(typeof(float)) ||
property.PropertyType.Equals(typeof(int)) ||
property.PropertyType.Equals(typeof(long)) ||
property.PropertyType.Equals(typeof(short)) ||
property.PropertyType.Equals(typeof(string)))
{
strValue = property.GetValue(item).ToString();
}
else
{
strValue = JsonConvert.SerializeObject(property.GetValue(item));
}
return strValue;
}
private List<T> AggregateDbReaderItems(DBReader reader)
{
List<T> items = new List<T>();
while (reader != null && reader.Read())
{
T item = new T();
foreach (var property in _itemProperties)
{
// if the property isn't being ignored
if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0)
{
string propertyName = property.Name;
var fieldNameAttribute = property.GetCustomAttributes(typeof(FieldNameAttribute), false).FirstOrDefault() as FieldNameAttribute;
if (fieldNameAttribute != null)
{
// cleanse by replacing all spaces with underscores
// TODO rip out all symbols and other invalid characters
propertyName = fieldNameAttribute.FieldName.Replace(" ", "_");
}
LogHelper.Log(LoggingLevel.TRACE, _config, "Finding key " + propertyName);
if (property.PropertyType.Equals(typeof(double)))
{
property.SetValue(item, reader.GetDoubleValue(propertyName));
}
else if (property.PropertyType.Equals(typeof(float)))
{
property.SetValue(item, reader.GetFloatValue(propertyName));
}
else if (property.PropertyType.Equals(typeof(int)))
{
property.SetValue(item, reader.GetIntValue(propertyName));
}
else if (property.PropertyType.Equals(typeof(long)))
{
property.SetValue(item, reader.GetLongValue(propertyName));
}
else if (property.PropertyType.Equals(typeof(short)))
{
property.SetValue(item, reader.GetShortValue(propertyName));
}
else if (property.PropertyType.Equals(typeof(string)))
{
property.SetValue(item, reader.GetStringValue(propertyName));
}
else
{
// was serialized
object deserializedValue = JsonConvert.DeserializeObject(reader.GetStringValue(propertyName), property.PropertyType);
property.SetValue(item, deserializedValue);
}
}
}
items.Add(item);
}
return items;
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/Models/TestUser.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestUser {
[PrimaryKey]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[FieldName("User Age")]
public int Age { get; set; }
[ColumnIgnore]
public string Name
{
get { return string.Concat(FirstName, " ", LastName); }
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Helpers/Extensions.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public static class Extensions
{
public static object GetValue(this PropertyInfo property, object obj)
{
return property.GetValue(obj, null);
}
public static void SetValue(this PropertyInfo property, object obj, object value)
{
property.SetValue(obj, value, null);
}
public static object GetDefault(this Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Example/DataAccess/ExampleSQLiteConfiguration.cs
using UnityEngine;
public class ExampleSQLiteConfiguration : SQLiteConfiguration
{
public override string DatabaseLocation { get { return Application.persistentDataPath; } }
public override LoggingLevel LoggingLevel { get { return LoggingLevel.TRACE; } }
public override ISQLiteLogger SQLiteLogger { get { return new UnityConsoleSQLiteLogger(); } }
}
public class PickySQLiteConfiguration : DefaultSQLiteConfiguration
{
public override LoggingLevel LoggingLevel { get { return LoggingLevel.TRACE; } }
}<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/FieldNameAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class FieldNameAttribute : Attribute
{
public string FieldName { get; private set; }
public FieldNameAttribute(string name)
{
FieldName = name;
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/NotNullAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class NotNullAttribute : Attribute { }
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/SizeAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SizeAttribute : Attribute
{
public int FieldSize { get; private set; }
public SizeAttribute(int size)
{
FieldSize = size;
}
}
<file_sep>/SQLiteORM.Net/Assets/SQLiteORM.Net/Source/Attributes/PrimaryKeyAttribute.cs
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class PrimaryKeyAttribute : Attribute { } | 615cbdd310ee3db3aea58b784522bd3a806e1fd3 | [
"Markdown",
"C#"
] | 25 | C# | chriszumberge/SQLiteORM.Net | a3d519a64528c438b97d006931ff8a0632a7aa05 | 6d69587641a69e7f835f5286f25448e02b9f5e6d |
refs/heads/main | <repo_name>duttahritwik/Cpp_BODMAS_Calculator<file_sep>/README.md
# Cpp_BODMAS_Calculator
This is a BODMAS Calculator written in C++ using the stack data structure.
Firstly, an expression is taken as input from the user and it is checked for validity. If the expression is invalid, the user will be prompted to input again.
If the input expression is mathematically correct, then this expression is converted to the postfix notation, also known as the Reverse Polish Notation, using stack data structure.
Following this, the postfix expression is evaluated using stacks again.
<file_sep>/A Refined Calculator.cpp
#include<iostream>
#include<cmath>
#include<string.h>
#include<stdio.h>
using namespace std;
class Stack
{
char symbols[300];
float number[300];
int top; int top2;
public:
Stack(){top=-1; top2=-1;}
void push(char c){symbols[++top]=c;}
void pop(){top--;}
void pushNum(float x){number[++top2]=x;}
void popNum(){top2--;}
int returnNumberOfElements(){return (top+1);}
char returnTopElement(){return symbols[top];}
float returnTopNum(){return number[top2];}
float returnSecondNum(){return number[(top2-1)];}
};
class bracket
{
char s[200];
int top;
public:
bracket(){top=-1;}
void push(char c){ s[++top]=c;}
void pop(){top--;}
char returnTopCharacter(){return s[top];}
int checkForEmptyStack()
{
if(top==-1)
return 1;
else
return 0;
}
};
int checkForPrecedence(char encounter, char topOfStack) /* returning 1 means encountered operator has higher precedence
than operator currently on top of stack*/
/// returning 2 means operator precedence is equal,0 means lesser
{
int valueToReturn;
switch(encounter)
{
case '^':{
if(topOfStack=='^')
valueToReturn=2;
else
valueToReturn=1;
break;
}
case '+':
{
if(topOfStack=='+'||topOfStack=='-')
valueToReturn=2;
else
valueToReturn=0;
break;
}
case '-':
{
if(topOfStack=='+'||topOfStack=='-')
valueToReturn=2;
else
valueToReturn=0;
break;
}
case '*':
{
if(topOfStack=='+' || topOfStack=='-')
valueToReturn=1;
else
if(topOfStack=='*'||topOfStack=='/')
valueToReturn=2;
else
valueToReturn=0;
break;
}
case '/':
{
if(topOfStack=='+' || topOfStack=='-')
valueToReturn=1;
else
if(topOfStack=='*'||topOfStack=='/')
valueToReturn=2;
else
valueToReturn=0;
break;
}
}
return valueToReturn;
}
void convertAndEvaluate(char s[])
{
char postfix[300]={'\0'}; int c=0;
Stack obj;
int length=strlen(s);
for(int x=0;x<length;x++)
{
if(isdigit(s[x]))
postfix[c++]=s[x];
if(s[x]=='.')
postfix[c++]=s[x];
if(s[x]=='+'||s[x]=='-'||s[x]=='*'||s[x]=='/'||s[x]=='^')
{
postfix[c++]=' ';
if(obj.returnNumberOfElements()==0 || checkForPrecedence(s[x],obj.returnTopElement())==1
|| obj.returnTopElement()=='(')
obj.push(s[x]);
else
{
while(checkForPrecedence(s[x],obj.returnTopElement())==0 || checkForPrecedence(s[x],obj.returnTopElement())==2)
{
postfix[c++]=obj.returnTopElement();
postfix[c++]=' ';
obj.pop();
if(obj.returnNumberOfElements()==0 || obj.returnTopElement()=='(')
break;
}
obj.push(s[x]);
}
}
if(s[x]=='(')
obj.push(s[x]);
if(s[x]==')')
{
postfix[c++]=' ';
while(obj.returnTopElement()!='(')
{
postfix[c++]=obj.returnTopElement();
obj.pop();
}
obj.pop();
}
}
postfix[c++]=' ';
while(obj.returnNumberOfElements()!=0)
{
postfix[c++]=obj.returnTopElement();
postfix[c++]=' ';
obj.pop();
}
for(int x=0;x<c;)
{
if(isdigit(postfix[x]))
{
int checkForDecimal=0,checkIndex=x;
while(postfix[checkIndex]!=' ')
{
checkIndex++;
if(postfix[checkIndex]=='.')
{
checkForDecimal++;
break;
}
}
if(checkForDecimal==1)
{
int index=x,numberOfDigits=0,numberOfDigitsAfterDecimal=0;
while(postfix[index]!='.')
{
numberOfDigits++; index++;
}
double answer=0; int value=numberOfDigits-1;
for(int var=x;var<index;var++)
{
answer+=(postfix[var]-48)*pow(10,value);
value--;
}
int decimal=index+1;
while(postfix[index]!=' ')
{
numberOfDigitsAfterDecimal++; index++;
}
int bunty=numberOfDigitsAfterDecimal-1;
for(int var2=index-1;var2>=decimal;var2--)
{
answer+=(postfix[var2]-48)*pow(10,-bunty);
bunty--;
}
obj.pushNum(answer);
x=index+1;
}
else
{
int index=x,numberOfDigits=0;
while(postfix[index]!=' ')
{
numberOfDigits++; index++;
}
double answer=0; int value=numberOfDigits-1;
for(int var=x;var<index;var++)
{
answer+=(postfix[var]-48)*pow(10,value);
value--;
}
obj.pushNum(answer);
x=index+1;
}
}
else
{
switch(postfix[x])
{
case '+':
{
double answer=obj.returnTopNum()+obj.returnSecondNum();
obj.popNum(); obj.popNum();
obj.pushNum(answer); x+=2;
break;
}
case '-':
{
double answer=-obj.returnTopNum()+obj.returnSecondNum();
obj.popNum(); obj.popNum();
obj.pushNum(answer); x+=2;
break;
}
case '*':
{
double answer=obj.returnTopNum()*obj.returnSecondNum();
obj.popNum(); obj.popNum();
obj.pushNum(answer); x+=2;
break;
}
case '/':
{
double answer=obj.returnSecondNum()/obj.returnTopNum();
obj.popNum(); obj.popNum();
obj.pushNum(answer); x+=2;
break;
}
case '^':
{
double answer=pow(obj.returnSecondNum(),obj.returnTopNum());
obj.popNum(); obj.popNum();
obj.pushNum(answer); x+=2;
break;
}
}
}
}
cout<<obj.returnTopNum();
}
int main()
{
char infix[200]; bracket obj;
cout<<"Input the infix expression?"; gets(infix);
int length=strlen(infix); int check=0;
for(int x=0;x<length;x++)
{
if(infix[0]==')')
{
check++; goto a;
}
if(infix[x]=='(')
obj.push(infix[x]);
if(infix[x]==')')
{
if(obj.checkForEmptyStack()==1
|| obj.returnTopCharacter()!='('&& infix[x]==')')
{
check++; goto a;
}
else
obj.pop();
}
}
if(obj.checkForEmptyStack()!=1)
check++;
a:
if(check==1)
cout<<"Invalid input. Clear expression and input again\n";
else
convertAndEvaluate(infix); /// SAMPLE INPUT 12.21*71221^2-212.9212/218-(23^3.32)+88.21/2121-10^5.43
return 0;
}
| d12d9107aa5e679882d82141383728f65d5adb95 | [
"Markdown",
"C++"
] | 2 | Markdown | duttahritwik/Cpp_BODMAS_Calculator | fa4e13beda2b5e0b314ccf57056dd6b754723c05 | 97730f08f05af47598f615161f7c30f3631aab5b |
refs/heads/main | <file_sep>const MdtToken = artifacts.require('MdtToken');
const StakePool = artifacts.require('StakePool');
module.exports = async function(deployer, network, accounts) {
await deployer.deploy(MdtToken)
const mdtToken = await MdtToken.deployed()
await deployer.deploy(StakePool, mdtToken.address)
const stakePool = await StakePool.deployed()
await mdtToken.transfer(accounts[1], '10000000000000000000000')
await mdtToken.transfer(accounts[2], '10000000000000000000000')
await mdtToken.transfer(accounts[3], '30000000000000000000000')
}<file_sep>const MdtToken = artifacts.require('MdtToken');
const StakePool = artifacts.require('StakePool');
require('chai')
.use(require('chai-as-promised'))
.should()
function tokens(n) {
return web3.utils.toWei(n, 'ether');
}
contract('StakePool', (accounts) =>{
let mdtToken, stakePool
before(async () =>{
mdtToken = await MdtToken.new()
stakePool = await StakePool.new(mdtToken.address)
await mdtToken.transfer(accounts[1], tokens('10000'), { from : accounts[0]} )
await mdtToken.transfer(accounts[2], tokens('10000'), { from : accounts[0]} )
await mdtToken.transfer(accounts[3], tokens('30000'), { from : accounts[0]} )
})
describe('MDT Token Deployement', async ()=> {
it('has a name', async () =>{
//let mdtToken = await MdtToken.new()
const name = await mdtToken.name()
assert.equal(name, "MindDeft Token")
})
it('account 0 has 9950000 tokens', async () =>{
//let mdtToken = await MdtToken.new()
const bal = await mdtToken.balanceOf(accounts[0])
assert.equal(bal.toString(), tokens('9950000'))
})
it('account 1 has 10000 tokens', async () =>{
//let mdtToken = await MdtToken.new()
const bal = await mdtToken.balanceOf(accounts[1])
assert.equal(bal.toString(), tokens('10000'))
})
it('account 2 has 10000 tokens', async () =>{
//let mdtToken = await MdtToken.new()
const bal = await mdtToken.balanceOf(accounts[2])
assert.equal(bal.toString(), tokens('10000'))
})
it('account 3 has 30000 tokens', async () =>{
//let mdtToken = await MdtToken.new()
const bal = await mdtToken.balanceOf(accounts[3])
assert.equal(bal.toString(), tokens('30000'))
})
})
describe('Stake Pool Deployement', async ()=> {
it('has a name', async () =>{
//let mdtToken = await MdtToken.new()
const name = await stakePool.name()
assert.equal(name, "Stake Pool System")
})
})
describe('Staking and Farming Operations', async() =>{
it('stakes MDT tokens',async() =>{
let result = await mdtToken.balanceOf(accounts[1])
assert.equal(result.toString(), tokens('10000'), 'Accounts[1] balance is correct before staking')
await mdtToken.approve(stakePool.address, tokens('10000'), {from : accounts[1]})
await stakePool.stakeTokens(tokens('10000'), {from : accounts[1]})
result = await mdtToken.balanceOf(accounts[1])
assert.equal(result.toString(), tokens('0'), 'Accounts[1] balance is correct after staking')
result = await mdtToken.balanceOf(stakePool.address)
assert.equal(result.toString(), tokens('10000'), 'StakePool address balance is correct after staking')
result = await stakePool.stakingBalance(accounts[1])
assert.equal(result.toString(), tokens('10000'), 'Accounts[1] staking balance in Stake Pool is correct after staking')
result = await stakePool.isStaking(accounts[1])
assert.equal(result.toString(), 'true', 'Accounts[1] is staking')
result = await stakePool.hasStaked(accounts[1])
assert.equal(result.toString(), 'true', 'Accounts[1] is in staking history')
})
it('gets balance', async() => {
result = await stakePool.getBal(accounts[1])
assert.equal(result.toString(), tokens('0'), 'Accounts[1] balance is correct after staking')
})
})
}) | 79779b530a228ac633c04d9cccdeba305344bc47 | [
"JavaScript"
] | 2 | JavaScript | Yogisam72/Stake-DeFi-System | 0bc9306140f6790fc626e0c4957aa8e89ad03135 | 7a934363c78adc6c64959be32fd3dc4acfa01eef |
refs/heads/master | <repo_name>nikhil-tayal/AdiNotes<file_sep>/src/main/java/com/backend/model/PostRequest.java
package com.backend.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class PostRequest {
public String authorName;
public String noteBody;
public String noteTitle;
public String CreatedDate;
public String lastEditedOn;
}
<file_sep>/src/main/java/com/backend/services/NotesService.java
package com.backend.services;
import com.backend.model.PostRequest;
public interface NotesService {
public int addNotes(PostRequest postRequest);
}
| b2125b955a03f0d4f59932178dd1e5d255a1ff89 | [
"Java"
] | 2 | Java | nikhil-tayal/AdiNotes | 19c32c9023f73eb4f48f9524ba43adeb20873d61 | 2f450fc33ed1f173b68343c95c545dced093331b |
refs/heads/master | <repo_name>zannujulius/ecommerce-api<file_sep>/controller/order.js
const User = require("../models/user");
const Product = require("../models/products");
const data = {
item: [
{
productName: "Air jordan XR3",
productId: "614b23ef83b4b5b779da6348",
quantity: 2,
price: 750.32,
total: 1500.64,
},
{
productName: "iphone 12 pro max",
productId: "614b259f83b4b5b779da634d",
quantity: 4,
price: 430.41,
total: 1721.64,
},
],
total: 6,
};
let order = [];
exports.postOrders = (req, res) => {
data.item.forEach((e) => {
Product.findById(e.productId)
.then((result) => {
let id = String(result._id);
if (e.productId !== id) {
return res.json({
error: "product doesnt exist",
});
} else {
if (e.price !== result.originalPrice) {
return res.json({
error: `${e.productName}, has a wring price`,
});
} else {
order.push(e);
console.log(order);
return res.send({
message: "Added to order successfully",
});
}
}
})
.catch((err) => {
console.log(err);
});
});
};
exports.getOrders = (req, res) => {
console.log(req.body);
};
<file_sep>/middleware/auth.js
const jwt = require("jsonwebtoken");
module.exports = auth = (req, res, next) => {
// taking the token from the request header
const token = req.header("X-Auth-token");
// if the request header doesnt have a token user cant access resource
if (!token) return res.status(401).send({ error: "Access denied" });
try {
const verified = jwt.verify(token, process.env.jwtSecret);
req.user = verified;
next();
} catch (error) {
res.status(400).send({ error: "Not authorized to access the resource" });
}
};
<file_sep>/routes/index.js
const express = require("express");
const router = express.Router();
const Product = require("../models/products");
const User = require("../models/user");
const Cart = require("../models/cart");
// Get all products
router.get("/", async (req, res) => {
try {
const products = await Product.find().populate("userId");
// console.log(products);
res.json({
message: products,
});
} catch (error) {
res.send({
error: "An occured",
});
}
});
//Get a particular product
router.get("/product-details/:id", (req, res) => {
const id = req.params.id;
Product.findById(id)
.then((product) => {
// console.log(product);
res.json({
message: product,
});
})
.catch((err) => {
console.log(err);
});
});
module.exports = router;
<file_sep>/app.js
const express = require("express");
const app = express();
const port = process.env.PORT || 8000;
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const User = require("./models/user");
app.use(cors());
app.use(express.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type,Accept,X-Auth-token,X-Username"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
app.use((req, res, next) => {
if (!req.get("X-Username")) {
return next();
}
const id = req.get("X-Username");
User.findById(id)
.then((user) => {
req.user = user;
next();
})
.catch((err) => {
console.log(err);
});
});
const authRoutes = require("./routes/auth");
const indexRoutes = require("./routes/index");
const adminRoutes = require("./routes/admin");
const orderRoutes = require("./routes/order");
app.use("/auth", authRoutes);
app.use(indexRoutes);
app.use("/admin", adminRoutes);
app.use(orderRoutes);
app.get("*", (req, res) => {
res.json({
message: `Can't find that`,
});
});
mongoose
.connect(process.env.mongodbURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((res) => {
console.log("Mongoose started ");
app.listen(port, () => {
console.log(`Server started on ${port}`);
});
})
.catch((err) => {
console.log(err);
});
<file_sep>/controller/auth.js
const User = require("../models/user");
require("dotenv").config();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
exports.getSignup = (req, res) => {
res.send("login route");
};
exports.postSignup = async (req, res) => {
const { email, phonenumber, name, password, role } = req.body;
// validation
if (!email.includes("@") || !email.includes(".")) {
return res.json({
error: "Please enter a valid email",
});
} else if (name == "") {
return res.json({
error: `Name can't be empty`,
});
} else if (password == "" || password.length < 4) {
return res.json({
error: "Please a valid password",
});
}
// checking if user exist
const userData = await User.findOne({ email: email });
// if email already exist
if (userData) {
return res.json({
error: "The email has been taken by another user ",
});
}
// hashing password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const user = new User({
name: name,
password: <PASSWORD>,
email: email,
phonenumber: phonenumber,
role: role,
});
user
.save()
.then((user) => {
jwt
.sign({ id: user._id }, process.env.jwtSecret, { expiresIn: "1d" })
.then((result) => {
res.json({
token,
user: user,
});
})
.catch((err) => console.log(err));
})
.catch((err) => {
res.json(err);
});
};
exports.getLogin = (req, res) => {
res.send("login route");
};
exports.postLogin = async (req, res) => {
const data = req.body;
console.log(data);
try {
// validation
if (!data.email || !data.password)
return res.jjson({ error: "both values are required" });
// cheeck if email exist
const userData = await User.findOne({ email: data.email });
if (!userData) {
return res.json({
error: `Invalid email Try again`,
});
}
// comparing password
const validatePassword = await bcrypt.compare(
data.password,
userData.password
);
if (!validatePassword) return res.send("Incorrect password");
const token = jwt.sign({ _id: userData._id }, process.env.jwtSecret, {
expiresIn: "1d",
});
if (!token) {
return res.send({
error: "got token error",
});
}
// set the response header
res.setHeader("X-Auth-token", token);
res.setHeader("X-Username", userData._id);
res.json({
message: "logged in success",
token: token,
user: userData.name.split(" ")[0],
});
} catch (error) {
res.send("An error occured");
}
};
<file_sep>/routes/auth.js
const express = require("express");
const router = express.Router();
const User = require("../models/user");
const {
getSignup,
postSignup,
getLogin,
postLogin,
} = require("../controller/auth");
require("dotenv").config();
// Get sign up
router.get("/signup", getSignup);
// Post sign up
router.post("/signup", postSignup);
// login
router.get("/login", getLogin);
// post
router.post("/login", postLogin);
module.exports = router;
<file_sep>/routes/order.js
const express = require("express");
const router = express.Router();
const Product = require("../models/products");
const { postOrders, getOrders } = require("../controller/order");
router.get("/orders", getOrders);
router.post("/orders", postOrders);
module.exports = router;
<file_sep>/routes/admin.js
const express = require("express");
const { get } = require("mongoose");
const router = express.Router();
const authRoutes = require("../middleware/auth");
const { populate } = require("../models/products");
const Product = require("../models/products");
const User = require("../models/user");
router.get("/", authRoutes, (req, res) => {
// res.send(req.user._id);
res.send("Admin route");
});
// add a product
router.post("/addproducts", authRoutes, async (req, res) => {
const {
title,
imagePath,
description,
originalPrice,
newPrice,
discount,
slideImage,
} = req.body;
console.log(req.user, "admin.js");
const product = new Product({
title: title,
imagePath: imagePath,
description: description,
originalPrice: originalPrice,
newPrice: newPrice,
discount: discount,
slideImage: slideImage,
userId: req.user._id,
});
product
.save()
.then((result) => {
res.json({ message: "Product added successfully" });
})
.catch((err) => {
console.log(err);
});
});
// get Edit
router.get("/edit-product/:id", (req, res) => {
const id = req.params.id;
Product.findById(id)
.then((product) => {
res.json({
message: product,
});
})
.catch((err) => {
console.log(err);
});
});
// post Edit products
router.post("/edit-product/:id", (req, res) => {
const {
title,
imagePath,
slideImage,
description,
price,
originalPrice,
newPrice,
} = req.body;
const id = req.params.id;
Product.findById(id)
.then((data) => {
(data.title = title),
(data.imagePath = imagePath),
(data.slideImage = slideImage),
(data.description = description),
(data.newPrice = newPrice),
(data.price = price),
(data.price = originalPrice);
return data
.save()
.then((product) => {
res.json({
message: "Product updated successfully",
});
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
});
// post detele product
router.delete("/edit-product/:id", async (req, res) => {
const id = req.params.id;
Product.findOneAndDelete({ _id: id })
.then((result) => {
res.json({
message: "Product deleted successfully",
});
res.redirect("/");
})
.catch((err) => {
console.log(err);
});
});
module.exports = router;
| f32134c8229a1f786cf07284575bed939efd5bee | [
"JavaScript"
] | 8 | JavaScript | zannujulius/ecommerce-api | b5099f444ab2a56995294f751686b67ccc1dae97 | 6f8281da89f5629d4e6496bed2db25b826089a27 |
refs/heads/master | <repo_name>zed-shawn/imagehandling<file_sep>/App.js
import React, { useState, useEffect } from "react";
import { Button, Image, View, Platform, Text } from "react-native";
import * as ImagePicker from "expo-image-picker";
import * as FaceDetector from "expo-face-detector";
import {} from "cloudinary-react";
const url = "https://api.cloudinary.com/v1_1/fsduhag8/image/upload";
export default function App() {
const [image, setImage] = useState(null);
const [result, setResult] = useState();
// const [faces, setFaces] = useState();
useEffect(() => {
(async () => {
if (Platform.OS !== "web") {
const {
status,
} = await ImagePicker.requestCameraRollPermissionsAsync();
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
//console.log(result);
const faceDetect = await detectFaces(result.uri);
//console.log("faceDetect", faceDetect);
const numFaces = faceDetect.faces.length;
if (numFaces === 1) {
dimCheck(faceDetect);
} else if (numFaces === 0) {
setResult(
"We're having trouble detecting a face. Please try another picture or different lighting :("
);
} else if (numFaces > 1) {
setResult("Bummer! More than one faces found. Please try again :(");
}
// setFaces(numFaces);
if (!result.cancelled) {
setImage(result.uri);
}
};
const detectFaces = async (imageUri) => {
const options = { mode: FaceDetector.Constants.Mode.fast };
return await FaceDetector.detectFacesAsync(imageUri, options);
};
const dimCheck = (resultObj) => {
// console.log("resultObj",resultObj);
const picWidth = resultObj.image.width;
const picHeight = resultObj.image.height;
const imgArea = picHeight * picWidth;
const faceWidth = resultObj.faces[0].bounds.size.width;
const faceHeight = resultObj.faces[0].bounds.size.height;
const faceArea = faceWidth * faceHeight;
const percentFace = faceArea / imgArea;
console.log(percentFace);
if (percentFace < 0.1) {
setResult(
"The face seems small, please retry by zooming in or try another pic :)"
);
} else if (percentFace >= 0.1 && percentFace <= 1) {
setResult("C'est parfait!! :D");
uploadHandler(resultObj.image.uri);
} else if (percentFace > 1) {
setResult("Something's not right. Please try again or another pic :/");
}
};
const uploadHandler = (file) => {
console.log("Upload handler called");
const fileData = { uri: file, type: "jpg" };
const formData = new FormData();
formData.append("file", fileData);
formData.append("upload_preset", "trialpic");
console.log("formData", formData);
fetch("https://api.cloudinary.com/v1_1/fsduhag8/image/upload", {
method: "POST",
body: formData,
})
.then((response) => {
jresp = JSON.stringify(response);
console.log("Upload response", jresp);
})
.catch((err) => {
console.log(err);
});
};
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
<Text>{result}</Text>
</View>
);
}
| e44484dcb83182ed2e9a6e600135ecd7d1e724dd | [
"JavaScript"
] | 1 | JavaScript | zed-shawn/imagehandling | fb56cb69d612052aa05dffc5b853be889b6b58dc | 0558f8704d9996ccd0a9d8151420c0b78f3b7a5c |
refs/heads/master | <repo_name>EliteGuzhva/Parser<file_sep>/Parser/ViewController.swift
//
// ViewController.swift
// Parser
//
// Created by <NAME> on 05/05/2017.
// Copyright © 2017 EliteGuzhva. All rights reserved.
//
import UIKit
import Kanna
import Alamofire
import SwiftyJSON
var offers: [String] = []
var imgs: [String] = []
let id = "-146381535"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let table = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
table.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
table.delegate = self
table.dataSource = self
table.register(TableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(table)
self.scrapeOffers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrapeOffers() -> Void {
Alamofire.request("https://api.vk.com/method/wall.get?&owner_id=\(id)&count=20").responseJSON { response in
let jsondata = JSON(data:response.data!)
let array = jsondata["response"].array
if (array?.count) != nil {
for i in 1..<array!.count{
var offer: String?
var img: String?
offer = jsondata["response"][i]["text"].string
offer = offer?.replacingOccurrences(of: "<br>", with: "\n")
img = jsondata["response"][i]["attachment"]["photo"]["src_xbig"].string
if (offer != nil && img != nil && offer != "") {
print(offer!)
print("")
offers.append(offer!)
imgs.append(img!)
}
}
OperationQueue.main.addOperation({()-> Void in
self.table.reloadData()
})
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 430
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return offers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.label.text = offers[indexPath.row]
cell.label.numberOfLines = 20
cell.label.font = UIFont.systemFont(ofSize: 12)
cell.label.frame = CGRect(x: 15, y: 15, width: self.view.frame.width - 30, height: 200)
cell.img.sd_setImage(with: URL(string : imgs[indexPath.row]))
cell.img.frame = CGRect(x: 15, y: cell.label.frame.maxY, width: self.view.frame.width - 30, height: 200)
cell.img.contentMode = .scaleAspectFit
return cell
}
}
| 32d7eefadf53d1db8a9b59d285c320def906b7c9 | [
"Swift"
] | 1 | Swift | EliteGuzhva/Parser | ef5b334de465b2be79200641307d3692ded4e87a | d09a1cc79d1f6ba5dac3c6e9e7a1ae5e8048eb5d |
refs/heads/main | <repo_name>wollllll/jquery_template<file_sep>/Readme.md
## 概要
jQueryを書くときのテンプレート。
webpack等を使って複数のjsファイルを一つのファイルにバンドルし、そのバンドルしたjsファイルを複数のページが参照しているときのみ使う、俺の書き方。
<file_sep>/main.js
const sample = {
/**
* 各ページの外枠のタグにページを表すidを振る
*/
page: $('#page-sample'),
/**
* 取得したページからfindしてdomを取得することでスコープをページ単位で区切る
*/
getDom(selector) {
return sample.page.find($(selector));
},
/**
* オブジェクト内で関数等またいでデータを扱う場合はここで定義
*/
data: {
message: '',
count: 0
},
/**
* 関数置くところ
*/
modules: {
setMessage() {
sample.data.message = 'hey';
},
showMessage() {
console.log(sample.data.message);
},
getText() {
const text = sample.getDom('#text').text();
console.log(text);
},
showAlert() {
alert('clicked');
},
/**
* 用途に合わせて階層深くしたり
*/
counter: {
increment() {
sample.data.count++;
sample.getDom('#count').val(sample.data.count);
},
getNowCount() {
alert(sample.data.count);
}
}
},
/**
* 定義した関数を実行
*/
init() {
sample.modules.setMessage();
sample.modules.showMessage();
sample.modules.getText();
sample.getDom('#alert').on('click', sample.modules.showAlert);
sample.getDom('#increment').on('click', sample.modules.counter.increment);
sample.getDom('#now-count').on('click', sample.modules.counter.getNowCount);
}
}
/**
* initを実行
*/
$(() => sample.init());
| 01e4aa4c323273d1f1cfbf243d3126315cd8a5bc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | wollllll/jquery_template | 37f425313e4cbb71e15d71f642ee07d5ca23a218 | b2e531a2cc7bbbb1dffc65558314acda09b94c5b |
refs/heads/master | <repo_name>MatiasDevop/restclient-net5-blazor<file_sep>/MockServiceUI/MockUI/Models/MockResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockUI.Models
{
public class MockResponse
{
public Guid Id { get; set; }
public string EndPoint { get; set; }
public int HttpMethod { get; set; }
public int ResponseCode { get; set; }
public string ResponseBody { get; set; }
}
}
<file_sep>/MockServiceApi/MockServiceApi/Data/DbInitializer.cs
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Data
{
public class DbInitializer
{
public static void Initialize(DataContext context)
{
//add mock response account for test
Guid mockId = new Guid("c193f46c-ac49-4614-a358-9660e25e6f73");
if (!context.MockResponses.Any())
{
var mock = new MockResponse()
{
EndPoint = "https://jsonplaceholder.typicode.com/users",
HttpMethod = (HttpVerb)1,
ResponseBody = "Hellow World",
ResponseCode = 200
};
var mock2 = new MockResponse()
{
EndPoint = "https://jsonplaceholder.typicode.com",
HttpMethod = (HttpVerb)3,
ResponseBody = "Not found",
ResponseCode = 400
};
context.MockResponses.Add(mock);
context.MockResponses.Add(mock2);
context.SaveChanges();
}
}
}
}
<file_sep>/readme.txt
/*******Intructions**************/
1 open api project
2 change jsonsetting to you local sqlserver
3 run :update-databse
4 rebuild just in case
5 open blazor proyect and testing all.<file_sep>/MockServiceApi/MockServiceApi/Repositories/MockResponseRepository.cs
using MockServiceApi.Data;
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Repositories
{
public class MockResponseRepository : IMockResponseRepository
{
private readonly DataContext _context;
public MockResponseRepository(DataContext context)
{
_context = context;
}
public async Task CreateItemAsync(MockResponse item)
{
await _context.MockResponses.AddAsync(item);
await _context.SaveChangesAsync();
}
public Task DeleteItemAsync(Guid id)
{
throw new NotImplementedException();
}
public async Task<MockResponse> GetItemAsync(Guid id)
{
var item = _context.MockResponses.Where(item => item.Id == id).SingleOrDefault();
return await Task.FromResult(item);
}
public async Task<IEnumerable<MockResponse>> GetItemsAsync()
{
return await Task.FromResult(_context.MockResponses.ToList());
}
public async Task UpdateItemAsync(MockResponse item)
{
await Task.FromResult(_context.MockResponses.Update(item));
await _context.SaveChangesAsync();
}
}
}
<file_sep>/MockServiceApi/MockServiceApi/Data/Migrations/20210203203436_ModifiedResClient.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace MockServiceApi.Data.Migrations
{
public partial class ModifiedResClient : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "MyProperty",
table: "RestClients",
newName: "HttpMethod");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "HttpMethod",
table: "RestClients",
newName: "MyProperty");
}
}
}
<file_sep>/MockServiceApi/MockServiceApi/Controllers/RestClientController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MockServiceApi.Dtos;
using MockServiceApi.Models;
using MockServiceApi.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
namespace MockServiceApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RestClientController : ControllerBase
{
private readonly IRestClientRepository _repository;
private static readonly HttpClient client = new HttpClient();
public RestClientController(IRestClientRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task<IEnumerable<RestClient>> GetItemsAsync()
{
var items = (await _repository.GetItemsAsync());
// .Select(item => item as RestClientDto);
return items;
}
[HttpGet("{id}")]
public async Task<ActionResult<RestClient>> GetItemAsync(Guid id)
{
var item = await _repository.GetItemAsync(id);
if (item is null)
{
return NotFound();
}
return item;//.AsDto();
}
[HttpPost]
public async Task<ActionResult<RestClient>> CreateItemAsync(RestClientDto itemDto)
{
RestClient item = new RestClient()
{
Id = Guid.NewGuid(),
EndPoint = itemDto.EndPoint,
HttpMethod = (HttpVerb)itemDto.HttpMethod
};
await _repository.CreateItemAsync(item);
return Ok(item);//CreatedAtAction(nameof(GetItemAsync), new { id = item.Id }); //item.AsDto());
}
}
}
<file_sep>/MockServiceUI/MockUI/Models/RestClientDto.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MockUI.Models
{
public class RestClientDto
{
public string EndPoint { get; set; }
public int HttpMethod { get; set; }
public string Parameter { get; set; }
}
public enum Method
{
[Display(Name = "POST")]
GET,
[Display(Name = "POST")]
POST,
[Display(Name = "PUT")]
PUT,
[Display(Name = "Delete")]
DELETE
}
}
<file_sep>/MockServiceApi/MockServiceApi/Data/DataContext.cs
using Microsoft.EntityFrameworkCore;
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<RestClient> RestClients { get; set; }
public DbSet<MockResponse> MockResponses { get; set; }
}
}
<file_sep>/MockServiceApi/MockServiceApi/Dtos/RequestDto.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Dtos
{
public class RequestDto
{
public JsonResult raw { get; set; }
}
}
<file_sep>/MockServiceUI/MockUI/Models/MethodRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockUI.Models
{
public class MethodRequest
{
public int id { get; set; }
public string Name { get; set; }
public List<MethodRequest> GetMethodRequest()
{
var list = new List<MethodRequest>
{
new MethodRequest { id = 0, Name = "GET"},
new MethodRequest { id = 1, Name = "POST" },
new MethodRequest { id = 2, Name = "PUT" },
new MethodRequest { id = 3, Name = "DELETE" },
};
return list;
}
}
}
<file_sep>/MockServiceApi/MockServiceApi/Controllers/MockResponseController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MockServiceApi.Dtos;
using MockServiceApi.Models;
using MockServiceApi.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MockServiceApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MockResponseController : ControllerBase
{
private readonly IMockResponseRepository _repository;
public MockResponseController(IMockResponseRepository repository)
{
_repository = repository;
}
private static readonly HttpClient client = new HttpClient();
[HttpGet]
public async Task<ActionResult<IEnumerable<MockResponse>>> GetItemsAsync()
{
var items = await _repository.GetItemsAsync();
// .Select(item => item as RestClientDto);
return items.ToList();
}
[HttpGet("{id}")]
public async Task<ActionResult<MockResponse>> GetItemAsync(Guid id)
{
var item = await _repository.GetItemAsync(id);
if (item is null)
{
return NotFound();
}
return item;//.AsDto();
}
[HttpPost]
public async Task<ActionResult<MockResponse>> CreateItemAsync(MockResponseDto mock)
{
MockResponse item = new MockResponse()
{
Id = Guid.NewGuid(),
EndPoint = mock.EndPoint,
HttpMethod = (HttpVerb)mock.HttpMethod,
ResponseCode = mock.ResponseCode,
ResponseBody = mock.ResponseBody
};
await _repository.CreateItemAsync(item);
return Ok(item);//CreatedAtAction(nameof(GetItemAsync), new { id = item.Id }); //item.AsDto());
}
[HttpPost("getDataRepo")]
public async Task<ActionResult<List<JsonDocument>>> GetDataRepo([FromBody]RestClientDto item)
{
HttpResponseMessage streamTask = new HttpResponseMessage();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
if (item.HttpMethod == 0)
{ // get Request
streamTask = await getMockService(item.EndPoint);
}
if (item.HttpMethod == 1)
{
// post
streamTask = postMockService(item.EndPoint, item.Parameter);
}
if (item.HttpMethod == 2)
{
// put
streamTask = await putMockService(item.EndPoint, item.Parameter);
}
if (item.HttpMethod == 3)
{
// delete
streamTask = await deleteMockService(item.EndPoint);
}
if (!streamTask.IsSuccessStatusCode)
throw new Exception(streamTask.ToString());
var responsemessage = streamTask.Content.ReadAsStringAsync().Result;
dynamic author = JsonConvert.DeserializeObject(responsemessage);
if (responsemessage is null)
{
return NotFound();
}
return Ok(responsemessage);
}
private async Task<HttpResponseMessage> getMockService(string endPoint)
{
var getData = await client.GetAsync(endPoint);
return getData;
}
private HttpResponseMessage postMockService(string endPoint, string content)
{
var inputMessage = new HttpRequestMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage getData = client.PostAsync(endPoint, inputMessage.Content).Result;
return getData;
}
private async Task<HttpResponseMessage> putMockService(string endPoint, string content)
{
var inputMessage = new HttpRequestMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PutAsync(endPoint, inputMessage.Content);
return response;
}
private async Task<HttpResponseMessage> deleteMockService(string endPoint)
{
HttpResponseMessage response = await client.DeleteAsync(endPoint);
return response;
}
}
}
<file_sep>/MockServiceApi/MockServiceApi/Repositories/IRestClientRepository.cs
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Repositories
{
public interface IRestClientRepository
{
Task<RestClient> GetItemAsync(Guid id);
Task<IEnumerable<RestClient>> GetItemsAsync();
Task CreateItemAsync(RestClient item);
Task UpdateItemAsync(RestClient item);
Task DeleteItemAsync(Guid id);
}
}
<file_sep>/MockServiceApi/MockServiceApi/Dtos/RestClientDto.cs
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace MockServiceApi.Dtos
{
public class RestClientDto
{
public string EndPoint { get; set; }
public int HttpMethod { get; set; }
public string Parameter { get; set; }
}
}
<file_sep>/MockServiceApi/MockServiceApi/Repositories/IMockResponseRepository.cs
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Repositories
{
public interface IMockResponseRepository
{
Task<MockResponse> GetItemAsync(Guid id);
Task<IEnumerable<MockResponse>> GetItemsAsync();
Task CreateItemAsync(MockResponse item);
Task UpdateItemAsync(MockResponse item);
Task DeleteItemAsync(Guid id);
}
}
<file_sep>/MockServiceApi/MockServiceApi/Models/MockResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Models
{
public class MockResponse : BaseEntity
{
public string EndPoint { get; set; }
public HttpVerb HttpMethod { get; set; }
public int ResponseCode { get; set; }
public string ResponseBody { get; set; }
}
}
<file_sep>/MockServiceApi/MockServiceApi/Repositories/RestClientRepository.cs
using MockServiceApi.Data;
using MockServiceApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MockServiceApi.Repositories
{
public class RestClientRepository : IRestClientRepository
{
private readonly DataContext _context;
public RestClientRepository(DataContext context)
{
_context = context;
}
public async Task CreateItemAsync(RestClient item)
{
await _context.RestClients.AddAsync(item);
await _context.SaveChangesAsync();
}
public Task DeleteItemAsync(Guid id)
{
throw new NotImplementedException();
}
public async Task<RestClient> GetItemAsync(Guid id)
{
var item = _context.RestClients.Where(item => item.Id == id).SingleOrDefault();
return await Task.FromResult(item);
}
public async Task<IEnumerable<RestClient>> GetItemsAsync()
{
return await Task.FromResult(_context.RestClients);
}
public async Task UpdateItemAsync(RestClient item)
{
await Task.FromResult(_context.RestClients.Update(item));
await _context.SaveChangesAsync();
}
}
}
| 0408fb997b3e5cab3668519e83fd8fa869cf4055 | [
"C#",
"Text"
] | 16 | C# | MatiasDevop/restclient-net5-blazor | 530d68a7ee4c2960b566b7d06da002b966a52a1f | f44518573ece84cf1c62030b212b972a32dc6a16 |
refs/heads/master | <repo_name>openVespa/FireFly<file_sep>/MiniGUI/WFF GenericHID Communication Library/deviceCommunication.cs
//-----------------------------------------------------------------------------
//
// deviceCommunication.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Threading;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Communication_Library
{
public partial class WFF_GenericHID_Communication_Library
{
#region outputToDeviceRegion
/// <summary>
/// writeRawReportToDevice - Writes a report to the device using interrupt transfer.
/// Note: this method performs no checking on the buffer. The first byte must
/// always be zero (or the write will fail!) and the second byte should be the
/// command number for the USB device firmware.
/// </summary>
private bool writeRawReportToDevice(Byte[] outputReportBuffer)
{
bool success = false;
int numberOfBytesWritten = 0;
// Since the Windows API requires us to have a leading 0 in all file output buffers
// we must create a 65 byte array, set the first byte to 0 and then copy in the 64
// bytes of real data in order for the read/write operation to function correctly
Byte[] adjustedOutputBuffer = new Byte[outputReportBuffer.Length + 1];
adjustedOutputBuffer[0] = 0;
outputReportBuffer.CopyTo(adjustedOutputBuffer, 1);
// Make sure a device is attached
if (!isDeviceAttached)
{
Debug.WriteLine("usbGenericHidCommunication:writeRawReportToDevice(): -> No device attached!");
return success;
}
try
{
// Set an output report via interrupt to the device
success = WriteFile(
deviceInformation.writeHandle,
adjustedOutputBuffer,
adjustedOutputBuffer.Length,
ref numberOfBytesWritten,
IntPtr.Zero);
if (success) Debug.WriteLine("usbGenericHidCommunication:writeRawReportToDevice(): -> Write report succeeded");
else
{
Debug.WriteLine("usbGenericHidCommunication:writeRawReportToDevice(): -> Write report failed!");
}
return success;
}
catch (Exception)
{
// An error - send out some debug and return failure
Debug.WriteLine("usbGenericHidCommunication:writeRawReportToDevice(): -> EXCEPTION: When attempting to send an output report");
return false;
}
}
/// <summary>
/// writeSingleReportToDevice - Writes a single report packet to the USB device.
/// The size of the passed outputReportBuffer must be correct for the device, so
/// this method checks the passed buffer's size against the output report size
/// discovered by the device enumeration.
/// </summary>
/// <param name="outputReportBuffer"></param>
/// <returns></returns>
protected bool writeSingleReportToDevice(Byte[] outputReportBuffer)
{
bool success;
// The size of our outputReportBuffer must be at least the same size as the output report (which is length+1).
if (outputReportBuffer.Length != (int)deviceInformation.capabilities.outputReportByteLength - 1)
{
// outputReportBuffer is not the right length!
Debug.WriteLine(
"usbGenericHidCommunication:writeSingleReportToDevice(): -> ERROR: The referenced outputReportBuffer size is incorrect for the output report size!");
return false;
}
// The writeRawReportToDevice method will write the passed buffer or return false
success = writeRawReportToDevice(outputReportBuffer);
return success;
}
/// <summary>
/// writeMultipleReportsToDevice - Attempts to write multiple reports to the device in
/// a single write. This action can be block the form execution if you write too much data.
/// If you need more data to the device and want to avoid any blocking you will have to make
/// multiple commands to the device and deal with the multiple requests and responses in your
/// application.
/// </summary>
/// <param name="outputReportBuffer"></param>
/// <param name="numberOfReports"></param>
/// <returns></returns>
protected bool writeMultipleReportsToDevice(Byte[] outputReportBuffer, int numberOfReports)
{
bool success = false;
// Range check the number of reports
if (numberOfReports == 0)
{
Debug.WriteLine(
"usbGenericHidCommunication:writeMultipleReportsToDevice(): -> ERROR: You cannot write 0 reports!");
return false;
}
if (numberOfReports > 128)
{
Debug.WriteLine(
"usbGenericHidCommunication:writeMultipleReportsToDevice(): -> ERROR: Reference application testing does not verify the code for more than 128 reports");
return false;
}
// The size of our outputReportBuffer must be at least the same size as the output report multiplied by the number of reports to be written.
if (outputReportBuffer.Length != (((int)deviceInformation.capabilities.outputReportByteLength - 1) * numberOfReports))
{
// outputReportBuffer is not the right length!
Debug.WriteLine(
"usbGenericHidCommunication:writeMultipleReportsToDevice(): -> ERROR: The referenced outputReportBuffer size is incorrect for the number of output reports requested!");
return false;
}
// The windows API returns a write failure if we try to send more than deviceInformation.capabilities.outputReportByteLength bytes
// in a single write to the device (would be nice if the HID API handled this, but it doesn't). Therefore we have to split a multi-
// report send into 64 byte chunks and send one at a time...
Int64 reportNumber;
Byte[] tempOutputBuffer = new Byte[deviceInformation.capabilities.outputReportByteLength - 1];
for (reportNumber = 0; reportNumber < numberOfReports; reportNumber++)
{
// Copy the next chunk of 64 bytes into the temporary output buffer
Int64 startByte = 0;
Int64 pointer = 0;
for (startByte = reportNumber * 64; startByte < (reportNumber * 64) + 64; startByte++)
{
tempOutputBuffer[pointer] = outputReportBuffer[startByte];
pointer++;
}
// The writeRawReportToDevice method will write the passed buffer or return false
success = writeRawReportToDevice(tempOutputBuffer);
if (success == false)
{
Debug.WriteLine(
"usbGenericHidCommunication:writeMultipleReportsToDevice(): -> ERROR: Sending failed for report {0} of {0}!",
reportNumber, numberOfReports);
// Give up
return false;
}
}
return success;
}
#endregion
#region inputFromDeviceRegion
/// <summary>
/// readRawReportFromDevice - Reads a raw report from the device with timeout handling
/// Note: This method performs no checking on the buffer. The first byte returned is
/// usually zero, the second byte is the command that the USB firmware is replying to.
/// The other 63 bytes are (possibly) data.
///
/// The maximum report size will be determind by the length of the inputReportBuffer.
/// </summary>
private bool readRawReportFromDevice(ref Byte[] inputReportBuffer, ref int numberOfBytesRead)
{
IntPtr eventObject = IntPtr.Zero;
NativeOverlapped hidOverlapped = new NativeOverlapped();
IntPtr nonManagedBuffer = IntPtr.Zero;
IntPtr nonManagedOverlapped = IntPtr.Zero;
Int32 result = 0;
bool success;
// Since the Windows API requires us to have a leading 0 in all file input buffers
// we must create a 65 byte array, set the first byte to 0 and then copy in the 64
// bytes of real data in order for the read/write operation to function correctly
Byte[] adjustedInputBuffer = new Byte[inputReportBuffer.Length + 1];
adjustedInputBuffer[0] = 0;
// Make sure a device is attached
if (!isDeviceAttached)
{
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> No device attached!");
return false;
}
try
{
// Prepare an event object for the overlapped ReadFile
eventObject = CreateEvent(IntPtr.Zero, false, false, "");
hidOverlapped.OffsetLow = 0;
hidOverlapped.OffsetHigh = 0;
hidOverlapped.EventHandle = eventObject;
// Allocate memory for the unmanaged input buffer and overlap structure.
nonManagedBuffer = Marshal.AllocHGlobal(adjustedInputBuffer.Length);
nonManagedOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(hidOverlapped));
Marshal.StructureToPtr(hidOverlapped, nonManagedOverlapped, false);
// Read the input report buffer
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> Attempting to ReadFile");
success = ReadFile(
deviceInformation.readHandle,
nonManagedBuffer,
adjustedInputBuffer.Length,
ref numberOfBytesRead,
nonManagedOverlapped);
if (!success)
{
// We are now waiting for the FileRead to complete
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> ReadFile started, waiting for completion...");
// Wait a maximum of 3 seconds for the FileRead to complete
result = WaitForSingleObject(eventObject, 3000);
switch (result)
{
// Has the ReadFile completed successfully?
case (System.Int32)WAIT_OBJECT_0:
success = true;
// Get the number of bytes transferred
GetOverlappedResult(deviceInformation.readHandle, nonManagedOverlapped, ref numberOfBytesRead, false);
Debug.WriteLine(string.Format("usbGenericHidCommunication:readRawReportFromDevice(): -> ReadFile successful (overlapped) {0} bytes read", numberOfBytesRead));
break;
// Did the FileRead operation timeout?
case WAIT_TIMEOUT:
success = false;
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> ReadFile timedout! USB device detached");
// Cancel the ReadFile operation
CancelIo(deviceInformation.readHandle);
if (!deviceInformation.hidHandle.IsInvalid) deviceInformation.hidHandle.Close();
if (!deviceInformation.readHandle.IsInvalid) deviceInformation.readHandle.Close();
if (!deviceInformation.writeHandle.IsInvalid) deviceInformation.writeHandle.Close();
// Detach the USB device to try to get us back in a known state
detachUsbDevice();
break;
// Some other unspecified error has occurred?
default:
success = false;
// Cancel the ReadFile operation
// Detach the USB device to try to get us back in a known state
detachUsbDevice();
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> ReadFile unspecified error! USB device detached");
break;
}
}
if (success)
{
// Report receieved correctly, copy the unmanaged input buffer over to the managed array buffer
Marshal.Copy(nonManagedBuffer, adjustedInputBuffer, 0, numberOfBytesRead);
// Make sure we didn't get a successful read with 0 bytes back
if (numberOfBytesRead > 0)
{
// Now we need to loose the leading 0 byte and transfer the buffer over to the real input buffer
// (I couldn't find a nicer way of doing this with a managed array of bytes, but if you know of
// one, let me know ;)
Int64 byteCounter;
for (byteCounter = 1; byteCounter < adjustedInputBuffer.Length; byteCounter++)
inputReportBuffer[byteCounter - 1] = adjustedInputBuffer[byteCounter];
// Adjust the number of bytes read (since it's returned by reference)
numberOfBytesRead -= 1;
}
Debug.WriteLine(string.Format("usbGenericHidCommunication:readRawReportFromDevice(): -> ReadFile successful returning {0} bytes", numberOfBytesRead));
}
}
catch (Exception)
{
// An error - send out some debug and return failure
Debug.WriteLine("usbGenericHidCommunication:readRawReportFromDevice(): -> EXCEPTION: When attempting to receive an input report");
return false;
}
// Release non-managed objects before returning
Marshal.FreeHGlobal(nonManagedBuffer);
Marshal.FreeHGlobal(nonManagedOverlapped);
// Close the file handle to release the object
CloseHandle(eventObject);
return success;
}
/// <summary>
/// readSingleReportFromDevice - Reads a single report packet from the USB device.
/// The size of the passed inputReportBuffer must be correct for the device, so
/// this method checks the passed buffer's size against the input report size
/// discovered by the device enumeration.
/// </summary>
/// <param name="inputReportBuffer"></param>
/// <returns></returns>
protected bool readSingleReportFromDevice(ref Byte[] inputReportBuffer)
{
bool success;
int numberOfBytesRead = 0;
// The size of our inputReportBuffer must be at least the same size as the input report.
if (inputReportBuffer.Length != ((int)deviceInformation.capabilities.inputReportByteLength - 1))
{
// inputReportBuffer is not the right length!
Debug.WriteLine(
"usbGenericHidCommunication:readSingleReportFromDevice(): -> ERROR: The referenced inputReportBuffer size is incorrect for the input report size!");
return false;
}
// The readRawReportFromDevice method will fill the passed readBuffer or return false
success = readRawReportFromDevice(ref inputReportBuffer, ref numberOfBytesRead);
return success;
}
/// <summary>
/// readMultipleReportsFromDevice - Attempts to retrieve multiple reports from the device in
/// a single read. This action can be block the form execution if you request too much data.
/// If you need more data from the device and want to avoid any blocking you will have to make
/// multiple commands to the device and deal with the multiple requests and responses in your
/// application.
/// </summary>
/// <param name="inputReportBuffer"></param>
/// <param name="numberOfReports"></param>
/// <returns></returns>
protected bool readMultipleReportsFromDevice(ref Byte[] inputReportBuffer, int numberOfReports)
{
bool success = false;
int numberOfBytesRead = 0;
long pointerToBuffer = 0;
// Note: The Windows HID API always returns with 65 bytes (i.e. a leading 0 and 64 real bytes) no
// matter how much data we request from the ReadFile, so this method is effectively the same as
// calling readRawReportFromDevice many times with a 64 byte buffer. However it provides a nice
// abstraction so it is kept.
// Define a temporary buffer for assembling partial data reads into the completed inputReportBuffer
Byte[] temporaryBuffer = new Byte[deviceInformation.capabilities.inputReportByteLength - 1];
// Range check the number of reports
if (numberOfReports == 0)
{
Debug.WriteLine(
"usbGenericHidCommunication:readMultipleReportsFromDevice(): -> ERROR: You cannot request 0 reports!");
return false;
}
if (numberOfReports > 128)
{
Debug.WriteLine(
"usbGenericHidCommunication:readMultipleReportsFromDevice(): -> ERROR: Reference application testing does not verify the code for more than 128 reports");
return false;
}
// The size of our inputReportBuffer must be at least the same size as the input report multiplied by the number of reports requested.
if (inputReportBuffer.Length != (((int)deviceInformation.capabilities.inputReportByteLength - 1) * numberOfReports))
{
// inputReportBuffer is not the right length!
Debug.WriteLine(
"usbGenericHidCommunication:readMultipleReportsFromDevice(): -> ERROR: The referenced inputReportBuffer size is incorrect for the number of input reports requested!");
return false;
}
// The readRawReportFromDevice method will fill the passed read buffer or return false
while (pointerToBuffer != (((int)deviceInformation.capabilities.inputReportByteLength-1) * numberOfReports))
{
Debug.WriteLine(
"usbGenericHidCommunication:readMultipleReportsFromDevice(): -> Reading from device...");
success = readRawReportFromDevice(ref temporaryBuffer, ref numberOfBytesRead);
// Was the read successful?
if (!success)
{
return false;
}
// Copy the received data into the referenced input buffer
Array.Copy(temporaryBuffer, 0, inputReportBuffer, pointerToBuffer, (long)numberOfBytesRead);
pointerToBuffer += (long)numberOfBytesRead;
}
Debug.WriteLine(
"usbGenericHidCommunication:readMultipleReportsFromDevice(): -> Got {0} bytes from device", pointerToBuffer);
return success;
}
#endregion
}
}
<file_sep>/MiniGUI/WFF GenericHID Communication Library/hidDll.cs
//-----------------------------------------------------------------------------
//
// hidDll.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Communication_Library
{
/// <summary>
/// hidDll - Partial class containing the API definitions required for interoperability
/// with the hdd.dll API from the Windows Driver Kit (WDK). Primarily this provides
/// methods for communicating with Windows' USB generic HID driver.
/// </summary>
public partial class WFF_GenericHID_Communication_Library
{
// API declarations for hid.dll, taken from hidpi.h (part of the
// Windows Driver Kit (WDK
internal const Int16 HidP_Input = 0;
internal const Int16 HidP_Output = 1;
internal const Int16 HidP_Feature = 2;
[StructLayout(LayoutKind.Sequential)]
internal struct HIDD_ATTRIBUTES
{
internal Int32 size;
internal UInt16 vendorId;
internal UInt16 productId;
internal UInt16 versionNumber;
}
internal struct HIDP_CAPS
{
internal Int16 usage;
internal Int16 usagePage;
internal Int16 inputReportByteLength;
internal Int16 outputReportByteLength;
internal Int16 featureReportByteLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
internal Int16[] reserved;
internal Int16 numberLinkCollectionNodes;
internal Int16 numberInputButtonCaps;
internal Int16 numberInputValueCaps;
internal Int16 numberInputDataIndices;
internal Int16 numberOutputButtonCaps;
internal Int16 numberOutputValueCaps;
internal Int16 numberOutputDataIndices;
internal Int16 numberFeatureButtonCaps;
internal Int16 numberFeatureValueCaps;
internal Int16 numberFeatureDataIndices;
}
//internal struct HidP_Value_Caps
// {
// internal Int16 usagePage;
// internal Byte reportID;
// internal Int32 isAlias;
// internal Int16 bitField;
// internal Int16 linkCollection;
// internal Int16 linkUsage;
// internal Int16 linkUsagePage;
// internal Int32 isRange;
// internal Int32 isStringRange;
// internal Int32 isDesignatorRange;
// internal Int32 isAbsolute;
// internal Int32 hasNull;
// internal Byte reserved;
// internal Int16 bitSize;
// internal Int16 reportCount;
// internal Int16 reserved2;
// internal Int16 reserved3;
// internal Int16 reserved4;
// internal Int16 reserved5;
// internal Int16 reserved6;
// internal Int32 logicalMin;
// internal Int32 logicalMax;
// internal Int32 physicalMin;
// internal Int32 physicalMax;
// internal Int16 usageMin;
// internal Int16 usageMax;
// internal Int16 stringMin;
// internal Int16 stringMax;
// internal Int16 designatorMin;
// internal Int16 designatorMax;
// internal Int16 dataIndexMin;
// internal Int16 dataIndexMax;
// }
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_FlushQueue(
SafeFileHandle HidDeviceObject
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_FreePreparsedData(
IntPtr PreparsedData
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_GetAttributes(
SafeFileHandle HidDeviceObject,
ref HIDD_ATTRIBUTES Attributes
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_GetFeature(
SafeFileHandle HidDeviceObject,
Byte[] lpReportBuffer,
Int32 ReportBufferLength
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_GetInputReport(
SafeFileHandle HidDeviceObject,
Byte[] lpReportBuffer,
Int32 ReportBufferLength);
[DllImport("hid.dll", SetLastError = true)]
internal static extern void HidD_GetHidGuid(
ref System.Guid HidGuid
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_GetNumInputBuffers(
SafeFileHandle HidDeviceObject,
ref Int32 NumberBuffers
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_GetPreparsedData(
SafeFileHandle HidDeviceObject,
ref IntPtr PreparsedData
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_SetFeature(
SafeFileHandle HidDeviceObject,
Byte[] lpReportBuffer,
Int32 ReportBufferLength);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_SetNumInputBuffers(
SafeFileHandle HidDeviceObject,
Int32 NumberBuffers
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Boolean HidD_SetOutputReport(
SafeFileHandle HidDeviceObject,
Byte[] lpReportBuffer,
Int32 ReportBufferLength
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Int32 HidP_GetCaps(
IntPtr PreparsedData,
ref HIDP_CAPS Capabilities
);
[DllImport("hid.dll", SetLastError = true)]
internal static extern Int32 HidP_GetValueCaps(
Int32 ReportType,
Byte[] ValueCaps,
ref Int32 ValueCapsLength,
IntPtr PreparsedData
);
}
}
<file_sep>/FFmini_HID/BU/24MAY2014_BU.c
/*
LUFA Library
Copyright (C) <NAME>, 2014.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2014 <NAME> (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaims all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
/** \file
*
* Main source file for the GenericHID demo. This file contains the main tasks of
* the demo and is responsible for the initial application hardware configuration.
*/
#include "GenericHID.h"
#include "map1.h"
#include "map2.h"
//#include "map3.h" // This was just a debug test map
volatile uint8_t USBConnected;
volatile uint8_t first_cycle;
volatile uint8_t bad_count;
volatile uint8_t send_flag;
volatile uint8_t map_num;
volatile uint8_t request_num;
volatile uint8_t seq_num;
volatile uint8_t MAP_STATIC_TEMP;
volatile uint8_t temp_rset;
// TO DO: combine all of these into one byte
volatile uint8_t ISR_flags;
volatile uint8_t reluctor_trigger;
volatile uint8_t t0OVF_trigger;
volatile uint8_t serial_trigger;
volatile uint8_t t1OVF_trigger;
volatile uint8_t timer1_OVF_RPM;
volatile uint8_t timer1H;
volatile uint8_t timer1L;
volatile uint8_t tcA_high;
volatile uint8_t tcA_low;
volatile uint8_t tcB_high;
volatile uint8_t tcB_low;
volatile uint8_t cht_h = 0;
volatile uint8_t cht_l = 0;
volatile uint8_t egt_h = 0;
volatile uint8_t egt_l = 0;
/** Buffer to hold the previously generated HID report, for comparison purposes inside the HID class driver. */
static uint8_t PrevHIDReportBuffer[GENERIC_REPORT_SIZE];
/** LUFA HID Class driver interface configuration and state information. This structure is
* passed to all HID Class driver functions, so that multiple instances of the same class
* within a device can be differentiated from one another.
*/
USB_ClassInfo_HID_Device_t Generic_HID_Interface =
{
.Config =
{
.InterfaceNumber = INTERFACE_ID_GenericHID,
.ReportINEndpoint =
{
.Address = GENERIC_IN_EPADDR,
.Size = GENERIC_EPSIZE,
.Banks = 1,
},
.PrevReportINBuffer = PrevHIDReportBuffer,
.PrevReportINBufferSize = sizeof(PrevHIDReportBuffer),
},
};
/** Main program entry point. This routine contains the overall program flow, including initial
* setup of all components and the main program loop.
*/
int main(void)
{
//SetupHardware();
//LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
//GlobalInterruptEnable();
temp_rset = MCUSR; // Grab reset register
MCUSR = 0x00; // Clear reset register
/* Disable watchdog if enabled by boot loader/fuses */
MCUSR &= ~(1 << WDRF);
wdt_disable();
static uint16_t MAP[101];
uint16_t tempdiv = 0;
uint32_t total_time = 0;
uint8_t temp_high = 0;
uint8_t temp_low = 0;
uint8_t RPM;
//uint8_t OLD_RPM1;
//uint8_t OLD_RPM2;
//uint8_t OLD_RPM3;
//uint8_t OLD_RPM4;
uint8_t OVFt1;
uint8_t OVFt1OLD;
//uint8_t MA;
//uint8_t MAL;
//uint8_t MAH;
//uint8_t serial_msg_count = 0;
//uint16_t crc;
uint8_t i; // generic indexer
//uint8_t FF_FWversion = 1;
uint8_t cycle_count = 0;
uint8_t EGT_check_flag = 0;
OVFt1 = 0; // Reset the OVF counter
OVFt1OLD = 0; // Reset the OVF counter
// Start with CDI trigger low
PORTD &= ~(_BV(IGN_TRIGGER)); // LOW
first_cycle = 1;
send_flag = 0;
bad_count = 0;
RPM = 0;
//OLD_RPM1 = 9;
//OLD_RPM2 = 9;
//OLD_RPM3 = 9;
//OLD_RPM4 = 9;
timer1H = 0;
timer1L = 0;
ISR_flags = 0;
reluctor_trigger = 0;
timer1_OVF_RPM = 0;
t0OVF_trigger = 0;
t1OVF_trigger = 0;
tcA_high = 0;
tcA_low = 0;
tcB_high = 0;
tcB_low = 0;
//crc = 0xffff; // initialize crc
CR_flag = 0;
// Starter MA values allows first cycle through
//MA = 0;
//MAL = 0;
//MAH = 101;
// 0 - INPUT
// 1 - OUTPUT
DDRB = 0x10; //
DDRC = 0x20; //
DDRD = 0x41; //
//**********************************************************
SetupHardware();
RingBuffer_InitBuffer(&BTtoFF_Buffer, BTtoFF_Buffer_Data, sizeof(BTtoFF_Buffer_Data));
//**********************************************************
// FF PULL
// TO DO: Switch to the LUFA switch reads?
if((PINB & 0x20))
{// && (!(PINF & 0x40))){ // LOAD MAP 2
map_num = 0x02; // Indicates MAP 2 is loaded
eeprom_busy_wait();
MAP_STATIC_TEMP = eeprom_read_byte((uint8_t*)&MAP2_STATIC);
for(i = 0;i<101;i++)
{
eeprom_busy_wait();
MAP[i] = eeprom_read_word((uint16_t*)&MAP2[i]);
}
}
else
{ // LOAD MAP 1
map_num = 0x01; // Indicates MAP 1 is loaded
eeprom_busy_wait();
MAP_STATIC_TEMP = eeprom_read_byte((uint8_t*)&MAP1_STATIC);
for(i = 0;i<101;i++)
{
eeprom_busy_wait();
MAP[i] = eeprom_read_word((uint16_t*)&MAP1[i]);
}
}
TCNT1 = 0; // Reset Timer1
//LEDs_TurnOffLEDs(LEDS_LED1);
PORTD &= ~(_BV(MAIN_LED)); // LOW
request_num = 0x01; // Gets us sending back data packets
sei(); // Enable interrupts
for (;;)
{
HID_Device_USBTask(&Generic_HID_Interface);
USB_USBTask();
// Check the flags
cli();
//********************************************************************
// IF this timer ever overflows more than 146 times,
// the engine is running at less than 100 RPMs.
if(timer1_OVF_RPM > 146)
{
// Disable comparators
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
first_cycle = 1;
total_time = 0;
OVFt1 = 0; // Reset the OVF counter
timer1_OVF_RPM = 0;
cycle_count = 0;
//OLD_RPM1 = 9;
//OLD_RPM2 = 9;
//OLD_RPM3 = 9;
//OLD_RPM4 = 9;
//MAL = 0;
//MAH = 101;
// Enable the pass thru circuit
PORTD &= ~(_BV(IGN_TRIGGER)); // LOW
}
//********************************************************************
if (reluctor_trigger) // time to make the donuts
{
if (!first_cycle)
{
PORTD &= ~(_BV(IGN_TRIGGER)); // LOW
// Copy volatile variables to local copies
// Does this help? Verify?
temp_high = timer1H;
temp_low = timer1L;
OVFt1 = timer1_OVF_RPM;
if( (OVFt1 > 0) )
{
tempdiv = 0x00FF & OVFt1;
tempdiv = tempdiv<<8;
tempdiv = tempdiv + temp_high;
RPM = (uint8_t)(37528/tempdiv);
total_time = tempdiv;
total_time = total_time<<8;
total_time = total_time + temp_low;
if(RPM < 101)
{
TCNT1 = 0x0000; // Reset Timer1
OCR1A = MAP[RPM];
OCR1B = MAP[RPM] + 800; // To Do: Change this to a variable
// Enable CompA, Disable CompB
TIFR1 = (1<<OCF1A); // Clear timer1A compare flag
TIMSK1|= (1<<OCIE1A); // Enable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
// Reset the OVF counter
OVFt1OLD = OVFt1;
OVFt1 = 0;
}
else // RPM > 101 (10,100 RPM), false trigger
{
TIMSK1&=~(1<<OCIE1A); // Disable timer1B compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
}
}
else // OVF = 0, false trigger
{
TIMSK1&=~(1<<OCIE1A); // Disable timer1B compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
}
} // End !first_cycle
// Clear the first cycle flag
else
{
first_cycle = 0;
OVFt1 = 0;
PORTD &= ~(_BV(IGN_TRIGGER)); // LOW
TIMSK1&=~(1<<OCIE1A); // Disable timer1B compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
}
reluctor_trigger = 0;
}// END reluctor_trigger
//********************************************************************
if(t0OVF_trigger) // 4Hz, 4 per second
{
t0OVF_trigger = 0;
PORTD ^= (_BV(MAIN_LED)); // TOGGLE
EGT_check_flag = 1;
}
sei();
if(EGT_check_flag)
{
PORTB &= ~(_BV(MAXCHT)); // LOW to read data
cht_h = SPI_ReceiveByte();
cht_l = SPI_ReceiveByte();
PORTB |= _BV(MAXCHT); // HIGH starts new conversion
PORTC &= ~(_BV(MAXEGT)); // LOW to read data
egt_h = SPI_ReceiveByte();
egt_l = SPI_ReceiveByte();
PORTC |= _BV(MAXEGT); // HIGH starts new conversion
EGT_check_flag = 0;
}
//*********************************************************************************************
if(CR_flag)
{
if( (!(RingBuffer_IsEmpty(&BTtoFF_Buffer))))
{
parse_SER_buffer(egt_h,egt_l,cht_h,cht_l,total_time);
}
}
}
}
//*******************************************************************************
void KillStuff(){
cli(); // disable interrupts
// Turn everything off and clear pending interrupts
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
TIMSK1&=~(1<<TOIE1); // Disable timer1 OVF
TIMSK0&=~(1<<TOIE0); // Disable timer0 OVF
UCSR1B&=~(1<<RXCIE1); // Disable RX ISR
EIMSK = 0x00; // Disable all external interrupts
TIFR1 = (1<<OCF1A); // Clear timer1A compare flag
TIFR1 = (1<<OCF1B); // Clear timer1B compare flag
TIFR1 = (1<<TOV1); // Clear timer1 OVF flag
TIFR0 = (1<<TOV0); // Clear timer0 OVF flag
EIFR = 0xFF; // Clear all pending external interrupts
UCSR1B = 0;
UCSR1A = 0;
UCSR1C = 0;
UBRR1 = 0;
CR_flag = 0;
//LEDs_TurnOffLEDs(LEDS_LED1);
PORTD &= ~(_BV(MAIN_LED)); // LOW
}
//********************************************************************
/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
#if (ARCH == ARCH_AVR8)
/* Disable watchdog if enabled by bootloader/fuses */
MCUSR &= ~(1 << WDRF);
wdt_disable();
/* Disable clock division */
clock_prescale_set(clock_div_1);
#elif (ARCH == ARCH_XMEGA)
/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
#endif
/* Hardware Initialization */
EXT_INT_init();
TIMER0_init();
TIMER1_init();
// Initialize the serial USART driver before first use, with 9600 baud (and no double-speed mode)
Serial_Init(9600, false);
UCSR1B |= (1 << RXCIE1); // Added this to enable RX ISR
SPI_Init((SPI_SPEED_FCPU_DIV_8 | SPI_SCK_LEAD_RISING | SPI_SAMPLE_TRAILING | SPI_ORDER_MSB_FIRST | SPI_MODE_MASTER ) );
USB_Init();
}
/** Event handler for the library USB Connection event. */
void EVENT_USB_Device_Connect(void)
{
}
/** Event handler for the library USB Disconnection event. */
void EVENT_USB_Device_Disconnect(void)
{
}
/** Event handler for the library USB Configuration Changed event. */
void EVENT_USB_Device_ConfigurationChanged(void)
{
bool ConfigSuccess = true;
ConfigSuccess &= HID_Device_ConfigureEndpoints(&Generic_HID_Interface);
USB_Device_EnableSOFEvents();
//LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}
/** Event handler for the library USB Control Request reception event. */
void EVENT_USB_Device_ControlRequest(void)
{
HID_Device_ProcessControlRequest(&Generic_HID_Interface);
}
/** Event handler for the USB device Start Of Frame event. */
void EVENT_USB_Device_StartOfFrame(void)
{
HID_Device_MillisecondElapsed(&Generic_HID_Interface);
}
/** HID class driver callback function for the creation of HID reports to the host.
*
* \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
* \param[in,out] ReportID Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
* \param[in] ReportType Type of the report to create, either HID_REPORT_ITEM_In or HID_REPORT_ITEM_Feature
* \param[out] ReportData Pointer to a buffer where the created report should be stored
* \param[out] ReportSize Number of bytes written in the report (or zero if no report is to be sent)
*
* \return Boolean \c true to force the sending of the report, \c false to let the library determine if it needs to be sent
*/
bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
uint8_t* const ReportID,
const uint8_t ReportType,
void* ReportData,
uint16_t* const ReportSize)
{
uint8_t* hidSendBuffer = (uint8_t*)ReportData;
uint16_t tempMAP;
uint8_t MAPindex;
uint8_t MAPindex_start;
uint8_t MAPindex_end;
uint8_t BUFFERindex;
static uint8_t msg_count = 0;
switch(request_num)
{
case 0x8A: // MAP got sent from host, handled in RX callback
//cli();
//KillStuff();
hidSendBuffer[0] = 0xAB; // Header
hidSendBuffer[1] = 0xCD;
hidSendBuffer[2] = 0x8A;
hidSendBuffer[3] = (seq_num | 0x80); // Echo back as an ACK
hidSendBuffer[22] = 0xDE; // Footer
hidSendBuffer[23] = 0xAD;
request_num = 0x00;
seq_num = 0x00;
*ReportSize = GENERIC_REPORT_SIZE;
return true;
break;
case 0x8B: //MAP being requested by host
//cli();
//KillStuff();
hidSendBuffer[0] = 0xAB; // Header
hidSendBuffer[1] = 0xCD;
hidSendBuffer[2] = 0x8B;
hidSendBuffer[3] = (seq_num | 0x80); // Echo back as an ACK
//hidSendBuffer[22] = 0xDE; // Footer
//hidSendBuffer[23] = 0xAD;
if(seq_num)
{
BUFFERindex = 4;
MAPindex_start = (uint8_t)((seq_num-1)*10);
MAPindex_end = MAPindex_start + 10;
// put data into MSG from EEPROM
if(MAPindex_end<101) // Generic bounds checking, should add error code in msg
{
eeprom_busy_wait();
if((PINB & 0x20)) // LOAD MAP 2
{
hidSendBuffer[29] = eeprom_read_byte((uint8_t*)&MAP2_STATIC);
}
else // LOAD MAP 1
{
hidSendBuffer[29] = eeprom_read_byte((uint8_t*)&MAP1_STATIC);
}
for(MAPindex = MAPindex_start; MAPindex<MAPindex_end; MAPindex++)
{
eeprom_busy_wait();
if((PINB & 0x20)) // LOAD MAP 2
{
tempMAP = eeprom_read_word((uint16_t*)&MAP2[MAPindex]);
}
else // LOAD MAP 1
{
tempMAP = eeprom_read_word((uint16_t*)&MAP1[MAPindex]);
}
hidSendBuffer[BUFFERindex] = (tempMAP & 0xFF00) >> 8; // MSB
++BUFFERindex;
hidSendBuffer[BUFFERindex] = (tempMAP & 0x00FF); // LSB
++BUFFERindex;
}
}
}
request_num = 0x00;
seq_num = 0x00;
*ReportSize = GENERIC_REPORT_SIZE;
return true;
//sei();
break;
case 0x01:
hidSendBuffer[0] = 0xAB; // Header
hidSendBuffer[1] = 0xCD;
hidSendBuffer[2] = 0x01; // MSG Type: Data Packet
// RPM and timing data
hidSendBuffer[3] = timer1H;
hidSendBuffer[4] = timer1L;
hidSendBuffer[5] = timer1_OVF_RPM;
hidSendBuffer[6] = tcA_high;
hidSendBuffer[7] = tcA_low;
hidSendBuffer[8] = tcB_high;
hidSendBuffer[9] = tcB_low;
// EGT and CHT data
hidSendBuffer[16] = egt_h;
hidSendBuffer[17] = egt_l;
hidSendBuffer[18] = cht_h;
hidSendBuffer[19] = cht_l;
// Current MAP number
hidSendBuffer[20] = map_num;
hidSendBuffer[21] = temp_rset;
hidSendBuffer[22] = MAP_STATIC_TEMP;
hidSendBuffer[23] = msg_count++;
*ReportSize = GENERIC_REPORT_SIZE;
break;
default:
*ReportSize = 0;
break;
}
return false;
}
/** HID class driver callback function for the processing of HID reports from the host.
*
* \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
* \param[in] ReportID Report ID of the received report from the host
* \param[in] ReportType The type of report that the host has sent, either HID_REPORT_ITEM_Out or HID_REPORT_ITEM_Feature
* \param[in] ReportData Pointer to a buffer where the received report has been stored
* \param[in] ReportSize Size in bytes of the received HID report
*/
void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
const uint8_t ReportID,
const uint8_t ReportType,
const void* ReportData,
const uint16_t ReportSize)
{
uint8_t* hidReceiveBuffer = (uint8_t*)ReportData;
uint16_t tempMAP;
uint8_t MAPindex;
uint8_t MAPindex_start;
uint8_t MAPindex_end;
uint8_t BUFFERindex;
// Do we have a command request from the host?
if (USB_ControlRequest.bRequest == HID_REQ_SetReport)
{
// Ensure this is the type of report we are interested in
if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
{
if((hidReceiveBuffer[0]==0xAB) &&(hidReceiveBuffer[1]==0xCD))
{
// Process GenericHID command packet
switch(hidReceiveBuffer[2]) // THIS LOCATION NEED TO CHANGE
{
case 0x8A: // Command 0x8A - Getting a MAP from HOST
request_num = 0x8A;
seq_num = hidReceiveBuffer[3];
if(seq_num)
{
// pull data from MSG and put it into EEPROM
BUFFERindex = 4;
MAPindex_start = (uint8_t)((seq_num-1)*10);
MAPindex_end = MAPindex_start + 10;
// put data into MSG from EEPROM
if(MAPindex_end<101) // Generic bounds checking, should add error code in msg
{
eeprom_busy_wait();
if((PINB & 0x20)) // LOAD MAP 2
{
eeprom_write_byte(((uint8_t*)&MAP2_STATIC),hidReceiveBuffer[29]);
}
else // LOAD MAP 1
{
eeprom_write_byte(((uint8_t*)&MAP1_STATIC),hidReceiveBuffer[29]);
}
for(MAPindex = MAPindex_start; MAPindex<MAPindex_end; MAPindex++)
{
tempMAP = 0x00;
tempMAP = (hidReceiveBuffer[BUFFERindex] << 8) + hidReceiveBuffer[BUFFERindex+1];
eeprom_busy_wait();
if((PINB & 0x20)) // LOAD MAP 2
{
eeprom_write_word(((uint16_t*)&MAP2[MAPindex]), tempMAP);
}
else // LOAD MAP 1
{
eeprom_write_word(((uint16_t*)&MAP1[MAPindex]), tempMAP);
}
++BUFFERindex;
++BUFFERindex;
}
}
}
break;
case 0x8B: // Command 0x8B - Send MAP to HOST
request_num = 0x8B;
seq_num = hidReceiveBuffer[3];
break;
case 0x8C: // Command 0x8C - Set MODE to FW loading, i.e. jump to bootloader
cli();
Jump_To_Bootloader();
break;
case 0x8F: // Command 0x8F - Reset FF
cli();
first_cycle = 1; // restarts data collection cycle
request_num = 0x01; // Gets us sending back data packets
sei();
break;
default:
// Unknown command received
break;
} // End of switch(hidReceiveBuffer[0])
}
}
}
}
//***********************************************************
//***********************************************************
//***** *****
//***** START OF THE ISR's *****
//***** *****
//***********************************************************
//***********************************************************
// This interrupt routine is run approx 61 times per second.
ISR(TIMER0_OVF_vect)
{
static uint8_t count=0;
// Interrupt after 156 counts for 100 Hz, so preload 256-156 = 100
// ((16000000/1024)/ 100) = 156
TCNT0 = 100;
if(++count >25) // 100hz/ 25 = 250 msec
{
t0OVF_trigger = 1;
ISR_flags = 1;
count = 0;
}
}
ISR(TIMER1_COMPA_vect)
{
// THIS IS WHERE THE TIMER1 OUTPUT MATCHES THE PRELOADED OUTPUT
// FROM PREVIOUS RPM CALC AND ADV RET CALC
// SO ITS TIME TO TRIGGER THE CDI
if(!first_cycle)
{
// Get the high and low count from timer 1
// Grab them a byte at a time to make it easier to send
tcA_low = TCNT1L;
tcA_high = TCNT1H;
PORTD |= _BV(IGN_TRIGGER); // HIGH
// Disable CompA, Enable CompB
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIFR1 = (1<<OCF1B); // Clear timer1B compare flag
TIMSK1 |= (1<<OCIE1B); // Enable timer1B compare
}
else
{
// Disable compA&B
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
}
}
ISR(TIMER1_COMPB_vect)
{
PORTD &= ~(_BV(IGN_TRIGGER)); // LOW fires at this point?
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
if(!first_cycle)
{
tcB_low = TCNT1L;
tcB_high = TCNT1H;
send_flag = 1; // SEND THE DATA
ISR_flags = 1;
}
}
ISR(TIMER1_OVF_vect)
{
//t1OVF_trigger = 1;
//ISR_flags = 1;
++timer1_OVF_RPM;
}
//*************************************************************
// MAX9924 triggered input from reluctor
//*************************************************************
ISR(INT1_vect)
{
if(!reluctor_trigger) // If your not already set (sort of a debounce?)
{
// Get the high and low count from timer 1
// Grab them a byte at a time to make it easier to send
// via serial port. Might be a smarter way to do this later.
timer1L = TCNT1L;
timer1H = TCNT1H;
TCNT1 = 0; // RESET timer1
reluctor_trigger = 1; // signal main to handle CDI trigger
ISR_flags = 1;
}
}
//*************************************************************
// ISR to manage the reception of data from the serial port
// placing received bytes into a circular buffer
//*************************************************************
ISR(USART1_RX_vect)
{
uint8_t ReceivedByte = UDR1;
if(ReceivedByte == 0x20) {return;} // Ignore spaces
if(ReceivedByte == 0x0D) {CR_flag = 1;} // Received a Carriage Return
RingBuffer_Insert(&BTtoFF_Buffer, ReceivedByte);
}
ISR(BADISR_vect)
{
bad_count++;
}
<file_sep>/MiniGUI/WFF GenericHID Communication Library/usbGenericHidCommunication.cs
//-----------------------------------------------------------------------------
//
// usbGenericHidCommunications.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Collections;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Communication_Library
{
// Since the Class Library is using System.windows.forms we need to set the following
// attribute to prevent VS2010 getting confused and attempting to open class library
// .cs files in the form designer.
[System.ComponentModel.DesignerCategory("")]
/// <summary>
/// WFF GenericHID Communication Library
/// </summary>
/// <remarks>This Library provides communication and device handling events
/// for USB devices which implement the generic HID protocol. It is
/// designed to be inherited into a class which deals with a specific
/// device firmware and is therefore defined as an abstract class.
///
/// This class definition contains the highest level parts of the
/// class which is defined over a number of files</remarks>
public partial class WFF_GenericHID_Communication_Library
{
/// <summary>
/// Constructor
/// </summary>
/// <remarks>This constructor method creates an object for HID communication and attempts to find
/// (and bind to) the USB device indicated by the passed VID (Vendor ID) and PID (Product ID) which
/// should both be passed as unsigned integers.</remarks>
public WFF_GenericHID_Communication_Library(int vid, int pid)
{
Debug.WriteLine("WFF_GenericHID_Communication_Library:WFF_GenericHID_Communication_Library() -> Class constructor called");
// Set the deviceAttached flag to false
deviceInformation.deviceAttached = false;
// Store the target device's VID and PID in the device attributes
deviceInformation.targetVid = (UInt16)vid;
deviceInformation.targetPid = (UInt16)pid;
// Register for device notifications
registerForDeviceNotifications(this.Handle);
}
/// <summary>
/// Destructor
/// </summary>
/// <remarks>This method closes any open connections to the USB device and clears up any resources
/// that have been consumed over the lifetime of the object.</remarks>
~WFF_GenericHID_Communication_Library()
{
Debug.WriteLine("WFF_GenericHID_Communication_Library:WFF_GenericHID_Communication_Library() -> Class destructor called");
// Detach the USB device (performs required clean up operations)
detachUsbDevice();
}
/// <summary>
/// deviceAttributesStructure is used to represent the details of the target USB device as the methods
/// discover them so they can be reused by other methods when communicating with the device
/// </summary>
private struct deviceInformationStructure
{
public UInt16 targetVid; // Our target device's VID
public UInt16 targetPid; // Our target device's PID
public bool deviceAttached; // Device attachment state flag
public HIDD_ATTRIBUTES attributes; // HID Attributes
public HIDP_CAPS capabilities; // HID Capabilities
public SafeFileHandle readHandle; // Read handle from the device
public SafeFileHandle writeHandle; // Write handle to the device
public SafeFileHandle hidHandle; // Handle used for communicating via hid.dll
public String devicePathName; // The device's path name
public IntPtr deviceNotificationHandle; // The device's notification handle
}
/// <summary>
/// deviceAttributes contains the discovered attributes of the target USB device
/// </summary>
private deviceInformationStructure deviceInformation;
/// <summary>
/// Detach the USB device
/// </summary>
/// <remarks>This method detaches the USB device and frees the read and write handles
/// to the device.</remarks>
private void detachUsbDevice()
{
Debug.WriteLine("WFF_GenericHID_Communication_Library:detachUsbDevice() -> Method called");
// Is a device currently attached?
if (isDeviceAttached)
{
Debug.WriteLine("WFF_GenericHID_Communication_Library:detachUsbDevice() -> Detaching device and closing file handles");
// Set the device status to detached;
isDeviceAttached = false;
// Close the readHandle, writeHandle and hidHandle
if (!deviceInformation.hidHandle.IsInvalid) deviceInformation.hidHandle.Close();
if (!deviceInformation.readHandle.IsInvalid) deviceInformation.readHandle.Close();
if (!deviceInformation.writeHandle.IsInvalid) deviceInformation.writeHandle.Close();
// Throw an event
onUsbEvent(EventArgs.Empty);
}
else Debug.WriteLine("WFF_GenericHID_Communication_Library:detachUsbDevice() -> No device attached");
}
/// <summary>
/// Is device attached?
/// </summary>
/// <remarks>This method is used to set (private) or test (public) the device attachment status</remarks>
public bool isDeviceAttached
{
get
{
return deviceInformation.deviceAttached;
}
private set
{
deviceInformation.deviceAttached = value;
}
}
}
}
<file_sep>/FFmini_HID/FFmini_HID/src/AT_parser.c
#include "AT_parser.h"
const char ELM327_ID[] PROGMEM = "ELM327 v1.3";
const char FAKE_VOLTAGE[] PROGMEM = "12.6V";
const char FF_mini[] PROGMEM = "FFmini";
const char OBD_header[] PROGMEM = "686AF1";
const uint8_t hex_map[] PROGMEM = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46}; // For hex conversion
void send_ELM327_prompt()
{
//Serial_SendByte(0x3E); // Sends the '>' prompt
RingBuffer_Insert(&FFtoBT_Buffer,0x3E);
send_ELM327_CR();
}
void send_ELM327_OK()
{
//Serial_SendByte('O'); //
RingBuffer_Insert(&FFtoBT_Buffer,'O');
//Serial_SendByte('K'); //
RingBuffer_Insert(&FFtoBT_Buffer,'K');
send_ELM327_CR();
}
void send_ELM327_CR()
{
RingBuffer_Insert(&FFtoBT_Buffer,0x0D);
//Serial_SendByte(0x0D); // CR
}
void send_ELM327_header()
{
// ADD HEADERS
Serial_SendString_P(OBD_header);
//END HEADERS
}
// ****************************************************************************
// PARSE OBD BT COMMANDS
// ****************************************************************************
void parse_SER_buffer(uint8_t EGT_H, uint8_t EGT_L, uint8_t CHT_H, uint8_t CHT_L, uint32_t total_time_RPM)
{
uint8_t OBD_headers = 0;
uint16_t RPM_calc;
uint8_t temp_ringer;
uint8_t temp_mode;
uint16_t tempEGTCHT1;
uint16_t tempEGTCHT2;
uint8_t ascii_1;
uint8_t ascii_2;
uint8_t ascii_3;
uint8_t ascii_4;
if( (!(RingBuffer_IsEmpty(&BTtoFF_Buffer))))
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
if(temp_ringer == 'A')
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
if(temp_ringer == 'T') // We now have an AT command to parse
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
if(temp_ringer == 'Z') // Reset command, fake it
{
//Serial_SendString_P(ELM327_ID);
RingBuffer_Insert(&FFtoBT_Buffer,'E');
RingBuffer_Insert(&FFtoBT_Buffer,'L');
RingBuffer_Insert(&FFtoBT_Buffer,'M');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
RingBuffer_Insert(&FFtoBT_Buffer,'2');
RingBuffer_Insert(&FFtoBT_Buffer,'7');
RingBuffer_Insert(&FFtoBT_Buffer,0X20); // space
RingBuffer_Insert(&FFtoBT_Buffer,'v');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'.');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'E') // Echo Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'M') // Protocol Memory Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'L') // Line Feed Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'S') // Blank Spaces or Store Protocol Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
if(temp_ringer == 'H') // Set Header
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
}
else if(temp_ringer == 'P') // Set Protocol
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // 0 or 1
}
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'H') // Headers Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
if(temp_ringer == '1')
{
OBD_headers = 1;
}
else
{
OBD_headers = 0;
}
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'R') // Responses Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
if(temp_ringer == 'V')
{
//Serial_SendString_P(FAKE_VOLTAGE);
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'2');
RingBuffer_Insert(&FFtoBT_Buffer,'.');
RingBuffer_Insert(&FFtoBT_Buffer,'6');
RingBuffer_Insert(&FFtoBT_Buffer,'V');
send_ELM327_CR();
send_ELM327_prompt();
}
else
{
send_ELM327_OK();
send_ELM327_prompt();
}
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'V') // Variable DLC Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == '1') // ATAT1 Adaptive headers Command
{
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flagg
}
else if(temp_ringer == '@') // Blank Spaces Command
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
if(temp_ringer == '1') // Descriptor
{
//Serial_SendString_P(FF_mini);
RingBuffer_Insert(&FFtoBT_Buffer,'F');
RingBuffer_Insert(&FFtoBT_Buffer,'F');
RingBuffer_Insert(&FFtoBT_Buffer,'m');
RingBuffer_Insert(&FFtoBT_Buffer,'i');
RingBuffer_Insert(&FFtoBT_Buffer,'n');
RingBuffer_Insert(&FFtoBT_Buffer,'i');
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else
{
send_ELM327_OK();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
}
else if(temp_ringer == 'I') // ID Yourself command
{
//Serial_SendString_P(ELM327_ID);
RingBuffer_Insert(&FFtoBT_Buffer,'E');
RingBuffer_Insert(&FFtoBT_Buffer,'L');
RingBuffer_Insert(&FFtoBT_Buffer,'M');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
RingBuffer_Insert(&FFtoBT_Buffer,'2');
RingBuffer_Insert(&FFtoBT_Buffer,'7');
RingBuffer_Insert(&FFtoBT_Buffer,0X20); // space
RingBuffer_Insert(&FFtoBT_Buffer,'v');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'.');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
}
}
//***********************************************************
// Didnt find AT command, so look for OBD command
//***********************************************************
else if (temp_ringer == '0')
{
temp_mode = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_mode;
switch (temp_mode)
{
case '1': // Mode 01
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
if ((RingBuffer_Peek(&BTtoFF_Buffer)== '0'))
{
RingBuffer_Remove(&BTtoFF_Buffer); // Removes peeked value above
//SendSERBuffer[temp_USB_indexer++] = '0';
if(temp_ringer == '0') // What PIDS are supported 0100
{
//Serial_SendByte('4');
//Serial_SendByte('1');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
if(OBD_headers)
{
send_ELM327_header();
}
//Serial_SendByte('0');
//Serial_SendByte('0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
// Supported PIDS below
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('1'); // Support for RPM PID 0x0C
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if (temp_ringer == '2') // 0120, PIDS 21-40 supported bit mask
{
//Serial_SendByte('4');
//Serial_SendByte('1');
//Serial_SendByte('2');
//Serial_SendByte('0');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'2');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
// Supported PIDS below
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0'); // Support for EGT bank PID 0x78
//Serial_SendByte('1');
//Serial_SendByte('8');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'8');
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else // kind of assuming its asking for what we support
{
//Serial_SendByte('4');
//Serial_SendByte('1');
//Serial_SendByte(temp_ringer);
//Serial_SendByte('0');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,temp_ringer);
RingBuffer_Insert(&FFtoBT_Buffer,'0');
// Supported PIDS below
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
//Serial_SendByte('0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
send_ELM327_CR(); // CR
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
}
else if (temp_ringer == '0') // 010x
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
if(temp_ringer == 'C') // 010C
{
// RPM request
//if((!first_cycle)&&(total_time_RPM))
if(total_time_RPM)
{
// This takes the total_time = timer1_OVF + timer1_HIGH + timer1_LOW
// and converts to the format required for OBD msg
// AND IT NEEDS TO BE OPTIMIZED TOO LARGE!!
RPM_calc = (uint16_t)(((0xE4E1C000)/total_time_RPM));
ascii_4 = pgm_read_byte(&hex_map[RPM_calc&0x000F]);
RPM_calc >>=0x04;
ascii_3 = pgm_read_byte(&hex_map[RPM_calc&0x000F]);
RPM_calc >>=0x04;
ascii_2 = pgm_read_byte(&hex_map[RPM_calc&0x000F]);
RPM_calc >>=0x04;
ascii_1 = pgm_read_byte(&hex_map[RPM_calc&0x000F]);
}
else
{
// IDLE
ascii_1 = '0';
ascii_2 = '0';
ascii_3 = '0';
ascii_4 = '0';
}
//Serial_SendByte('4');
//Serial_SendByte('1');
//Serial_SendByte('0');
//Serial_SendByte('C');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'0');
RingBuffer_Insert(&FFtoBT_Buffer,'C');
//Serial_SendByte(ascii_1);
//Serial_SendByte(ascii_2);
//Serial_SendByte(ascii_3);
//Serial_SendByte(ascii_4);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_1);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_2);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_3);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_4);
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
}
else if (temp_ringer == '3')
{
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
//SendSERBuffer[temp_USB_indexer++] = temp_ringer;
if(temp_ringer == 'C')
{
// EGT request
if(EGT_L & 0x04)
{
// OPEN SENSOR
// All 0's is actually -40 in OBD
ascii_1 = '0';
ascii_2 = '0';
ascii_3 = '0';
ascii_4 = '0';
}
else
{
// This convert raw EGT and CHT into OBD format
tempEGTCHT1 = EGT_H;
tempEGTCHT1 = tempEGTCHT1<<8;
tempEGTCHT1 = tempEGTCHT1 + EGT_L;
tempEGTCHT1 &= 0x7FF8;
tempEGTCHT1 >>= 0x03;
tempEGTCHT2 = tempEGTCHT1;
tempEGTCHT1 = tempEGTCHT1<<1;
tempEGTCHT2 = tempEGTCHT2>>1;
tempEGTCHT1 = tempEGTCHT1 + tempEGTCHT2;
tempEGTCHT1 = tempEGTCHT1 + 400;
ascii_4 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_3 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_2 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_1 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
}
//Serial_SendByte('4');
//Serial_SendByte('1');
//Serial_SendByte('3');
//Serial_SendByte('C');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
RingBuffer_Insert(&FFtoBT_Buffer,'C');
//Serial_SendByte(ascii_1);
//Serial_SendByte(ascii_2);
//Serial_SendByte(ascii_3);
//Serial_SendByte(ascii_4);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_1);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_2);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_3);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_4);
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
else if(temp_ringer == 'D')
{
// CHT request
if(CHT_L & 0x04)
{
// OPEN SENSOR
// All 0's is actually -40 in OBD
ascii_1 = '0';
ascii_2 = '0';
ascii_3 = '0';
ascii_4 = '0';
}
else
{
// This convert raw EGT and CHT into OBD format
tempEGTCHT1 = CHT_H;
tempEGTCHT1 = tempEGTCHT1<<8;
tempEGTCHT1 = tempEGTCHT1 + CHT_L;
tempEGTCHT1 &= 0x7FF8;
tempEGTCHT1 >>= 0x03;
tempEGTCHT2 = tempEGTCHT1;
tempEGTCHT1 = tempEGTCHT1<<1;
tempEGTCHT2 = tempEGTCHT2>>1;
tempEGTCHT1 = tempEGTCHT1 + tempEGTCHT2;
tempEGTCHT1 = tempEGTCHT1 + 400;
ascii_4 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_3 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_2 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
tempEGTCHT1 >>=0x04;
ascii_1 = pgm_read_byte(&hex_map[tempEGTCHT1&0x000F]);
}
//Serial_SendByte('4');
//Serial_SendByte('1');
//Serial_SendByte('3');
//Serial_SendByte('D');
//Sensor #2 value
RingBuffer_Insert(&FFtoBT_Buffer,'4');
RingBuffer_Insert(&FFtoBT_Buffer,'1');
RingBuffer_Insert(&FFtoBT_Buffer,'3');
RingBuffer_Insert(&FFtoBT_Buffer,'D');
//Serial_SendByte(ascii_1);
//Serial_SendByte(ascii_2);
//Serial_SendByte(ascii_3);
//Serial_SendByte(ascii_4);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_1);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_2);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_3);
RingBuffer_Insert(&FFtoBT_Buffer,ascii_4);
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
}
}
break;
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
// We dont support these so respond accordingly
//Serial_SendByte('4');
RingBuffer_Insert(&FFtoBT_Buffer,'4');
//Serial_SendByte(temp_mode);
RingBuffer_Insert(&FFtoBT_Buffer,temp_mode);
//Serial_SendByte(RingBuffer_Remove(&BTtoFF_Buffer));
RingBuffer_Insert(&FFtoBT_Buffer,RingBuffer_Remove(&BTtoFF_Buffer));
//Serial_SendByte(RingBuffer_Remove(&BTtoFF_Buffer));
RingBuffer_Insert(&FFtoBT_Buffer,RingBuffer_Remove(&BTtoFF_Buffer));
send_ELM327_CR();
send_ELM327_prompt();
temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer); // PULLS CR out of buffer
CR_flag = 0; // Clears CR flag
break;
}
}
}
} // END PARSE_SER_BUFFER
<file_sep>/MiniGUI/WFF GenericHID Demo Application/mainForm.cs
//-----------------------------------------------------------------------------
//
// mainForm.cs
//
// WFF UDB GenericHID Demonstration Application (Version 4_0)
// A demonstration application for the WFF GenericHID Communication Library
//
//-----------------------------------------------------------------------------
// BAL ADDED MSG PARSING
// BAL Tested and the HB LED blinked
// BAL Added logging
//
// BAL Added EGT gauge and code for that. Ray visit.
// BAL 20 NOV 2015, this is what I am using. Seems to mostly work.
// BAL 15 APRIL 2016, still using this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.IO;
namespace WFF_GenericHID_Demo_Application
{
public partial class mainForm : Form
{
Label[] Testlabel = new Label[101];
public mainForm()
{
InitializeComponent();
FillMapPanel();
// FFmini test code uses Atmels test VID/PID VID=0x03EB and PID=0x2150
theUsbDemoDevice = new usbDemoDevice(0x03EB, 0x204F);
// Add a listener for usb events
theUsbDemoDevice.usbEvent += new usbDemoDevice.usbEventsHandler(usbEvent_receiver);
// Perform an initial search for the target USB device (in case
// it is already connected as we will not get an event for it)
theUsbDemoDevice.findTargetDevice();
}
// Create an instance of the USB reference device object
private usbDemoDevice theUsbDemoDevice;
private StreamWriter writer = new StreamWriter("c:\\BROOKS_TEMP\\LOGGER16APRIL2016.CSV");
// Create a listener for USB events
private void usbEvent_receiver(object o, EventArgs e)
{
// Check the status of the USB device and update the form accordingly
if (theUsbDemoDevice.isDeviceAttached)
{
// USB Device is currently attached
// Update the form's status label
this.usbDeviceStatusLabel.Text = "USB Device is attached";
}
else
{
// USB Device is currently unattached
// Update the form's status label
this.usbDeviceStatusLabel.Text = "USB Device is detached";
// Update the form
this.potStateLabel.Text = "0";
//this.potentiometerAnalogMeter.Value = 0;
this.TACH_GAUGE.Value = 0;
theUsbDemoDevice.TachState = 0;
theUsbDemoDevice.MANum = 0;
theUsbDemoDevice.MALNum = 0;
theUsbDemoDevice.MAHNum = 0;
theUsbDemoDevice.LOGState = false;
theUsbDemoDevice.Led2State = false;
theUsbDemoDevice.HBState = false;
theUsbDemoDevice.VRState = false;
this.LOGPictureBox.Image = Properties.Resources.red_off_16;
this.led2PictureBox.Image = Properties.Resources.red_off_16;
this.HBPictureBox.Image = Properties.Resources.red_off_16;
this.VRPictureBox.Image = Properties.Resources.red_off_16;
// Clear the debug window
this.debugTextBox.Clear();
}
}
// When the device status poll timer ticks we query the USB device for status
private void deviceStatusPollTimer_Tick(object sender, EventArgs e)
{
// Get the device's status
if (theUsbDemoDevice.isDeviceAttached)
{
if (theUsbDemoDevice.getDeviceStatus())
{
// Update the form
if (theUsbDemoDevice.LOGState == true) this.LOGPictureBox.Image = Properties.Resources.red_on_16;
else this.LOGPictureBox.Image = Properties.Resources.red_off_16;
if (theUsbDemoDevice.Led2State == true) this.led2PictureBox.Image = Properties.Resources.red_on_16;
else this.led2PictureBox.Image = Properties.Resources.red_off_16;
if (theUsbDemoDevice.HBState == true) this.HBPictureBox.Image = Properties.Resources.red_on_16;
else this.HBPictureBox.Image = Properties.Resources.red_off_16;
if (theUsbDemoDevice.VRState == true) this.VRPictureBox.Image = Properties.Resources.red_on_16;
else this.VRPictureBox.Image = Properties.Resources.red_off_16;
this.potStateLabel.Text = Convert.ToString(theUsbDemoDevice.TachState * 10);
this.TACH_GAUGE.Value = (float)(theUsbDemoDevice.TachState/100.0);
// MOVE THIS SOMEWHERE ELSE!!!!!!!!!!!
UInt16 temp_CHT;
UInt16 temp_EGT;
float tE;
float tC;
// ********************************** CHT ****************************************************
if ((theUsbDemoDevice.CHT_RAW & 0x0004) > 0)// 0xFFFF)
{
this.CHT_GAUGE.Value = 0;
CHT_txt.Text = "OPEN SENSOR";
}
else
{
temp_CHT = theUsbDemoDevice.CHT_RAW;
temp_CHT &= 0x7FF8;
temp_CHT >>= 0x03;
tC = (float)(((temp_CHT * 0.25) * 1.8) + 32.0);
this.CHT_GAUGE.Value = tC;
CHT_txt.Text = Convert.ToString(tC);
}
// ********************************** EGT ****************************************************
if ((theUsbDemoDevice.EGT_RAW & 0x0004) > 0) //== 0xFFFF)
{
this.EGT_GAUGE.Value = 0;
EGT_txt.Text = "OPEN SENSOR";
}
else
{
temp_EGT = theUsbDemoDevice.EGT_RAW;
temp_EGT &= 0x7FF8;
temp_EGT >>= 0x03;
//tE = (float)(temp_EGT / 4.0);
//tE = (float)((temp_EGT * 1.8) + 32.0);
tE = (float)(((temp_EGT * 0.25) * 1.8) + 32.0);
this.EGT_GAUGE.Value = tE;
EGT_txt.Text = Convert.ToString(tE);
}
// ********************************** RPM ****************************************************
RPM_txt.Text = Convert.ToString(theUsbDemoDevice.TachState*10);
this.MAPLabel.Text = Convert.ToString(theUsbDemoDevice.MapNum);
this.MODELabel.Text = Convert.ToString(theUsbDemoDevice.ModeNum);
switch (theUsbDemoDevice.MsgType)
{
case 1:
this.debugTextBox.AppendText("Data\r\n");
if (theUsbDemoDevice.LOGState == true)
{
// Currently logging RESET REG, MAP NUM, TACH STATE, MAL, MA, MAH
this.writer.WriteLine(Convert.ToString(theUsbDemoDevice.RESETReg) + "," + Convert.ToString(theUsbDemoDevice.CYCLECount) + "," + Convert.ToString(theUsbDemoDevice.MapNum) + "," + Convert.ToString(theUsbDemoDevice.TachState * 10) + "," + CHT_txt.Text + "," + EGT_txt.Text + "," + Convert.ToString(theUsbDemoDevice.MALNum) + "," + Convert.ToString(theUsbDemoDevice.MANum) + "," + Convert.ToString(theUsbDemoDevice.MAHNum) + ";");
//this.writer.WriteLine(Convert.ToString(theUsbDemoDevice.RESETReg) + "," + Convert.ToString(theUsbDemoDevice.CYCLECount) + "," + Convert.ToString(theUsbDemoDevice.MapNum) + "," + Convert.ToString(theUsbDemoDevice.TachState * 10) + "," + Convert.ToString(theUsbDemoDevice.MALNum) + "," + Convert.ToString(theUsbDemoDevice.MANum) + "," + Convert.ToString(theUsbDemoDevice.MAHNum) + "," + Convert.ToString(theUsbDemoDevice.YYCOUNT) + "," + Convert.ToString(Y1LOG) + "," + Convert.ToString(Y2LOG) + "," + Convert.ToString(Y3LOG) + "," + Convert.ToString(Y4LOG) + "," + Convert.ToString(Y5LOG) + "," + Convert.ToString(Y6LOG) + "," + Convert.ToString(Y7LOG) + "," + Convert.ToString(theUsbDemoDevice.PURPLECOUNT) + "," + Convert.ToString(P1LOG) + "," + Convert.ToString(P2LOG) + "," + Convert.ToString(P3LOG) + "," + Convert.ToString(P4LOG) + "," + Convert.ToString(P5LOG) + "," + Convert.ToString(P6LOG) + "," + Convert.ToString(theUsbDemoDevice.CHT_RAW) + ";");
}
break;
case 2:
if (theUsbDemoDevice.ModeNum == 3)//138)
{
this.debugTextBox.AppendText("Mode: LOAD LUT\r\n");
}
else if (theUsbDemoDevice.ModeNum == 4)//139)
{
this.debugTextBox.AppendText("Mode: READ LUT\r\n");
}
else if (theUsbDemoDevice.ModeNum == 5)//140)
{
this.debugTextBox.AppendText("Mode: LOAD FW\r\n");
}
else
{
this.debugTextBox.AppendText("Mode: UNKNOWN\r\n");
}
break;
case 3:
this.debugTextBox.AppendText("HeartBeat\r\n");
break;
case 4:
this.debugTextBox.AppendText("SERIAL\r\n");
break;
case 0x8A:
this.debugTextBox.AppendText("Write Map ACK\r\n");
if (theUsbDemoDevice.ModeNum < 11)
{
// Update progress bar
progressBar1.Value = (int)(theUsbDemoDevice.ModeNum * 10);
}
else
{
progressBar1.Value = 100;
LUTLOADbutton.Enabled = true;
LUTREADbutton.Enabled = true;
FWbutton.Enabled = true;
RUNbutton.Enabled = true;
progressBar1.Value = 0;
}
break;
case 0x8B:
this.debugTextBox.AppendText("Read Map ACK\r\n");
STATUpDown.Value = theUsbDemoDevice.STATMAPNum;
if (theUsbDemoDevice.READMapState < 11)
{
// Update progress bar
progressBar1.Value = (int)(theUsbDemoDevice.READMapState * 10);
}
else
{
progressBar1.Value = 100;
LUTLOADbutton.Enabled = true;
LUTREADbutton.Enabled = true;
FWbutton.Enabled = true;
RUNbutton.Enabled = true;
progressBar1.Value = 0;
}
break;
default:
this.debugTextBox.AppendText("!! BAD PACKET !!\r\n");
break;
}
}
}
}
private void LOGPictureBox_Click(object sender, EventArgs e)
{
// LOG LED clicked
if (theUsbDemoDevice.LOGState == false)
{
this.LOGPictureBox.Image = Properties.Resources.red_on_16;
theUsbDemoDevice.LOGState = true;
this.writer.WriteLine("RESETReg, CYCLECount, MapNum, RPM, CHT, IAT, TPS, EGT, MALNum, MANum, MAHNum, FILTERCount, FILTERMA1, FILTERRPM1, FILTERMA2, FILTERRPM2, FILTERMA3, FILTERRPM3, FILTERMA4, FILTERRPM4, FILTERMA5, FILTERRPM5, PURPLECOUNT, P1LOG, P2LOG, P3LOG, P4LOG, P5LOG, P6LOG ;");
}
else
{
this.writer.WriteLine("STOP LOG");
this.writer.Close();
this.LOGPictureBox.Image = Properties.Resources.red_off_16;
theUsbDemoDevice.LOGState = false;
}
}
private void LUTLOADbutton_Click(object sender, EventArgs e)
{
DialogResult LUTLOADyn;
if (theUsbDemoDevice.isDeviceAttached)
{
LUTLOADyn = MessageBox.Show("Are you sure you want to load this map to FF?\r\nIt will over write existing map.", "Confirm Map Load", MessageBoxButtons.YesNo);
if (LUTLOADyn == DialogResult.Yes)
{
LUTLOADbutton.Enabled = false;
LUTREADbutton.Enabled = false;
RUNbutton.Enabled = false;
FWbutton.Enabled = false;
// This starts the SEND MAP to FF sequence
theUsbDemoDevice.sendMAP(0x00);
}
}
else
{
LUTLOADyn = MessageBox.Show("Connect Firelfy and try again.", "Firefly not Attached", MessageBoxButtons.OK);
}
}
private void LUTREADbutton_Click(object sender, EventArgs e)
{
DialogResult LUTREADyn;
if (theUsbDemoDevice.isDeviceAttached)
{
LUTLOADbutton.Enabled = false;
LUTREADbutton.Enabled = false;
FWbutton.Enabled = false;
RUNbutton.Enabled = false;
LUTREADyn = MessageBox.Show("Are you sure you want to read the map from FF?\r\nAll unsaved IGN map data will be lost.", "Confirm Read Map", MessageBoxButtons.YesNo);
if (LUTREADyn == DialogResult.Yes)
{
theUsbDemoDevice.readMAP(0x00);
}
else
{
LUTLOADbutton.Enabled = true;
LUTREADbutton.Enabled = true;
FWbutton.Enabled = true;
RUNbutton.Enabled = true;
}
}
else
{
LUTREADyn = MessageBox.Show("Connect Firelfy and try again.","Firefly not Attached", MessageBoxButtons.OK);
}
}
private void FWbutton_Click(object sender, EventArgs e)
{
LUTLOADbutton.Enabled = true;
LUTREADbutton.Enabled = true;
FWbutton.Enabled = false;
theUsbDemoDevice.JUMPtoFW(0x8C);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//int size = -1;
StreamReader readerOPEN = null;
string stringReader;
string tempLOC;
string tempVALUE;
string tempCRC;
bool ReadMapError = false;
int i;
int indexC;
int indexV;
int indexer;
openFileDialog1.Filter = "FireFly Ign |*.fly";
openFileDialog1.Title = "Open a FireFly Map";
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
readerOPEN = new StreamReader(openFileDialog1.FileName);
if (readerOPEN != null)
{
using (readerOPEN)
{
// Insert code to read the stream here.
//Until reader.Peek = -1
while ((stringReader = readerOPEN.ReadLine()) != null)
{
//stringReader = readerOPEN.ReadLine();
if (stringReader.IndexOf("[#NOTE:", 0) != -1)
{
indexer = stringReader.IndexOf("END]", 0);
// the_notes = stringReader.Substring( 7, stringReader.Length - 13);
//MessageBox.Show(stringReader.Substring(7, stringReader.Length - 13));
}
else if (stringReader.IndexOf("[#STAT:", 0) != -1)
{
indexer = stringReader.IndexOf("END]", 0);
indexC = stringReader.IndexOf("C", 0);
STATUpDown.Value = Convert.ToUInt16(stringReader.Substring(7, indexC - 7));
//MessageBox.Show(stringReader.Substring(7, indexC - 7));
//TO DO: CHECK CRC VALUES
}
else if (stringReader.IndexOf("[#MAP:", 0) != -1)
{
indexer = stringReader.IndexOf("END]", 0);
indexC = stringReader.IndexOf("C", 0);
indexV = stringReader.IndexOf("V", 0);
tempLOC = stringReader.Substring(6, indexV - 6);
tempVALUE = stringReader.Substring(indexV + 1, indexC - indexV - 1);
tempCRC = stringReader.Substring(indexC + 1, indexer - indexC - 1);
ChartGlobalData.TestNum[Convert.ToUInt16(tempLOC)].Value = Convert.ToUInt16(tempVALUE);
//TO DO: CHECK CRC VALUES
//MsgBox(tempLOC & " " & tempVALUE & " " & tempCRC)
}
else
{
// MsgBox("ooops FILE READ")
MessageBox.Show("ooops FILE READ");
ReadMapError = true;
}
}
// Did this to assign value in cell# 100
//FIX ME!!!
ChartGlobalData.TestNum[100].Value = ChartGlobalData.TestNum[99].Value;
}
}
}
catch (Exception ex)
{
ReadMapError = true;
readerOPEN.Close();
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
if (ReadMapError == false)
{
for (i = 0; i < 101; i++)
{
Testlabel[i].Visible = true;
ChartGlobalData.TestNum[i].Visible = true;
ChartGlobalData.TestNum[i].ReadOnly = false;
}
chart1.Visible = true;
MAPpanel.Visible = true;
STATUpDown.Visible = true;
saveToolStripMenuItem.Enabled = true;
RUNbutton.Visible = true;
LUTLOADbutton.Visible = true;
LUTREADbutton.Visible = true;
TACH_GAUGE.Visible = false;
CHT_GAUGE.Visible = false;
EGT_GAUGE.Visible = false;
RPM_txt.Visible = false;
CHT_txt.Visible = false;
EGT_txt.Visible = false;
HBPictureBox.Visible = false;
VRPictureBox.Visible = false;
LOGPictureBox.Visible = false;
led2PictureBox.Visible = false;
label1.Visible = false;
label2.Visible = false;
label4.Visible = false;
label5.Visible = false;
label6.Visible = false;
label7.Visible = false;
label8.Visible = false;
label10.Visible = false;
potStateLabel.Visible = false;
MAPLabel.Visible = false;
MODELabel.Visible = false;
groupBox1.Text = "IGN MAP Edit";
}
}
// Console.WriteLine(size); // <-- Shows file size in debugging mode.
//Console.WriteLine(result); // <-- For debugging use only.
}
//**************************************************************************
private void FillMapPanel()
{
int i = 0;
Series seriesX;
for (i = 0; i < 101; i++)
{
Testlabel[i] = new System.Windows.Forms.Label();
this.MAPpanel.Controls.Add(Testlabel[i]);
Testlabel[i].AutoSize = true;
Testlabel[i].Location = new System.Drawing.Point(2, (26 * i) + 5);
Testlabel[i].Name = "TestLabel" + i.ToString();
Testlabel[i].Size = new System.Drawing.Size(13, 13);
Testlabel[i].TabIndex = 50 + i;
Testlabel[i].Text = i.ToString();
Testlabel[i].Visible = false;
//************************************************************************************
ChartGlobalData.TestNum[i] = new System.Windows.Forms.NumericUpDown();
this.MAPpanel.Controls.Add(ChartGlobalData.TestNum[i]);
ChartGlobalData.TestNum[i].Location = new System.Drawing.Point(21, (26 * i) + 3);
ChartGlobalData.TestNum[i].Name = "ChartGlobalData.TestNum" + i.ToString();
ChartGlobalData.TestNum[i].Size = new System.Drawing.Size(40, 40);
ChartGlobalData.TestNum[i].TabIndex = 80 + i;
ChartGlobalData.TestNum[i].ReadOnly = true;
ChartGlobalData.TestNum[i].ValueChanged += new System.EventHandler(TestNum_ValueChanged);
ChartGlobalData.TestNum[i].Visible = false;
}
//************************************************************************************
seriesX = new Series();
seriesX.Name = "Tester";
chart1.Series.Add(seriesX);
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 10000;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisX.MajorGrid.Interval = 1000;
chart1.ChartAreas[0].AxisY.MajorGrid.Interval = 1;
}
public void TestNum_ValueChanged(object sender, EventArgs e)
{
int i = 0;
chart1.Series["Tester"].Points.Clear();
chart1.ChartAreas[0].AxisX.MajorGrid.Interval = 1000;
chart1.ChartAreas[0].AxisY.MajorGrid.Interval = 1;
for (i = 0; i < 101; i++)
{
//chart1.Series["Tester"].Points.AddY(i);
chart1.Series["Tester"].Points.AddXY(i * 100, ChartGlobalData.TestNum[i].Value);
}
// Set series chart type
chart1.Series["Tester"].ChartType = SeriesChartType.Line;
chart1.Series["Tester"].Color = System.Drawing.Color.Red;
chart1.Series["Tester"].BorderWidth = 3;
// MessageBox.Show(((NumericUpDown)sender).Name.ToString());
}
private void RUNbutton_Click(object sender, EventArgs e)
{
int i;
DialogResult RUNyn;
RUNyn = MessageBox.Show("Are you sure you want to return to RUN mode? All unsaved IGN map data will be lost", "Return to RUN MODE?", MessageBoxButtons.YesNo);
if (RUNyn == DialogResult.Yes)
{
for (i = 0; i < 101; i++)
{
Testlabel[i].Visible = false;
ChartGlobalData.TestNum[i].Visible = false;
ChartGlobalData.TestNum[i].ReadOnly = true;
}
chart1.Visible = false;
MAPpanel.Visible = false;
STATUpDown.Visible = false;
saveToolStripMenuItem.Enabled = false;
RUNbutton.Visible = false;
LUTLOADbutton.Visible = false;
LUTREADbutton.Visible = false;
TACH_GAUGE.Visible = true;
CHT_GAUGE.Visible = true;
EGT_GAUGE.Visible = true;
RPM_txt.Visible = true;
CHT_txt.Visible = true;
EGT_txt.Visible = true;
HBPictureBox.Visible = true;
VRPictureBox.Visible = true;
LOGPictureBox.Visible = true;
led2PictureBox.Visible = true;
label1.Visible = true;
label2.Visible = true;
label4.Visible = true;
label5.Visible = true;
label6.Visible = true;
label7.Visible = true;
label8.Visible = true;
label10.Visible = true;
potStateLabel.Visible = true;
MAPLabel.Visible = true;
MODELabel.Visible = true;
groupBox1.Text = "FF Run Mode";
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
int i;
STATUpDown.Visible = true;
STATUpDown.Value = 18;
for (i = 0; i < 101; i++)
{
Testlabel[i].Visible = true;
ChartGlobalData.TestNum[i].Visible = true;
ChartGlobalData.TestNum[i].ReadOnly = false;
ChartGlobalData.TestNum[i].Value = STATUpDown.Value - 1;
}
chart1.Visible = true;
MAPpanel.Visible = true;
saveToolStripMenuItem.Enabled = true;
RUNbutton.Visible = true;
LUTLOADbutton.Visible = true;
LUTREADbutton.Visible = true;
TACH_GAUGE.Visible = false;
CHT_GAUGE.Visible = false;
EGT_GAUGE.Visible = false;
RPM_txt.Visible = false;
CHT_txt.Visible = false;
EGT_txt.Visible = false;
HBPictureBox.Visible = false;
VRPictureBox.Visible = false;
LOGPictureBox.Visible = false;
led2PictureBox.Visible = false;
label1.Visible = false;
label2.Visible = false;
label4.Visible = false;
label5.Visible = false;
label6.Visible = false;
label7.Visible = false;
label8.Visible = false;
label10.Visible = false;
potStateLabel.Visible = false;
MAPLabel.Visible = false;
MODELabel.Visible = false;
editToolStripMenuItem.Enabled = true;
groupBox1.Text = "IGN MAP Edit";
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
int i;
saveFileDialog1.Filter = "FireFly Ign |*.fly";
saveFileDialog1.Title = "Save a FireFly Map";
saveFileDialog1.FileName = "";
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
// If the file name is not an empty string open it for saving.
if( saveFileDialog1.FileName != null )
{
StreamWriter writerSAVE= new StreamWriter(saveFileDialog1.FileName);
writerSAVE.Write("[#NOTE:" + "ADD NOTES HERE" + "C8END]");
writerSAVE.WriteLine("");
writerSAVE.Write("[#STAT:" + Convert.ToString(STATUpDown.Value) + "C8END]");
writerSAVE.WriteLine("");
for (i=0;i<101;i++)
{
writerSAVE.Write("[#MAP:" + Convert.ToString(i ) + "V" + Convert.ToString(ChartGlobalData.TestNum[i].Value) + "C8END]");
writerSAVE.WriteLine("");
progressBar1.Value = i;
}
try
{
writerSAVE.Close();
}
catch (Exception ex)
{
MessageBox.Show("Could not close file.", "File save error", MessageBoxButtons.OK);
}
}
}
}
private void STATUpDown_ValueChanged(object sender, EventArgs e)
{
uint i;
uint temp_min;
//DAMN!! Gotta update all the min/max values for the table.
for (i = 0; i < 101; i++)
{
ChartGlobalData.TestNum[i].Maximum = STATUpDown.Value - 1;
if (i > 0)
{
temp_min = 65536 / (26667 / i);
if (temp_min > 0)
{
if (STATUpDown.Value > temp_min)
{
ChartGlobalData.TestNum[i].Minimum = STATUpDown.Value - temp_min;
}
else
{
ChartGlobalData.TestNum[i].Minimum = 0;
}
}
}
else
{
ChartGlobalData.TestNum[i].Minimum = STATUpDown.Value - 1;
}
}
ChartGlobalData.TestNum[0].Minimum = STATUpDown.Value - 1;
theUsbDemoDevice.STATMAPNum = (Byte)STATUpDown.Value;
}
private void blockFillToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("TO DO!!!", "ADD BLOCK FILL", MessageBoxButtons.OK);
}
private void mapNotesToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("TO DO!!!", "ADD MAP NOTES", MessageBoxButtons.OK);
}
//**********************************************************************************
}
public class ChartGlobalData
{
public static NumericUpDown[] TestNum = new NumericUpDown[101];
}
}
<file_sep>/FFmini_HID/FFmini_HID/src/EXT.h
// External Interrupt header file
void EXT_INT_init(void);
<file_sep>/MiniGUI/WFF GenericHID Demo Application/usbDemoDevice.cs
//-----------------------------------------------------------------------------
//
// usbDemoDevice.cs
//
// WFF UDB GenericHID Demonstration Application (Version 4_0)
// A demonstration application for the WFF GenericHID Communication Library
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Demo_Application
{
using WFF_GenericHID_Communication_Library;
class usbDemoDevice : WFF_GenericHID_Communication_Library
{
// Class constructor - place any initialisation here
public usbDemoDevice(int vid, int pid) : base(vid, pid)
{
// Initialise the local copy of the device's state
deviceState.LOG_LED_State = false;
deviceState.led2State = false;
deviceState.HB_LED_State = false;
deviceState.VR_LED_State = false;
deviceState.tachState = 0;
deviceState.msgType = 0x00;
deviceState.readMapState = 0x00;
deviceState.statMAPNum = 0x00;
deviceState.mapNum = 0x00;
deviceState.modeNum = 0x00;
deviceState.maNum = 0x00;
deviceState.maLNum = 0x00;
deviceState.maHNum = 0x00;
deviceState.resetReg = 0x00;
deviceState.cycleCount = 0x00;
deviceState.CHT_raw = 0;
deviceState.EGT_raw = 0;
}
// Methods to store and access a local copy of the device's state
// Initialise the local copy of the device's state
private struct deviceStateStruct
{
public Boolean LOG_LED_State;
public Boolean led2State;
public Boolean HB_LED_State;
public Boolean VR_LED_State;
public UInt32 tachState;
public Byte msgType;
public Byte readMapState;
public Byte statMAPNum;
public Byte mapNum;
public Byte modeNum;
public Byte maNum;
public Byte maLNum;
public Byte maHNum;
public Byte resetReg;
public Byte cycleCount;
public UInt16 CHT_raw;
public UInt16 EGT_raw;
}
// Create a game state object
private deviceStateStruct deviceState;
// Accessor classes for the device's state values
public Boolean LOGState
{
get { return deviceState.LOG_LED_State; }
set { deviceState.LOG_LED_State = value; }
}
public Boolean Led2State
{
get { return deviceState.led2State; }
set { deviceState.led2State = value; }
}
public Boolean HBState
{
get { return deviceState.HB_LED_State; }
set { deviceState.HB_LED_State = value; }
}
public Boolean VRState
{
get { return deviceState.VR_LED_State; }
set { deviceState.VR_LED_State = value; }
}
public UInt32 TachState
{
get { return deviceState.tachState; }
set { deviceState.tachState = value; }
}
public UInt32 MsgType
{
get { return deviceState.msgType; }
set { deviceState.msgType = (byte)value; }
}
public UInt32 READMapState
{
get { return deviceState.readMapState; }
set { deviceState.readMapState = (byte)value; }
}
public UInt32 STATMAPNum
{
get { return deviceState.statMAPNum; }
set { deviceState.statMAPNum = (byte)value; }
}
public UInt32 MapNum
{
get { return deviceState.mapNum; }
set { deviceState.mapNum = (byte)value; }
}
public UInt32 ModeNum
{
get { return deviceState.modeNum; }
set { deviceState.modeNum = (byte)value; }
}
public UInt32 MANum
{
get { return deviceState.maNum; }
set { deviceState.maNum = (byte)value; }
}
public UInt32 MALNum
{
get { return deviceState.maLNum; }
set { deviceState.maLNum = (byte)value; }
}
public UInt32 MAHNum
{
get { return deviceState.maHNum; }
set { deviceState.maHNum = (byte)value; }
}
public UInt32 RESETReg
{
get { return deviceState.resetReg; }
set { deviceState.resetReg = (byte)value; }
}
public UInt32 CYCLECount
{
get { return deviceState.cycleCount; }
set { deviceState.cycleCount = (byte)value; }
}
public UInt16 CHT_RAW
{
get { return deviceState.CHT_raw; }
set { deviceState.CHT_raw = value; }
}
public UInt16 EGT_RAW
{
get { return deviceState.EGT_raw; }
set { deviceState.EGT_raw = value; }
}
//*****************************************************************************
//*****************************************************************************
// Code to send commands to the device ----------
public bool getDeviceStatus()
{
// Declare our input buffer
//14MAY2014 64 to 32 Byte[] inputBuffer = new Byte[64];
Byte[] inputBuffer = new Byte[32];
bool success;
uint TotalTime = 0;
uint CompATime = 0;
uint CompBTime = 0;
uint MA = 0;
uint MAL = 0;
uint MAH = 0;
uint RPM_Calc = 0;
uint RPM_Ret = 0;
UInt16 tempMAP_RAW;
UInt16 tempMAP_LOC;
UInt16 tempMAP_CHART;
byte temp_MAP_STAT;
double temp_CONVERT;
uint i;
uint temp_min;
// Perform the read
success = readSingleReportFromDevice(ref inputBuffer);
// Was the read successful?
if (!success) return false;
// Time to parse the MSG
// Check header and footer
//if ((inputBuffer[0] == 0xAB) && (inputBuffer[1] == 0xCD) && (inputBuffer[61] == 0xDE) && (inputBuffer[62] == 0xAD))
if ((inputBuffer[0] == 0xAB) && (inputBuffer[1] == 0xCD) )
{
// Get the MSG type
switch (inputBuffer[2])
{
case 0x01: // Data Packet
TotalTime = (uint)((inputBuffer[5] << 16) + (inputBuffer[3] << 8) + inputBuffer[4]);
CompATime = (uint)((inputBuffer[6] << 8) + inputBuffer[7]);
CompBTime = (uint)((inputBuffer[8] << 8) + inputBuffer[9]);
if (TotalTime > 0)
{
RPM_Calc = (60 * (16000000 / TotalTime));
RPM_Ret = (uint)(inputBuffer[10] * 100);
// Toggle VR LED
if (deviceState.VR_LED_State == true) { deviceState.VR_LED_State = false; }
else { deviceState.VR_LED_State = true; }
}
else { deviceState.VR_LED_State = false; }
deviceState.tachState = RPM_Calc / 10;
deviceState.msgType = 0x01;
deviceState.EGT_raw = (UInt16)((inputBuffer[16] << 8) + inputBuffer[17]);
deviceState.CHT_raw = (UInt16)((inputBuffer[18] << 8) + inputBuffer[19]);
deviceState.maNum = inputBuffer[12];
deviceState.maLNum = inputBuffer[13];
deviceState.maHNum = inputBuffer[14];
deviceState.cycleCount = inputBuffer[15];
deviceState.mapNum = inputBuffer[20];
//Debug.WriteLine("RPM CALC: " + Convert.ToString(RPM_Calc) + " RPM RET: " + Convert.ToString(RPM_Ret) + " TT: " + Convert.ToString(TotalTime) + " MA: " + Convert.ToString(MA) + " MAL: " + Convert.ToString(MAL) + " MAH: " + Convert.ToString(MAH));
Debug.WriteLine("RPM CALC: " + Convert.ToString(RPM_Calc) + " RPM RET: " + Convert.ToString(RPM_Ret) + " TT: " + Convert.ToString(TotalTime) + " COMPA: " + Convert.ToString(CompATime) + " COMPB: " + Convert.ToString(CompBTime));
break;
case 0x02: // MODE packet
deviceState.modeNum = inputBuffer[11];
deviceState.msgType = 0x02;
Debug.WriteLine("MODE: " + Convert.ToString(inputBuffer[11]));
break;
case 0x03: // Heart Beat
// Nothing important in HB MSG, just toggle HB LED
if (deviceState.HB_LED_State == true)
{
deviceState.HB_LED_State = false;
}
else
{
deviceState.HB_LED_State = true;
}
deviceState.msgType = 0x03;
deviceState.mapNum = inputBuffer[20];
deviceState.resetReg = inputBuffer[21];
deviceState.EGT_raw = (UInt16)((inputBuffer[16] << 8) + inputBuffer[17]);
deviceState.CHT_raw = (UInt16)((inputBuffer[18] << 8) + inputBuffer[19]);
Debug.WriteLine("HeartBeat");
break;
case 0x04: // Serial Stream
deviceState.msgType = 0x04;
Debug.WriteLine("SER:");
for (int tempi = 3; tempi < inputBuffer[30]; tempi++)
{
Debug.Write(Convert.ToChar( inputBuffer[tempi]));
}
Debug.Write("\r\n");
break;
//******************************************************************************************************
case 0x8A: //sendMAP
deviceState.modeNum = (byte)((inputBuffer[3] & 0x7F));
deviceState.msgType = 0x8A;
Debug.WriteLine("SEQ NUM:" + Convert.ToString(deviceState.modeNum));
++deviceState.modeNum;
//deviceState.writeMapState = deviceState.modeNum;
// 0 to start
// 1 for 0-24
// 2 for 25-49
// 3 for 50-74
// 4 for 75-99
//14MAY2014 64 to 32 if (deviceState.modeNum < 5)
if (deviceState.modeNum < 11)
{
sendMAP(deviceState.modeNum);
}
else
{
// Reset FF
Debug.WriteLine("WRITE DONE. NEED TO RESET FF!!");
resetFF();
}
break;
//******************************************************************************************************
case 0x8B: //readMAP
deviceState.modeNum = (byte)((inputBuffer[3]& 0x7F));
deviceState.msgType = 0x8B;
Debug.WriteLine("SEQ NUM:" + Convert.ToString(deviceState.modeNum));
if (deviceState.modeNum != 0)
{
temp_MAP_STAT = inputBuffer[29];
deviceState.statMAPNum = temp_MAP_STAT;
//DAMN!! Gotta update all the min/max values for the table. Fuck
for (i = 0; i < 101; i++)
{
ChartGlobalData.TestNum[i].Maximum = temp_MAP_STAT - 1;
if (i > 0)
{
temp_min = 65536 / (26667 / i);
if (temp_min > 0)
{
if (temp_MAP_STAT > temp_min)
{
ChartGlobalData.TestNum[i].Minimum = temp_MAP_STAT - temp_min;
}
else
{
ChartGlobalData.TestNum[i].Minimum = 0;
}
}
}
else
{
ChartGlobalData.TestNum[i].Minimum= temp_MAP_STAT - 1;
}
}
ChartGlobalData.TestNum[0].Minimum = temp_MAP_STAT - 1;
//14MAY2014 64 to 32 for (i = 4; i < 54; i++)
for (i = 4; i < 24; i++)
{
// Covert 2 bytes to 16 bit integer
tempMAP_RAW = (UInt16)((inputBuffer[i] << 8) + inputBuffer[i + 1]);
//14MAY2014 64 to 32 tempMAP_LOC = (UInt16)(((i / 2) - 2)+ ((deviceState.modeNum - 1)*25)) ;
tempMAP_LOC = (UInt16)(((i / 2) - 2) + ((deviceState.modeNum - 1) * 10));
if (tempMAP_LOC == 0)
{
temp_CONVERT = (((600.0 * (1) * tempMAP_RAW) / 16000000.0) + 0.5);
}
else
{
temp_CONVERT = (((600.0 * (tempMAP_LOC) * tempMAP_RAW) / 16000000.0) + 0.5);
}
//temp_CONVERT = (((600.0 * (tempMAP_LOC) * tempMAP_RAW) / 16000000.0) + 0.5);
tempMAP_CHART = (UInt16)(temp_CONVERT);// (((600 * (tempMAP_LOC) * tempMAP_RAW) / 16000000) + 0.5);
ChartGlobalData.TestNum[tempMAP_LOC].Value = temp_MAP_STAT - tempMAP_CHART;
i++;
Debug.WriteLine(Convert.ToString(tempMAP_LOC) + ": " + Convert.ToString(tempMAP_RAW) + " : " + Convert.ToString(temp_MAP_STAT) + " : " + Convert.ToString(tempMAP_CHART) + " : " + Convert.ToString(ChartGlobalData.TestNum[tempMAP_LOC].Value));
}
}
else
{
Debug.WriteLine("ReadMAP start MSG ACK received");
}
++deviceState.modeNum;
deviceState.readMapState = deviceState.modeNum;
if (deviceState.modeNum < 11)
{
readMAP(deviceState.modeNum);
}
else
{
// Reset FF
Debug.WriteLine("READ DONE. NEED TO RESET FF!!");
resetFF();
}
break;
default:
deviceState.msgType = 0xFF;
Debug.WriteLine("UNKNOWN PACKET");
break;
}
}
else
{
Debug.WriteLine("BAD PACKET");
}
success = true;
// The data was sent and received ok!
return success;
}
// *********************************************************************************************
// *********************************************************************************************
public bool sendMAP(byte SEQ)
{
UInt16 tempMAP_RAW;
UInt16 tempMAP_LOC;
UInt16 tempMAP_CHART;
byte temp_MAP_STAT = deviceState.statMAPNum;// 31;
double temp_CONVERT;
uint i;
Debug.WriteLine("Demo Application -> Sending MAP to FF" );
// Declare our output buffer
//14MAY2014 64 to 32 Byte[] outputBuffer = new Byte[64];
Byte[] outputBuffer = new Byte[32];
outputBuffer[0] = 0xAB;
outputBuffer[1] = 0xCD;
outputBuffer[2] = 0x8A;
outputBuffer[3] = SEQ; // First packet of sequence
/*14MAY2014 64 to 32
outputBuffer[60] = deviceState.statMAPNum;
outputBuffer[62] = 0xDE;
outputBuffer[63] = 0xAD;*/
outputBuffer[29] = deviceState.statMAPNum;
outputBuffer[30] = 0xDE;
outputBuffer[31] = 0xAD;
// Get the values from the chart
if (SEQ > 0)
{
//14MAY2014 64 to 32 for (i = 4; i < 54; i++)
for (i = 4; i < 24; i++)
{
//14MAY2014 64 to 32 tempMAP_LOC = (UInt16)(((i / 2) - 2) + ((SEQ - 1) * 25));
tempMAP_LOC = (UInt16)(((i / 2) - 2) + ((SEQ - 1) * 10));
tempMAP_CHART = (UInt16) (temp_MAP_STAT - ChartGlobalData.TestNum[tempMAP_LOC].Value);
if (tempMAP_LOC == 0)
{
//temp_CONVERT = 30000;
temp_CONVERT = (16000000.0 * tempMAP_CHART) / (600.0 * 1);
}
else
{
temp_CONVERT = (16000000.0 * tempMAP_CHART) / (600.0 * tempMAP_LOC);
}
tempMAP_RAW = Convert.ToUInt16(temp_CONVERT);
outputBuffer[i] = (byte)((tempMAP_RAW & 0xFF00) >> 8); // MSB
outputBuffer[i+1] = (byte)(tempMAP_RAW & 0x00FF); // LSB
Debug.WriteLine("MAP SEND " + Convert.ToString(tempMAP_LOC) + ": " + Convert.ToString(tempMAP_RAW) + " : " + Convert.ToString(outputBuffer[i]) + " : " + Convert.ToString(outputBuffer[i+1]));
++i;
}
}
// Perform the write command
bool success;
success = writeSingleReportToDevice(outputBuffer);
return success;
}
public bool readMAP(byte SEQ)
{
Debug.WriteLine("Demo Application -> Reading MAP from FF ");
// Declare our output buffer
//14MAY2014 64 to 32 Byte[] outputBuffer = new Byte[64];
Byte[] outputBuffer = new Byte[32];
outputBuffer[0] = 0xAB;
outputBuffer[1] = 0xCD;
outputBuffer[2] = 0x8B; // Send Mode #
outputBuffer[3] = SEQ;
//outputBuffer[30] = 0xDE; //outputBuffer[62] = 0xDE;
//outputBuffer[31] = 0xAD; //outputBuffer[63] = 0xAD;
// Perform the write command
bool success;
success = writeSingleReportToDevice(outputBuffer);
return success;
}
public bool JUMPtoFW(Byte modenumber)
{
Debug.WriteLine("Demo Application -> Sending set device MODE number: " + Convert.ToString(modenumber));
// Declare our output buffer
//14MAY2014 64 to 32 Byte[] outputBuffer = new Byte[64];
Byte[] outputBuffer = new Byte[32];
outputBuffer[0] = 0xAB;
outputBuffer[1] = 0xCD;
outputBuffer[2] = 0x8C;// modenumber; // Send Mode #
outputBuffer[3] = 0x00; // First packet of sequence
outputBuffer[30] = 0xDE; //outputBuffer[62] = 0xDE;
outputBuffer[31] = 0xAD; //outputBuffer[63] = 0xAD;
// Perform the write command
bool success;
success = writeSingleReportToDevice(outputBuffer);
return success;
}
public bool resetFF()
{
Debug.WriteLine("Demo Application -> Resetting the FF ");
// Declare our output buffer
//14MAY2014 64 to 32 Byte[] outputBuffer = new Byte[64];
Byte[] outputBuffer = new Byte[32];
outputBuffer[0] = 0xAB;
outputBuffer[1] = 0xCD;
outputBuffer[2] = 0x8F; // Reset FF
//outputBuffer[3] = SEQ;
//outputBuffer[30] = 0xDE; //outputBuffer[62] = 0xDE;
//outputBuffer[31] = 0xAD; //outputBuffer[63] = 0xAD;
// Perform the write command
bool success;
success = writeSingleReportToDevice(outputBuffer);
return success;
}
// *********************************************************************************************
// *********************************************************************************************
}
}
<file_sep>/README.md
# FireFly
The digital ignition controller, called the FireFly Mini, uses the stock Variable Reluctor (VR) pickup and is the typical retard only system. Also includes (2) K-type thermocouple inputs for Exhaust Gas Temperature (EGT) and Cylinder Head Temperature (CHT) monitoring. The goal is to provide a programmable ignition controller that dynamically adjusts based on EGT and CHT values. A Windows program allows you to customize ignition curves over USB; log RPM, CHT, and EGT values; and flash the firmware. You can save maps, read the map that is loaded,etc. I've also created an basic android app that displays the RPM, CHT, and EGT values. In addition, the FF mini simulates the popular OBDII ELM327 interface. This allows my old Vespa to have an "OBD II ecu", allowing you to take advantage of the many ELM327 based apps available. My personal favorite is the Torque app.
The GUI was developed using Microsoft Visual C# 2010 and relies heavily on the Generic HID program and contains portions of the WFF GenericHID Communication Library which is (c)2011 <NAME> - http://www.waitingforfriday.com
The Eagle schematics and board files are provided, along with the BOM, and the Gerbers. The circuit card was designed to fit into a Polycase LP-11F enclosure. The design uses an atmega16u2 and the source code was developed in Atmel Studio 6.1. The USB stack is based on the LUFA USB Library.
http://www.fourwalledcubicle.com/LUFA.php
<file_sep>/FFmini_HID/FFmini_HID/src/TIMERS.h
void TIMER0_init(void);
void TIMER1_init(void);
<file_sep>/MiniGUI/WFF GenericHID Communication Library/deviceDiscovery.cs
//-----------------------------------------------------------------------------
//
// deviceDiscovery.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Communication_Library
{
public partial class WFF_GenericHID_Communication_Library
{
/// <summary>
/// Find all devices with the HID GUID attached to the system
/// </summary>
/// <remarks>This method searches for all devices that have the correct HID GUID and
/// returns an array of matching device paths</remarks>
private bool findHidDevices(ref String[] listOfDevicePathNames, ref int numberOfDevicesFound)
{
Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Method called");
// Detach the device if it's currently attached
if (isDeviceAttached) detachUsbDevice();
// Initialise the internal variables required for performing the search
Int32 bufferSize = 0;
IntPtr detailDataBuffer = IntPtr.Zero;
Boolean deviceFound;
IntPtr deviceInfoSet = new System.IntPtr();
Boolean lastDevice = false;
Int32 listIndex = 0;
SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
Boolean success;
// Get the required GUID
System.Guid systemHidGuid = new Guid();
HidD_GetHidGuid(ref systemHidGuid);
Debug.WriteLine(string.Format("usbGenericHidCommunication:findHidDevices() -> Fetched GUID for HID devices ({0})", systemHidGuid.ToString()));
try
{
// Here we populate a list of plugged-in devices matching our class GUID (DIGCF_PRESENT specifies that the list
// should only contain devices which are plugged in)
Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Using SetupDiGetClassDevs to get all devices with the correct GUID");
deviceInfoSet = SetupDiGetClassDevs(ref systemHidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
// Reset the deviceFound flag and the memberIndex counter
deviceFound = false;
listIndex = 0;
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
// Look through the retrieved list of class GUIDs looking for a match on our interface GUID
do
{
//Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Enumerating devices");
success = SetupDiEnumDeviceInterfaces
(deviceInfoSet,
IntPtr.Zero,
ref systemHidGuid,
listIndex,
ref deviceInterfaceData);
if (!success)
{
//Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> No more devices left - giving up");
lastDevice = true;
}
else
{
// The target device has been found, now we need to retrieve the device path so we can open
// the read and write handles required for USB communication
// First call is just to get the required buffer size for the real request
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
IntPtr.Zero,
0,
ref bufferSize,
IntPtr.Zero);
// Allocate some memory for the buffer
detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
Marshal.WriteInt32(detailDataBuffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);
// Second call gets the detailed data buffer
//Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> Getting details of the device");
success = SetupDiGetDeviceInterfaceDetail
(deviceInfoSet,
ref deviceInterfaceData,
detailDataBuffer,
bufferSize,
ref bufferSize,
IntPtr.Zero);
// Skip over cbsize (4 bytes) to get the address of the devicePathName.
IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt32() + 4);
// Get the String containing the devicePathName.
listOfDevicePathNames[listIndex] = Marshal.PtrToStringAuto(pDevicePathName);
//Debug.WriteLine(string.Format("usbGenericHidCommunication:findHidDevices() -> Found matching device (memberIndex {0})", memberIndex));
deviceFound = true;
}
listIndex = listIndex + 1;
}
while (!((lastDevice == true)));
}
catch (Exception)
{
// Something went badly wrong... output some debug and return false to indicated device discovery failure
Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> EXCEPTION: Something went south whilst trying to get devices with matching GUIDs - giving up!");
return false;
}
finally
{
// Clean up the unmanaged memory allocations
if (detailDataBuffer != IntPtr.Zero)
{
// Free the memory allocated previously by AllocHGlobal.
Marshal.FreeHGlobal(detailDataBuffer);
}
if (deviceInfoSet != IntPtr.Zero)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
}
if (deviceFound)
{
Debug.WriteLine(string.Format("usbGenericHidCommunication:findHidDevices() -> Found {0} devices with matching GUID", listIndex - 1));
numberOfDevicesFound = listIndex - 2;
}
else Debug.WriteLine("usbGenericHidCommunication:findHidDevices() -> No matching devices found");
return deviceFound;
}
/// <summary>
/// Find the target device based on the VID and PID
/// </summary>
/// <remarks>This method used the 'findHidDevices' to fetch a list of attached HID devices
/// then it searches through the list looking for a HID device with the correct VID and
/// PID</remarks>
public void findTargetDevice()
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Method called");
bool deviceFoundByGuid = false;
String[] listOfDevicePathNames = new String[128]; // 128 is the maximum number of USB devices allowed on a single host
int listIndex = 0;
bool success = false;
bool isDeviceDetected;
int numberOfDevicesFound = 0;
try
{
// Reset the device detection flag
isDeviceDetected = false;
// Get all the devices with the correct HID GUID
deviceFoundByGuid = findHidDevices(ref listOfDevicePathNames, ref numberOfDevicesFound);
if (deviceFoundByGuid)
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Devices with matching GUID found...");
listIndex = 0;
do
{
Debug.WriteLine(string.Format("usbGenericHidCommunication:findTargetDevice() -> Performing CreateFile to listIndex {0}", listIndex));
deviceInformation.hidHandle = CreateFile(listOfDevicePathNames[listIndex], 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, 0);
if (!deviceInformation.hidHandle.IsInvalid)
{
deviceInformation.attributes.size = Marshal.SizeOf(deviceInformation.attributes);
success = HidD_GetAttributes(deviceInformation.hidHandle, ref deviceInformation.attributes);
if (success)
{
Debug.WriteLine(string.Format("usbGenericHidCommunication:findTargetDevice() -> Found device with VID {0}, PID {1} and Version number {2}",
Convert.ToString(deviceInformation.attributes.vendorId, 16),
Convert.ToString(deviceInformation.attributes.productId, 16),
Convert.ToString(deviceInformation.attributes.versionNumber, 16)));
// Do the VID and PID of the device match our target device?
if ((deviceInformation.attributes.vendorId == deviceInformation.targetVid) &&
(deviceInformation.attributes.productId == deviceInformation.targetPid))
{
// Matching device found
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Device with matching VID and PID found!");
isDeviceDetected = true;
// Store the device's pathname in the device information
deviceInformation.devicePathName = listOfDevicePathNames[listIndex];
}
else
{
// Wrong device, close the handle
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Device didn't match... Continuing...");
isDeviceDetected = false;
deviceInformation.hidHandle.Close();
}
}
else
{
// Something went rapidly south... give up!
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Something bad happened - couldn't fill the HIDD_ATTRIBUTES, giving up!");
isDeviceDetected = false;
deviceInformation.hidHandle.Close();
}
}
// Move to the next device, or quit if there are no more devices to examine
listIndex++;
}
while (!((isDeviceDetected || (listIndex == numberOfDevicesFound + 1))));
}
// If we found a matching device then we need discover more details about the attached device
// and then open read and write handles to the device to allow communication
if (isDeviceDetected)
{
// Query the HID device's capabilities (primarily we are only really interested in the
// input and output report byte lengths as this allows us to validate information sent
// to and from the device does not exceed the devices capabilities.
//
// We could determine the 'type' of HID device here too, but since this class is only
// for generic HID communication we don't care...
queryDeviceCapabilities();
if (success)
{
// Open the readHandle to the device
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Opening a readHandle to the device");
deviceInformation.readHandle = CreateFile(
deviceInformation.devicePathName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
// Did we open the readHandle successfully?
if (deviceInformation.readHandle.IsInvalid)
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Unable to open a readHandle to the device!");
}
else
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Opening a writeHandle to the device");
deviceInformation.writeHandle = CreateFile(
deviceInformation.devicePathName,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
0,
0);
// Did we open the writeHandle successfully?
if (deviceInformation.writeHandle.IsInvalid)
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> Unable to open a writeHandle to the device!");
// Attempt to close the writeHandle
deviceInformation.writeHandle.Close();
}
else
{
// Device is now discovered and ready for use, update the status
isDeviceAttached = true;
onUsbEvent(EventArgs.Empty); // Throw an event
}
}
}
}
else
{
// The device wasn't detected.
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> No matching device found!");
}
}
catch (Exception)
{
Debug.WriteLine("usbGenericHidCommunication:findTargetDevice() -> EXCEPTION: Unknown - device not found");
isDeviceDetected = false;
}
}
/// <summary>
/// queryDeviceCapabilities - Used the hid.dll function to query the capabilities
/// of the target device.
/// </summary>
private void queryDeviceCapabilities()
{
IntPtr preparsedData = new System.IntPtr();
Int32 result = 0;
Boolean success = false;
try
{
// Get the preparsed data from the HID driver
success = HidD_GetPreparsedData(deviceInformation.hidHandle, ref preparsedData);
// Get the HID device's capabilities
result = HidP_GetCaps(preparsedData, ref deviceInformation.capabilities);
if ((result != 0))
{
Debug.WriteLine("usbGenericHidCommunication:queryDeviceCapabilities() -> Device query results:");
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Usage: {0}",
Convert.ToString(deviceInformation.capabilities.usage, 16)));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Usage Page: {0}",
Convert.ToString(deviceInformation.capabilities.usagePage, 16)));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Input Report Byte Length: {0}",
deviceInformation.capabilities.inputReportByteLength));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Output Report Byte Length: {0}",
deviceInformation.capabilities.outputReportByteLength));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Feature Report Byte Length: {0}",
deviceInformation.capabilities.featureReportByteLength));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Link Collection Nodes: {0}",
deviceInformation.capabilities.numberLinkCollectionNodes));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Input Button Caps: {0}",
deviceInformation.capabilities.numberInputButtonCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Input Value Caps: {0}",
deviceInformation.capabilities.numberInputValueCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Input Data Indices: {0}",
deviceInformation.capabilities.numberInputDataIndices));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Output Button Caps: {0}",
deviceInformation.capabilities.numberOutputButtonCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Output Value Caps: {0}",
deviceInformation.capabilities.numberOutputValueCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Output Data Indices: {0}",
deviceInformation.capabilities.numberOutputDataIndices));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Feature Button Caps: {0}",
deviceInformation.capabilities.numberFeatureButtonCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Feature Value Caps: {0}",
deviceInformation.capabilities.numberFeatureValueCaps));
Debug.WriteLine(string.Format("usbGenericHidCommunication:queryDeviceCapabilities() -> Number of Feature Data Indices: {0}",
deviceInformation.capabilities.numberFeatureDataIndices));
}
}
catch (Exception)
{
// Something went badly wrong... this shouldn't happen, so we throw an exception
Debug.WriteLine("usbGenericHidCommunication:queryDeviceCapabilities() -> EXECEPTION: An unrecoverable error has occurred!");
throw;
}
finally
{
// Free up the memory before finishing
if (preparsedData != IntPtr.Zero)
{
success = HidD_FreePreparsedData(preparsedData);
}
}
}
}
}
<file_sep>/MiniGUI/WFF GenericHID Communication Library/kernel32Dll.cs
//-----------------------------------------------------------------------------
//
// kernel32Dll.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace WFF_GenericHID_Communication_Library
{
/// <summary>
/// kernel32Dll - Internal class containing the API definitions required for interoperability
/// with the kernel32.dll. Primarily this provides file operation methods required for
/// sending and receiving data from Windows' USB generic HID driver.
/// </summary>
public partial class WFF_GenericHID_Communication_Library
{
internal const Int32 FILE_FLAG_OVERLAPPED = 0x40000000;
internal const Int32 FILE_SHARE_READ = 1;
internal const Int32 FILE_SHARE_WRITE = 2;
internal const UInt32 GENERIC_READ = 0x80000000;
internal const UInt32 GENERIC_WRITE = 0x40000000;
internal const Int32 INVALID_HANDLE_VALUE = -1;
internal const Int32 OPEN_EXISTING = 3;
internal const Int32 WAIT_TIMEOUT = 0x102;
internal const Int32 WAIT_OBJECT_0 = 0;
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
internal Int32 nLength;
internal Int32 lpSecurityDescriptor;
internal Int32 bInheritHandle;
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern Int32 CancelIo(
SafeFileHandle hFile
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr CreateEvent(
IntPtr SecurityAttributes,
Boolean bManualReset,
Boolean bInitialState,
String lpName
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern SafeFileHandle CreateFile(
String lpFileName,
UInt32 dwDesiredAccess,
Int32 dwShareMode,
IntPtr lpSecurityAttributes,
Int32 dwCreationDisposition,
Int32 dwFlagsAndAttributes,
Int32 hTemplateFile
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern Boolean GetOverlappedResult(
SafeFileHandle hFile,
IntPtr lpOverlapped,
ref Int32 lpNumberOfBytesTransferred,
Boolean bWait
);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern Boolean ReadFile(
SafeFileHandle hFile,
IntPtr lpBuffer,
Int32 nNumberOfBytesToRead,
ref Int32 lpNumberOfBytesRead,
IntPtr lpOverlapped
);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern Int32 WaitForSingleObject(
IntPtr hHandle,
Int32 dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern Boolean WriteFile(
SafeFileHandle hFile,
Byte[] lpBuffer,
Int32 nNumberOfBytesToWrite,
ref Int32 lpNumberOfBytesWritten,
IntPtr lpOverlapped
);
[DllImport("kernel32", SetLastError = true)]
internal static extern bool CloseHandle(
IntPtr h
);
}
}
<file_sep>/FFmini_HID/FFmini_HID/src/reset.h
/* Stuff about reset and bootloader */
#ifndef RESET_H_
#define RESET_H_
#include "LUFA/Common/Common.h"
#include "LUFA/Drivers/USB/USB.h"
void Jump_To_Bootloader(void);
#endif
<file_sep>/MiniGUI/WFF GenericHID Communication Library/deviceNotifications.cs
//-----------------------------------------------------------------------------
//
// deviceNotifications.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
// The following namespace allows debugging output (when compiled in debug mode)
using System.Diagnostics;
namespace WFF_GenericHID_Communication_Library
{
/// <summary>
/// This partial class contains the methods required for detecting when
/// the USB device is attached or detached.
/// </summary>
public partial class WFF_GenericHID_Communication_Library : Control
{
/// <summary>
/// Create a delegate for the USB event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void usbEventsHandler(object sender, EventArgs e);
/// <summary>
/// Define the event
/// </summary>
public event usbEventsHandler usbEvent;
/// <summary>
/// The usb event thrower
/// </summary>
/// <param name="e"></param>
protected virtual void onUsbEvent(EventArgs e)
{
if (usbEvent != null)
{
Debug.WriteLine("usbGenericHidCommunications:onUsbEvent() -> Throwing a USB event to a listener");
usbEvent(this, e);
}
else Debug.WriteLine("usbGenericHidCommunications:onUsbEvent() -> Attempted to throw a USB event, but no one was listening");
}
/// <summary>
/// isNotificationForTargetDevice - Compares the target devices pathname against the
/// pathname of the device which caused the event message
/// </summary>
private Boolean isNotificationForTargetDevice(Message m)
{
Int32 stringSize;
try
{
DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1();
DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR();
Marshal.PtrToStructure(m.LParam, devBroadcastHeader);
// Is the notification event concerning a device interface?
if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
// Get the device path name of the affected device
stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2);
devBroadcastDeviceInterface.dbcc_name = new Char[stringSize + 1];
Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface);
String deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize);
// Compare the device name with our target device's pathname (strings are moved to lower case
// using en-US to ensure case insensitivity accross different regions)
if ((String.Compare(deviceNameString.ToLower(new System.Globalization.CultureInfo("en-US")),
deviceInformation.devicePathName.ToLower(new System.Globalization.CultureInfo("en-US")), true) == 0)) return true;
else return false;
}
}
catch (Exception)
{
Debug.WriteLine("usbGenericHidCommunication:isNotificationForTargetDevice() -> EXCEPTION: An unknown exception has occured!");
return false;
}
return false;
}
/// <summary>
/// registerForDeviceNotification - registers the window (identified by the windowHandle) for
/// device notification messages from Windows
/// </summary>
public Boolean registerForDeviceNotifications(IntPtr windowHandle)
{
Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Method called");
// A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request.
DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero;
Int32 size = 0;
// Get the required GUID
System.Guid systemHidGuid = new Guid();
HidD_GetHidGuid(ref systemHidGuid);
try
{
// Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure.
size = Marshal.SizeOf(devBroadcastDeviceInterface);
devBroadcastDeviceInterface.dbcc_size = size;
devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
devBroadcastDeviceInterface.dbcc_reserved = 0;
devBroadcastDeviceInterface.dbcc_classguid = systemHidGuid;
devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
// Register for notifications and store the returned handle
deviceInformation.deviceNotificationHandle = RegisterDeviceNotification(windowHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE);
Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface);
if ((deviceInformation.deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32()))
{
Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration failed");
return false;
}
else
{
Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration succeded");
return true;
}
}
catch (Exception)
{
Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> EXCEPTION: An unknown exception has occured!");
}
finally
{
// Free the memory allocated previously by AllocHGlobal.
if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer);
}
return false;
}
/// <summary>
/// handleDeviceNotificationMessages - this method examines any windows devices messages that are
/// received to check if they are relevant to our target USB device. If so the method takes the
/// correct action dependent on the message type.
/// </summary>
/// <param name="m"></param>
public void handleDeviceNotificationMessages(Message m)
{
//Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> Method called");
// Make sure this is a device notification
if (m.Msg != WM_DEVICECHANGE) return;
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> Device notification received");
try
{
switch (m.WParam.ToInt32())
{
// Device attached
case DBT_DEVICEARRIVAL:
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> New device attached");
// If our target device is not currently attached, this could be our device, so we attempt to find it.
if (!isDeviceAttached)
{
findTargetDevice();
onUsbEvent(EventArgs.Empty); // Generate an event
}
break;
// Device removed
case DBT_DEVICEREMOVECOMPLETE:
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> A device has been removed");
// Was this our target device?
if (isNotificationForTargetDevice(m))
{
// If so detach the USB device.
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> The target USB device has been removed - detaching...");
detachUsbDevice();
onUsbEvent(EventArgs.Empty); // Generate an event
}
break;
// Other message
default:
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> Unknown notification message");
break;
}
}
catch (Exception)
{
Debug.WriteLine("usbGenericHidCommunication:handleDeviceNotificationMessages() -> EXCEPTION: An unknown exception has occured!");
}
}
/// <summary>
/// WndProc - This method overrides the WinProc in order to pass notification messages
/// to the base WndProc
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
handleDeviceNotificationMessages(m);
// Pass the notification message to the base WndProc
base.WndProc(ref m);
}
}
}
<file_sep>/MiniGUI/WFF GenericHID Communication Library/setupapiDll.cs
//-----------------------------------------------------------------------------
//
// setupapiDll.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace WFF_GenericHID_Communication_Library
{
/// <summary>
/// setupapiDll - Internal class containing the API definitions required for interoperability
/// with the setupapi.dll. Primarily this provides methods for device discovery and
/// identification.
/// </summary>
public partial class WFF_GenericHID_Communication_Library
{
// from setupapi.h
internal const Int32 DIGCF_PRESENT = 2;
internal const Int32 DIGCF_DEVICEINTERFACE = 0X10;
internal struct SP_DEVICE_INTERFACE_DATA
{
internal Int32 cbSize;
internal System.Guid InterfaceClassGuid;
internal Int32 Flags;
internal IntPtr Reserved;
}
//internal struct SP_DEVICE_INTERFACE_DETAIL_DATA
// {
// internal Int32 cbSize;
// internal String DevicePath;
// }
//internal struct SP_DEVINFO_DATA
// {
// internal Int32 cbSize;
// internal System.Guid ClassGuid;
// internal Int32 DevInst;
// internal Int32 Reserved;
// }
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Int32 SetupDiCreateDeviceInfoList(
ref System.Guid ClassGuid,
Int32 hwndParent
);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Int32 SetupDiDestroyDeviceInfoList(
IntPtr DeviceInfoSet
);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Boolean SetupDiEnumDeviceInterfaces(
IntPtr DeviceInfoSet,
IntPtr DeviceInfoData,
ref System.Guid InterfaceClassGuid,
Int32 MemberIndex,
ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData
);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr SetupDiGetClassDevs(
ref System.Guid ClassGuid,
IntPtr Enumerator,
IntPtr hwndParent,
Int32 Flags
);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern Boolean SetupDiGetDeviceInterfaceDetail(
IntPtr DeviceInfoSet,
ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
IntPtr DeviceInterfaceDetailData,
Int32 DeviceInterfaceDetailDataSize,
ref Int32 RequiredSize,
IntPtr DeviceInfoData);
}
}
<file_sep>/FFmini_HID/FFmini_HID/src/TIMERS.c
// Timer(s) code
#include "TIMERS.h"
#include <avr/io.h>
#include <avr/interrupt.h>
void TIMER0_init()
{
// Configure timer 0 to generate a timer overflow interrupt every
// 256*1024 clock cycles, or approx 61 Hz when using 16 MHz clock
// Seed clock with (256-156) = 100 for 100 Hz clock
TCCR0A = 0x00;
TCCR0B = 0x05;
TCNT0 = 100;
TIMSK0 = (1<<TOIE0);
}
void TIMER1_init()
{
// Initialize the 16-bit Timer1 to clock at 16 MHz
TCCR1A = 0x00; // Prescale Timer1 @ 1
TCCR1B = 0x01;
TIFR1&=~(1<<TOV1); // Clear overflow flag
TIMSK1 |= (1<<TOIE1); // start timer
TIMSK1&=~(1<<OCIE1A); // Disable timer1A compare
TIMSK1&=~(1<<OCIE1B); // Disable timer1B compare
}
<file_sep>/MiniGUI/WFF GenericHID Communication Library/user32Dll.cs
//-----------------------------------------------------------------------------
//
// user32Dll.cs
//
// WFF GenericHID Communication Library (Version 4_0)
// A class for communicating with Generic HID USB devices
//
// Copyright (c) 2011 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Web: http://www.waitingforfriday.com
// Email: <EMAIL>
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace WFF_GenericHID_Communication_Library
{
/// <summary>
/// user32Dll - Internal class containing the API definitions required for interoperability
/// with the user32.dll. Primarily this provides methods for erceiving event notifications
/// which are used to alert the application when devices are added and removed from the
/// system.
/// </summary>
public partial class WFF_GenericHID_Communication_Library
{
// from dbt.h
internal const Int32 DBT_DEVICEARRIVAL = 0x8000;
internal const Int32 DBT_DEVICEREMOVECOMPLETE = 0x8004;
internal const Int32 DBT_DEVTYP_DEVICEINTERFACE = 5;
internal const Int32 DBT_DEVTYP_HANDLE = 6;
internal const Int32 DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4;
internal const Int32 DEVICE_NOTIFY_SERVICE_HANDLE = 1;
internal const Int32 DEVICE_NOTIFY_WINDOW_HANDLE = 0;
internal const Int32 WM_DEVICECHANGE = 0x219;
[StructLayout(LayoutKind.Sequential)]
internal class DEV_BROADCAST_DEVICEINTERFACE
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
internal Int16 dbcc_name;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class DEV_BROADCAST_DEVICEINTERFACE_1
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 16)]
internal Byte[] dbcc_classguid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
internal Char[] dbcc_name;
}
[StructLayout(LayoutKind.Sequential)]
internal class DEV_BROADCAST_HDR
{
internal Int32 dbch_size;
internal Int32 dbch_devicetype;
internal Int32 dbch_reserved;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr RegisterDeviceNotification(
IntPtr hRecipient,
IntPtr NotificationFilter,
Int32 Flags
);
[DllImport("user32.dll", SetLastError = true)]
internal static extern Boolean UnregisterDeviceNotification(
IntPtr Handle
);
}
}
<file_sep>/FFmini_HID/FFmini_HID/src/EXT.c
// External interrupt code
#include "EXT.h"
#include <avr/io.h>
#include <avr/interrupt.h>
void EXT_INT_init(void){
// interrupt on INT1 pin rising edge (MAX9924 triggered)
//EICRA = (1<<ISC31) | (1<<ISC30) | (1<<ISC21) | (1<<ISC20)| (1<<ISC11) | (1<<ISC10) | (1<<ISC01) | (1<<ISC00);
// interrupt on INT1 pin falling edge (MAX9924 triggered)
EICRA = (1<<ISC31) | (0<<ISC30) | (1<<ISC21) | (0<<ISC20)| (1<<ISC11) | (0<<ISC10) | (1<<ISC01) | (0<<ISC00);
EIMSK = (1<<INT1); // Enable MAX9924
}
<file_sep>/FFmini_HID/FFmini_HID/src/AT_parser.h
#ifndef __AT_PARSER_H__
#define __AT_PARSER_H__
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <LUFA/Drivers/Peripheral/Serial.h>
#include <LUFA/Drivers/Misc/RingBuffer.h>
volatile uint8_t CR_flag;
/** Circular buffer to hold data from FFmini to BlueTooth SPP device*/
RingBuffer_t FFtoBT_Buffer;
/** Underlying data buffer for FFmini, where the bytes to be TD'd are located. */
uint8_t FFtoBT_Buffer_Data[32];
/** Circular buffer to hold data from BlueTooth SPP device to FFmini*/
RingBuffer_t BTtoFF_Buffer;
/** Underlying data buffer for BlueTooth SPP device, where RX'd bytes are located. */
uint8_t BTtoFF_Buffer_Data[32];
void send_ELM327_prompt(void);
void send_ELM327_OK(void);
void send_ELM327_CR(void);
void parse_SER_buffer(uint8_t EGT_H, uint8_t EGT_L, uint8_t CHT_H, uint8_t CHT_L, uint32_t total_time_RPM);
void send_ELM327_header(void);
#endif
<file_sep>/FFmini_HID/FFmini_HID/src/reset.c
/* Stuff about reset and bootloader */
#include <avr/wdt.h>
#include <avr/io.h>
#include <util/delay.h>
#include "reset.h"
uint32_t Boot_Key ATTR_NO_INIT;
#define MAGIC_BOOT_KEY 0xDC42ACCA
//#define FLASH_SIZE_BYTES 0x8000 // 32 K bytes of Flash in 32u2
#define FLASH_SIZE_BYTES 0x4000 // 16 K bytes of Flash in 16u2
#define BOOTLOADER_SEC_SIZE_BYTES 0x1000 // 2K words of bootloader
//#define BOOTLOADER_START_ADDRESS (FLASH_SIZE_BYTES - BOOTLOADER_SEC_SIZE_BYTES)
#define BOOTLOADER_START_ADDRESS ((FLASH_SIZE_BYTES - BOOTLOADER_SEC_SIZE_BYTES)>>1)
void Bootloader_Jump_Check(void) ATTR_INIT_SECTION(3);
void Bootloader_Jump_Check(void)
{
// If the reset source was the bootloader and the key is correct, clear it and jump to the bootloader
if ((MCUSR & (1 << WDRF)) && (Boot_Key == MAGIC_BOOT_KEY))
{
Boot_Key = 0;
((void (*)(void))BOOTLOADER_START_ADDRESS)();
}
}
void Jump_To_Bootloader()
{
// If USB is used, detach from the bus and reset it
USB_Disable();
// Disable all interrupts
cli();
// Wait two seconds for the USB detachment to register on the host
Delay_MS(2000);
// Set the bootloader key to the magic value and force a reset
Boot_Key = MAGIC_BOOT_KEY;
wdt_enable(WDTO_250MS);
for (;;);
}
| 6048afac34f2380cac943387a215f72d680c5c7a | [
"Markdown",
"C#",
"C"
] | 20 | C# | openVespa/FireFly | 573c63bc562b66494bdc74d7c5a1d0b2e3206dc4 | 271ceb50587c9153bb4d8291adc77c8d45a1fed0 |
refs/heads/master | <file_sep>var Menu = {
init: function() {
$('a.new-menu').on('click', this.toggleMenuForm);
$('form#new_menu').on('ajax:success', this.appendMenu);
$('form#new_menu').on('ajax:error', this.showErrors);
},
toggleMenuForm: function(e) {
e.preventDefault();
$('form#new_menu').toggleClass('hidden');
},
appendMenu: function(event, data) {
$('ul.menus').append(data)
},
showErrors: function(xhr, data, status) {
if (data.statusText == "Unauthorized") return window.location = data.responseText
$('ul.menus').before(data.responseText)
}
}
$(document).ready(function() {
Menu.init();
})
| 5d1f471b6d605e41d8abc26a35215d93db8964c2 | [
"JavaScript"
] | 1 | JavaScript | magee/rails_on_ajax | 74aa5fa13e6904329c9eace373b14d45dd3291b1 | e844fb6893864bdc363c022709d541772dba446e |
refs/heads/master | <file_sep>package com.pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.baseClass.LibGlobal;
public class CustomerServicePage extends LibGlobal {
public CustomerServicePage() {
PageFactory.initElements(driver, this);
}
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[1]")
private WebElement yourOrdersTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[2]")
private WebElement returnsAndRefundsTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[3]")
private WebElement manageAddressTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[4]")
private WebElement managePrimeTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[5]")
private WebElement paymentSettingsTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[6]")
private WebElement accountSettingsTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[7]")
private WebElement covid19AndAmazonTab;
@FindBy(xpath = "(//div[@class='a-box self-service-rich-card'])[8]")
private WebElement digitalServicesAndDeviceSupportTab;
public boolean checkYourOrdersTab() {
return isEnabled(yourOrdersTab);
}
public boolean checkReturnsAndRefundsTab() {
return isEnabled(returnsAndRefundsTab);
}
public boolean checkManageAddressTab() {
return isEnabled(manageAddressTab);
}
public boolean checkManagePrimeTab() {
return isEnabled(managePrimeTab);
}
public boolean checkPaymentSettingsTab() {
return isEnabled(paymentSettingsTab);
}
public boolean checkAccountSettingsTab() {
return isEnabled(accountSettingsTab);
}
public boolean checkCovid19AndAmazonTab() {
return isEnabled(covid19AndAmazonTab);
}
public boolean checkDigitalServicesAndDeviceSupportTab() {
return isEnabled(digitalServicesAndDeviceSupportTab);
}
@FindBy(xpath = "//input[@class='a-input-text a-span12']")
private WebElement moreSolutionsTxtBox;
@FindBy(xpath = "//input[@class='a-button-input']")
private WebElement goMoreSolutionsBtn;
public boolean checkMoreSolutionsTxtBox() {
return isEnabled(moreSolutionsTxtBox);
}
public boolean checkGoMoreSolutionsBtn() {
return isEnabled(goMoreSolutionsBtn);
}
@FindBy(xpath = "//a[@class='active']")
private WebElement recommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[1]")
private WebElement whereIsMyOrderInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[2]")
private WebElement payingForYourOrderInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[3]")
private WebElement deliveryChargesInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[4]")
private WebElement returnsAndRefundsInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[5]")
private WebElement manageYourAccountInfoInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[6]")
private WebElement payOnDeliveryInRecommendedTopics;
@FindBy(xpath = "(//a[@class='same_window cs-override-recommended'])[7]")
private WebElement revisePaymentInRecommendedTopics;
public boolean checkRecommendedTopics() {
return isEnabled(recommendedTopics);
}
public void mouseOverRecommendedTopics() {
moveToElement(recommendedTopics);
}
public boolean checkWhereIsMyOrderInRecommendedTopics() {
return isEnabled(whereIsMyOrderInRecommendedTopics);
}
public boolean checkPayingForYourOrderInRecommendedTopics() {
return isEnabled(payingForYourOrderInRecommendedTopics);
}
public boolean checkDeliveryChargesInRecommendedTopics() {
return isEnabled(deliveryChargesInRecommendedTopics);
}
public boolean checkReturnsAndRefundsInRecommendedTopics() {
return isEnabled(returnsAndRefundsInRecommendedTopics);
}
public boolean checkManageYourAccountInfoInRecommendedTopics() {
return isEnabled(manageYourAccountInfoInRecommendedTopics);
}
public boolean checkPayOnDeliveryInRecommendedTopics() {
return isEnabled(payOnDeliveryInRecommendedTopics);
}
public boolean checkRevisePaymentInRecommendedTopics() {
return isEnabled(revisePaymentInRecommendedTopics);
}
@FindBy(xpath = "(//a[@tabindex='-1'])[2]")
private WebElement shippingAndDelivery;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910250'])[1]")
private WebElement amazonPrimeInShippingAndDelivery;
@FindBy(xpath = "(//a[text()='Shipping Speeds and Delivery Charges'])[1]")
private WebElement shippingSpeedsAndDeliveryChargesInShippingAndDelivery;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910530'])[1]")
private WebElement trackYourPackageInShippingAndDelivery;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910090'])[1]")
private WebElement contactCourierInShippingAndDelivery;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910400'])[1]")
private WebElement orderingRestrictionsInShippingAndDelivery;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910060'])[1]")
private WebElement moreInShippingAndDelivery;
public boolean checkShippingAndDelivery() {
return isEnabled(shippingAndDelivery);
}
public void mouseOverShippingAndDelivery() {
moveToElement(shippingAndDelivery);
}
public boolean checkAmazonPrimeInShippingAndDelivery() {
return isEnabled(amazonPrimeInShippingAndDelivery);
}
public boolean checkShippingSpeedsAndDeliveryChargesInShippingAndDelivery() {
return isEnabled(shippingSpeedsAndDeliveryChargesInShippingAndDelivery);
}
public boolean checkTrackYourPackageInShippingAndDelivery() {
return isEnabled(trackYourPackageInShippingAndDelivery);
}
public boolean checkContactCourierInShippingAndDelivery() {
return isEnabled(contactCourierInShippingAndDelivery);
}
public boolean checkOrderingRestrictionsInShippingAndDelivery() {
return isEnabled(orderingRestrictionsInShippingAndDelivery);
}
public boolean checkMoreInShippingAndDelivery() {
return isEnabled(moreInShippingAndDelivery);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-2']")
private WebElement amazonPrime;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910360'])[1]")
private WebElement aboutAmazonPrimeInAmazonPrime;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910190'])[1]")
private WebElement signUpForAmazonPrimeInAP;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910200'])[1]")
private WebElement aboutAmazonPrimeMembershipFeeInAP;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202085280'])[1]")
private WebElement aboutPrimeEligibleItemsInAP;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910440'])[1]")
private WebElement amazonPrimeDeliveryBenefitsInAP;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201910250'])[2]")
private WebElement moreInPrime;
public boolean checkAmazonPrime() {
return isEnabled(amazonPrime);
}
public void mouseOverAmazonPrime() {
moveToElement(amazonPrime);
}
public boolean checkAboutAmazonPrimeInAmazonPrime() {
return isEnabled(aboutAmazonPrimeInAmazonPrime);
}
public boolean checkSignUpForAmazonPrimeInAP() {
return isEnabled(signUpForAmazonPrimeInAP);
}
public boolean checkAboutAmazonPrimeMembershipFeeInAP() {
return isEnabled(aboutAmazonPrimeMembershipFeeInAP);
}
public boolean checkAboutPrimeEligibleItemsInAP() {
return isEnabled(aboutPrimeEligibleItemsInAP);
}
public boolean checkAmazonPrimeDeliveryBenefitsInAP() {
return isEnabled(amazonPrimeDeliveryBenefitsInAP);
}
public boolean checkMoreInPrime() {
return isEnabled(moreInPrime);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-3']")
private WebElement paymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202054820'])[1]")
private WebElement payOnDeliveryInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202054460'])[1]")
private WebElement emiInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201895360'])[1]")
private WebElement creditDebitCardInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202054800'])[1]")
private WebElement netBankingInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=GSNBBJP63SM65UDB'])[1]")
private WebElement unknownChangesInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201895510'])[1]")
private WebElement aboutLightingDealsInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202212990'])[1]")
private WebElement upiInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html/ref=hp_gt_pt_rvpt_ppp?nodeId=202054720'])[1]")
private WebElement revisePaymentInPaymentsAndPricing;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201894450'])[1]")
private WebElement moreInPaymentsPricingAndPromotions;
public boolean checkPaymentsAndPricing() {
return isEnabled(paymentsAndPricing);
}
public void mouseOverPaymentsAndPricing() {
moveToElement(paymentsAndPricing);
}
public boolean checkPayOnDeliveryInPaymentsAndPricing() {
return isEnabled(payOnDeliveryInPaymentsAndPricing);
}
public boolean checkEmiInPaymentsAndPricing() {
return isEnabled(emiInPaymentsAndPricing);
}
public boolean checkCreditDebitCardInPaymentsAndPricing() {
return isEnabled(creditDebitCardInPaymentsAndPricing);
}
public boolean checkNetBankingInPaymentsAndPricing() {
return isEnabled(netBankingInPaymentsAndPricing);
}
public boolean checkUnknownChangesInPaymentsAndPricing() {
return isEnabled(unknownChangesInPaymentsAndPricing);
}
public boolean checkAboutLightingDealsInPaymentsAndPricing() {
return isEnabled(aboutLightingDealsInPaymentsAndPricing);
}
public boolean checkUpiInPaymentsAndPricing() {
return isEnabled(upiInPaymentsAndPricing);
}
public boolean checkRevisePaymentInPaymentsAndPricing() {
return isEnabled(revisePaymentInPaymentsAndPricing);
}
public boolean checkMoreInPaymentsPricingAndPromotions() {
return isEnabled(moreInPaymentsPricingAndPromotions);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-4']")
private WebElement amazonPay;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/l/11962108031?ref=cs_apay_t_uapb_dk'])[1]")
private WebElement usingAmazonPayBalanceInAmazonPay;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/payment/statement?ref=cs_apay_t_vs_dk'])[1]")
private WebElement viewAmazonPayTransactionsInAmazonPay;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/l/16204586031?ref=cs_apay_t_mkyc_dk'])[1]")
private WebElement completeFullKYCInAmazonPay;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202123460?ref=cs_apay_t_legal_dk'])[1]")
private WebElement legalInAmazonPay;
@FindBy(xpath = "(//a[@href=\"https://www.amazon.in/gp/help/customer/display.html/?ie=UTF8&nodeId=202123450?ref=cs_apay_t_lp_dk\"])[1]")
private WebElement moreInAmazonPay;
public boolean checkAmazonPay() {
return isEnabled(amazonPay);
}
public void mouseOverAmazonPay() {
moveToElement(amazonPay);
}
public boolean checkUsingAmazonPayBalanceInAmazonPay() {
return isEnabled(usingAmazonPayBalanceInAmazonPay);
}
public boolean checkViewAmazonPayTransactionsInAmazonPay() {
return isEnabled(viewAmazonPayTransactionsInAmazonPay);
}
public boolean checkCompleteFullKYCInAmazonPay() {
return isEnabled(completeFullKYCInAmazonPay);
}
public boolean checkLegalInAmazonPay() {
return isEnabled(legalInAmazonPay);
}
public boolean checkMoreInAmazonPay() {
return isEnabled(moreInAmazonPay);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-5']")
private WebElement returnsRefunds;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202111910?ref=cs_ret_dk_rp'])[1]")
private WebElement aboutOurReturnPoliciesInReturnsRefunds;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202115040?ref=cs_ret_dk_htr'])[1]")
private WebElement howToReturnAnItemInReturnsRefunds;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202115040?ref=cs_ret_dk_rtk'])[1]")
private WebElement checkStatusOfReturnInReturnsRefunds;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html/?nodeId=202111770?ref=cs_ret_dk_rft'])[1]")
private WebElement refundTimelinesInReturnsRefunds;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=201819090?ref=cs_ret_dk_lp'])[1]")
private WebElement moreInReturnsAndRefunds;
public boolean checkReturnsRefunds() {
return isEnabled(returnsRefunds);
}
public void mouseOverReturnsRefunds() {
moveToElement(returnsRefunds);
}
public boolean checkAboutOurReturnPoliciesInReturnsRefunds() {
return isEnabled(aboutOurReturnPoliciesInReturnsRefunds);
}
public boolean checkHowToReturnAnItemInReturnsRefunds() {
return isEnabled(howToReturnAnItemInReturnsRefunds);
}
public boolean checkCheckStatusOfReturnInReturnsRefunds() {
return isEnabled(checkStatusOfReturnInReturnsRefunds);
}
public boolean checkRefundTimelinesInReturnsRefunds() {
return isEnabled(refundTimelinesInReturnsRefunds);
}
public boolean checkMoreInReturnsAndRefunds() {
return isEnabled(moreInReturnsAndRefunds);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-6']")
private WebElement ordering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202001140'])[1]")
private WebElement cancelItemsOrOrdersInOrdering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202001380'])[1]")
private WebElement aboutItemsFulfilledByAmazonInOrdering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202001340'])[1]")
private WebElement aboutSellerFulfilledItemsInOrdering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201937140'])[1]")
private WebElement aboutGiftOrdersInOrdering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201889520'])[1]")
private WebElement searchAndBrowseForItemsInOrdering;
@FindBy(xpath = "(//a[@href='https://www.amazon.in/gp/help/customer/display.html/ref=hp_gt_od_ist?ie=UTF8&nodeId=GSM5XBBDEXX69Z9S'])[1]")
private WebElement installationsInOrdering;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201887920'])[1]")
private WebElement moreInOrdering;
public boolean checkOrdering() {
return isEnabled(ordering);
}
public void mouseOverOrdering() {
moveToElement(ordering);
}
public boolean checkCancelItemsOrOrdersInOrdering() {
return isEnabled(cancelItemsOrOrdersInOrdering);
}
public boolean checkAboutItemsFulfilledByAmazonInOrdering() {
return isEnabled(aboutItemsFulfilledByAmazonInOrdering);
}
public boolean checkAboutSellerFulfilledItemsInOrdering() {
return isEnabled(aboutSellerFulfilledItemsInOrdering);
}
public boolean checkAboutGiftOrdersInOrdering() {
return isEnabled(aboutGiftOrdersInOrdering);
}
public boolean checkSearchAndBrowseForItemsInOrdering() {
return isEnabled(searchAndBrowseForItemsInOrdering);
}
public boolean checkInstallationsInOrdering() {
return isEnabled(installationsInOrdering);
}
public boolean checkMoreInOrdering() {
return isEnabled(moreInOrdering);
}
@FindBy(xpath = "//a[@rel='#help-gateway-category-7']")
private WebElement managingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/css/account/cards/view.html/ref=hp_ss_comp_mpo'])[1]")
private WebElement manageYourPaymentMethodsInManagingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201945280'])[1]")
private WebElement changeYourAccountSettingInManagingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201945390'])[1]")
private WebElement aboutMessageCenterInManagingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=202056480'])[1]")
private WebElement connectYourSocialAccountsToAmazonInManagingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201945370'])[1]")
private WebElement aboutMobilePhoneNumberAccountsInManagingYourAccount;
@FindBy(xpath = "(//a[@href='/gp/help/customer/display.html?nodeId=201945240'])[1]")
private WebElement moreInManagingYourAccount;
public boolean checkManagingYourAccount() {
return isEnabled(managingYourAccount);
}
public void mouseOverManagingYourAccount() {
moveToElement(managingYourAccount);
}
public boolean checkManageYourPaymentMethodsInManagingYourAccount() {
return isEnabled(manageYourPaymentMethodsInManagingYourAccount);
}
public boolean checkChangeYourAccountSettingInManagingYourAccount() {
return isEnabled(changeYourAccountSettingInManagingYourAccount);
}
public boolean checkAboutMessageCenterInManagingYourAccount() {
return isEnabled(aboutMessageCenterInManagingYourAccount);
}
public boolean checkConnectYourSocialAccountsToAmazonInManagingYourAccount() {
return isEnabled(connectYourSocialAccountsToAmazonInManagingYourAccount);
}
public boolean checkAboutMobilePhoneNumberAccountsInManagingYourAccount() {
return isEnabled(aboutMobilePhoneNumberAccountsInManagingYourAccount);
}
public boolean checkMoreInManagingYourAccount() {
return isEnabled(moreInManagingYourAccount);
}
@FindBy(xpath="//a[@rel='#help-gateway-category-8']")
private WebElement devicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot1?nodeId=201252620'])[1]")
private WebElement getKindleBookOrderRefundInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot2?nodeId=GLSQ4722655M4ZEJ'])[1]")
private WebElement cancelKindleUnlimitedSubscriptionInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot3?nodeId=GMR4JYXHYDSTNQRK'])[1]")
private WebElement downloadTheAlexaAppInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot4?nodeId=G7HTKNXBW4GPXSH6'])[1]")
private WebElement setUpYourFireTVInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot5?nodeId=GEARX33JWH4K6WHJ'])[1]")
private WebElement getHelpPairingYourFireTVRemoteInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot6?nodeId=GJF9SGT5262FJLQE'])[1]")
private WebElement setParentalControlsOnFireTVInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot7?nodeId=GYFBX6H2ZQLQ2XRJ'])[1]")
private WebElement fireTVIsntTurningOnInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_spot8?nodeId=GA7K5AML6222YDEW'])[1]")
private WebElement cantScreenMirrorOnFireTVDevicesInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html/ref=hp_gt_d2_fusion?nodeId=200127470'])[1]")
private WebElement allDevicesAndDigitalServicesHelpInDevicesAndDigitalServices;
@FindBy(xpath="(//a[@href='https://www.amazon.com/gp/redirect.html/ref=hp_gt_ss_fo_mycd?location=/hz/mycd/myx'])[1]")
private WebElement manageYourContentAndDevicesInDevicesAndDigitalServices;
@FindBy(xpath="//a[@rel='#help-gateway-category-8']")
private WebElement askTheDigitalAndDeviceCommunityInDevicesAndDigitalServices;
public boolean checkDevicesAndDigitalServices() {
return isEnabled(devicesAndDigitalServices);
}
public void mouseOverDevicesAndDigitalServices() {
moveToElement(devicesAndDigitalServices);
}
public boolean checkGetKindleBookOrderRefundInDevicesAndDigitalServices() {
return isEnabled(getKindleBookOrderRefundInDevicesAndDigitalServices);
}
public boolean checkCancelKindleUnlimitedSubscriptionInDevicesAndDigitalServices() {
return isEnabled(cancelKindleUnlimitedSubscriptionInDevicesAndDigitalServices);
}
public boolean checkDownloadTheAlexaAppInDevicesAndDigitalServices() {
return isEnabled(downloadTheAlexaAppInDevicesAndDigitalServices);
}
public boolean checkSetUpYourFireTVInDevicesAndDigitalServices() {
return isEnabled(setUpYourFireTVInDevicesAndDigitalServices);
}
public boolean checkGetHelpPairingYourFireTVRemoteInDevicesAndDigitalServices() {
return isEnabled(getHelpPairingYourFireTVRemoteInDevicesAndDigitalServices);
}
public boolean checkSetParentalControlsOnFireTVInDevicesAndDigitalServices() {
return isEnabled(setParentalControlsOnFireTVInDevicesAndDigitalServices);
}
public boolean checkFireTVIsntTurningOnInDevicesAndDigitalServices() {
return isEnabled(fireTVIsntTurningOnInDevicesAndDigitalServices);
}
public boolean checkCantScreenMirrorOnFireTVDevicesInDevicesAndDigitalServices() {
return isEnabled(cantScreenMirrorOnFireTVDevicesInDevicesAndDigitalServices);
}
public boolean checkAllDevicesAndDigitalServicesHelpInDevicesAndDigitalServices() {
return isEnabled(allDevicesAndDigitalServicesHelpInDevicesAndDigitalServices);
}
public boolean checkManageYourContentAndDevicesInDevicesAndDigitalServices() {
return isEnabled(manageYourContentAndDevicesInDevicesAndDigitalServices);
}
public boolean checkAskTheDigitalAndDeviceCommunityInDevicesAndDigitalServices() {
return isEnabled(askTheDigitalAndDeviceCommunityInDevicesAndDigitalServices);
}
@FindBy(xpath="//a[@rel='#help-gateway-category-9']")
private WebElement amazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?language=en_IN&nodeId=201633340'])[1]")
private WebElement getStartedWithYourBusinessAccountInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202117480'])[1]")
private WebElement aboutAmazonBusinessInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202117500'])[1]")
private WebElement registeringYourBusinessAccountInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html/?ie=UTF8&nodeId=202117560'])[1]")
private WebElement aboutGSTInvoiceInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202117580'])[1]")
private WebElement howToIdentifyProductWithGSTInvoiceInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=201894740'])[1]")
private WebElement howToDownloadGSTInvoiceInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202117460'])[1]")
private WebElement frequentlyAskedQuestionsInAmazonBusiness;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html?nodeId=202117440'])[1]")
private WebElement moreAboutAmazonBusiness;
public boolean checkAmazonBusiness() {
return isEnabled(amazonBusiness);
}
public void mouseOverAmazonBusiness() {
moveToElement(amazonBusiness);
}
public boolean checkGetStartedWithYourBusinessAccountInAmazonBusiness() {
return isEnabled(getStartedWithYourBusinessAccountInAmazonBusiness);
}
public boolean checkAboutAmazonBusinessInAmazonBusiness() {
return isEnabled(aboutAmazonBusinessInAmazonBusiness);
}
public boolean checkRegisteringYourBusinessAccountInAmazonBusiness() {
return isEnabled(registeringYourBusinessAccountInAmazonBusiness);
}
public boolean checkAboutGSTInvoiceInAmazonBusiness() {
return isEnabled(aboutGSTInvoiceInAmazonBusiness);
}
public boolean checkHowToIdentifyProductWithGSTInvoiceInAmazonBusiness() {
return isEnabled(howToIdentifyProductWithGSTInvoiceInAmazonBusiness);
}
public boolean checkHowToDownloadGSTInvoiceInAmazonBusiness() {
return isEnabled(howToDownloadGSTInvoiceInAmazonBusiness);
}
public boolean checkFrequentlyAskedQuestionsInAmazonBusiness() {
return isEnabled(frequentlyAskedQuestionsInAmazonBusiness);
}
public boolean checkMoreAboutAmazonBusiness() {
return isEnabled(moreAboutAmazonBusiness);
}
@FindBy(xpath="//a[@rel='#help-gateway-category-10']")
private WebElement otherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=202001340'])[2]")
private WebElement sellerFulfilledOrdersInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=202115230'])[1]")
private WebElement contactingAmazonInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/copilot/share/ref=hp_gt_comp_copilot'])[1]")
private WebElement amazonCoPilotInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=201911300'])[1]")
private WebElement siteFeaturesInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=201908990'])[1]")
private WebElement securityAndPrivacyInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=201936650'])[1]")
private WebElement giftsAndListsInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='https://sellercentral.amazon.in/gp/help/external/home'])[1]")
private WebElement helpForAmazonSellersInOtherTopicsAndHelpSites;
@FindBy(xpath="(//a[@href='https://www.amazon.in/gp/help/customer/display.html/ref=cs_dk_covid?ie=UTF8&nodeId=GDFU3JS5AL6SYHRD'])[1]")
private WebElement fAQsAboutOrdersAndCOVID19VirusInOtherTopicsAndHelpSites;
public boolean checkOtherTopicsAndHelpSites() {
return isEnabled(otherTopicsAndHelpSites);
}
public void mouseOverOtherTopicsAndHelpSites() {
moveToElement(otherTopicsAndHelpSites);
}
public boolean checkSellerFulfilledOrdersInOtherTopicsAndHelpSites() {
return isEnabled(sellerFulfilledOrdersInOtherTopicsAndHelpSites);
}
public boolean checkContactingAmazonInOtherTopicsAndHelpSites() {
return isEnabled(contactingAmazonInOtherTopicsAndHelpSites);
}
public boolean checkAmazonCoPilotInOtherTopicsAndHelpSites() {
return isEnabled(amazonCoPilotInOtherTopicsAndHelpSites);
}
public boolean checkSiteFeaturesInOtherTopicsAndHelpSites() {
return isEnabled(siteFeaturesInOtherTopicsAndHelpSites);
}
public boolean checkSecurityAndPrivacyInOtherTopicsAndHelpSites() {
return isEnabled(securityAndPrivacyInOtherTopicsAndHelpSites);
}
public boolean checkGiftsAndListsInOtherTopicsAndHelpSites() {
return isEnabled(giftsAndListsInOtherTopicsAndHelpSites);
}
public boolean checkHelpForAmazonSellersInOtherTopicsAndHelpSites() {
return isEnabled(helpForAmazonSellersInOtherTopicsAndHelpSites);
}
public boolean checkFAQsAboutOrdersAndCOVID19VirusInOtherTopicsAndHelpSites() {
return isEnabled(fAQsAboutOrdersAndCOVID19VirusInOtherTopicsAndHelpSites);
}
@FindBy(xpath="//a[@rel='#help-gateway-category-11']")
private WebElement customerService;
@FindBy(xpath="(//a[@href='https://in.amazonforum.com'])[1]")
private WebElement askDigitalAndDeviceCommunityInCustomerService;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=201910530'])[1]")
private WebElement trackYourPackageInCustomerService;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=202115040'])[1]")
private WebElement aboutOurReturnsPoliciesInCustomerService;
@FindBy(xpath="(//a[@href='/gp/help/customer/display.html?nodeId=201936950'])[1]")
private WebElement orderGiftCardsInCustomerService;
@FindBy(xpath="(//button[@class='a-button-text'])[1]")
private WebElement contactUsBtnInCustomerService;
public boolean checkCustomerService() {
return isEnabled(customerService);
}
public void mouseOverCustomerService() {
moveToElement(customerService);
}
public boolean checkAskDigitalAndDeviceCommunityInCustomerService() {
return isEnabled(askDigitalAndDeviceCommunityInCustomerService);
}
public boolean checkTrackYourPackageInCustomerService() {
return isEnabled(trackYourPackageInCustomerService);
}
public boolean checkAboutOurReturnsPoliciesInCustomerService() {
return isEnabled(aboutOurReturnsPoliciesInCustomerService);
}
public boolean checkOrderGiftCardsInCustomerService() {
return isEnabled(orderGiftCardsInCustomerService);
}
public boolean checkContactUsBtnInCustomerService() {
return isEnabled(contactUsBtnInCustomerService);
}
}
<file_sep>package com.baseClass;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class LibGlobal {
public static WebDriver driver;
public static Robot rob;
public static Alert alert;
public static WebDriver launchBrowser(String browserName) {
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Baseclass\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
else if (browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "D:\\Selenium\\Baseclass\\driver\\geckodriver.exe");
driver = new FirefoxDriver();
} else {
System.setProperty("webdriver.ie.driver", "D:\\Selenium\\Baseclass\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
return driver;
}
public static boolean isDisplayed(WebElement e) {
return e.isDisplayed();
}
public static boolean isEnabled(WebElement e) {
return e.isEnabled();
}
public static void getToUrl(String url) {
driver.get(url);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public static String currentUrl() {
String currentUrl = driver.getCurrentUrl();
return currentUrl;
}
public static String title() {
String title = driver.getTitle();
return title;
}
public static void sendKey(WebElement e, String text) {
if(isDisplayed(e) && isEnabled(e) && text!=null ) {
e.sendKeys(text);
}
}
public static void click(WebElement e) {
if(isDisplayed(e) && isEnabled(e) ) {
e.click();
}
}
public static void quit() {
driver.quit();
}
public static String retriveText(WebElement e) {
String text = e.getText();
return text;
}
public static String retriveAttribute(WebElement e) {
String attributevalue = e.getAttribute("value");
return attributevalue;
}
public static void moveToElement(WebElement e) {
Actions action = new Actions(driver);
action.moveToElement(e).perform();
}
public static void dragAndDrop(WebElement src, WebElement des) {
Actions action = new Actions(driver);
action.dragAndDrop(src, des).perform();
}
public static void doubleClick(WebElement e) {
Actions action = new Actions(driver);
action.doubleClick(e).perform();
}
public static void rightClick(WebElement e) {
Actions action = new Actions(driver);
action.contextClick(e).perform();
}
public static void selectAll() {
rob.keyPress(KeyEvent.VK_CONTROL);
rob.keyPress(KeyEvent.VK_A);
rob.keyRelease(KeyEvent.VK_A);
rob.keyRelease(KeyEvent.VK_CONTROL);
}
public static void cut() {
rob.keyPress(KeyEvent.VK_CONTROL);
rob.keyPress(KeyEvent.VK_X);
rob.keyRelease(KeyEvent.VK_X);
rob.keyRelease(KeyEvent.VK_CONTROL);
}
public static void paste() {
rob.keyPress(KeyEvent.VK_CONTROL);
rob.keyPress(KeyEvent.VK_V);
rob.keyRelease(KeyEvent.VK_V);
rob.keyRelease(KeyEvent.VK_CONTROL);
}
public static void enter() {
rob.keyPress(KeyEvent.VK_ENTER);
rob.keyRelease(KeyEvent.VK_ENTER);
}
public static void arrowDown() {
rob.keyPress(KeyEvent.VK_DOWN);
rob.keyRelease(KeyEvent.VK_DOWN);
}
public static void arrowUp() {
rob.keyPress(KeyEvent.VK_UP);
rob.keyRelease(KeyEvent.VK_UP);
}
public static void arrowLeft() {
rob.keyPress(KeyEvent.VK_LEFT);
rob.keyRelease(KeyEvent.VK_LEFT);
}
public static void arrowRight() {
rob.keyPress(KeyEvent.VK_RIGHT);
rob.keyRelease(KeyEvent.VK_RIGHT);
}
public static void screenShot(String path) throws IOException {
TakesScreenshot shot = (TakesScreenshot) driver;
File src = shot.getScreenshotAs(OutputType.FILE);
File des = new File(path);
FileUtils.copyFile(src, des);
}
public static void scrollDown(WebElement e) {
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].scrollIntoView(true)", e);
}
public static void scrollUp(WebElement e) {
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].scrollIntoView(false)", e);
}
public static void jscriptClick(WebElement e) {
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click()", e);
}
public static void acceptAlert() {
driver.switchTo().alert();
alert.accept();
}
public static void dismissAlert() {
driver.switchTo().alert();
alert.dismiss();
}
public static void getIntoFrame(int index) {
driver.switchTo().frame(index);
}
public static void getIntoFrame(String id) {
driver.switchTo().frame(id);
}
public static void getIntoFrame(WebElement e) {
driver.switchTo().frame(e);
}
public static void switchToWindow(int i) {
Set<String> windowHandles = driver.getWindowHandles();
ArrayList<String> al = new ArrayList<String>(windowHandles);
String id = al.get(i);
driver.switchTo().window(id);
}
public static void selectByVisibleTextDD(WebElement e, String value) {
Select s = new Select(e);
s.selectByVisibleText(value);
}
}
<file_sep>package com.test;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.baseClass.LibGlobal;
import com.pom.BestSellersPage;
import com.pom.HomePage;
public class BestSellersTest extends LibGlobal{
HomePage home;
BestSellersPage sell;
@BeforeMethod
public void launchAmazonBestSellerPage() {
launchBrowser("chrome");
getToUrl("https://www.amazon.in/");
home = new HomePage();
home.getBestSellersPage();
sell = new BestSellersPage();
}
@Test
public void verifySideNavBarLinks() {
Assert.assertTrue(sell.checkBestSellersLink(), "Best seller link is not enabled");
Assert.assertTrue(sell.checkHotNewReleasesLink(), "Hot New Releases link is not enabled");
Assert.assertTrue(sell.checkMoversAndShakersLink(), "Movers And Shakers Link is not enabled");
Assert.assertTrue(sell.checkMostWishedForLink(), "Most Wished For link is not enabled");
Assert.assertTrue(sell.checkMostGiftedLink(), "Most Gifted link is not enabled");
Assert.assertTrue(sell.checkAmazonLaunchpadLink(), "Amazon Launchpad link is not enabled");
Assert.assertTrue(sell.checkAppsForAndroidLink(), "Apps For Android link is not enabled");
Assert.assertTrue(sell.checkAudibleAudiobooksLink(), "Audible Audio books link is not enabled");
Assert.assertTrue(sell.checkBabyProductsLink(), "Baby Products link is not enabled");
Assert.assertTrue(sell.checkBeautyLink(), "Beauty link is not enabled");
Assert.assertTrue(sell.checkBooksLink(), "books link is not enabled");
Assert.assertTrue(sell.checkCarAndMotorbikeLink(), "Car And Motorbike link is not enabled");
Assert.assertTrue(sell.checkClothingAndAccessoriesLink(), "Clothing And Accessories link is not enabled");
Assert.assertTrue(sell.checkComputersAndAccessoriesLink(), "Computers And Accessories link is not enabled");
Assert.assertTrue(sell.checkElectronicsLink(), "Electronics link is not enabled");
Assert.assertTrue(sell.checkGroceryAndGourmetFoodsLink(), "Grocery And Gourmet Foods link is not enabled");
Assert.assertTrue(sell.checkHealthAndPersonalCareLink(), "Health And Personal Care link is not enabled");
Assert.assertTrue(sell.checkGardenAndOutdoorsLink(), "Garden And Outdoors link is not enabled");
Assert.assertTrue(sell.checkGiftCardsLink(), "Gift cards link is not enabled");
Assert.assertTrue(sell.checkHomeAndKitchenLink(), "Home And Kitchen link is not enabled");
Assert.assertTrue(sell.checkIndustrialAndScientificLink(), "Industrial And Scientific link is not enabled");
Assert.assertTrue(sell.checkHomeImprovementLink(), "Home Improvement link is not enabled");
Assert.assertTrue(sell.checkJewelleryLink(), "Jewellery link is not enabled");
Assert.assertTrue(sell.checkKindleStoreLink(), "Kindle store link is not enabled");
Assert.assertTrue(sell.checkMoviesAndTVShowsLink(), "Movies And TVShows link is not enabled");
Assert.assertTrue(sell.checkMusicLink(), "Music link is not enabled");
Assert.assertTrue(sell.checkMusicalInstrumentsLink(), "Musical Instruments link is not enabled");
Assert.assertTrue(sell.checkOfficeProductsLink(), "Office Products link is not enabled");
Assert.assertTrue(sell.checkPetSuppliesLink(), "Pet Supplies link is not enabled");
Assert.assertTrue(sell.checkShoesAndHandbagsLink(), "Shoes And Handbags link is not enabled");
Assert.assertTrue(sell.checkSoftwareLink(), "software link is not enabled");
Assert.assertTrue(sell.checkSportsFitnessAndOutdoorsLink(), "Sports Fitness And Outdoors link is not enabled");
Assert.assertTrue(sell.checkToysAndGamesLink(), "Toys And Games link is not enabled");
Assert.assertTrue(sell.checkVideoGamesLink(), "video Games link is not enabled");
Assert.assertTrue(sell.checkWatchesLink(), "watches link is not enabled");
}
}
<file_sep>package com.test;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.baseClass.LibGlobal;
import com.pom.HomePage;
import com.pom.TodaysdealPage;
public class TodaysDealPageTest extends LibGlobal{
HomePage home;
TodaysdealPage today;
@BeforeMethod
public void launchTodaysDealsPage() {
launchBrowser("chrome");
getToUrl("https://www.amazon.in/");
home = new HomePage();
home.getTodaysDealsPage();
today = new TodaysdealPage();
}
@Test
public void verifyAllNavBarLinks() {
Assert.assertTrue(today.checkTodaysDealsTab(), "Todays deals link is not enabled");
Assert.assertTrue(today.checkAllDealsTab(), "All deals link is not enabled");
Assert.assertTrue(today.checkWatchedDealsTab(), "Watched deals link is not enabled");
Assert.assertTrue(today.checkSubscribeAndSaveTab(), "Subscribe And Save link is not enabled");
Assert.assertTrue(today.checkCouponsTab(), "Coupons link is not enabled");
Assert.assertTrue(today.checkAmazonAssistantTab(), "Amazon Assistant link is not enabled");
Assert.assertTrue(today.checkRefurbishedAndOpenBoxTab(), "Refurbished And OpenBox link is not enabled");
}
@Test
public void verifySideNavBarRadioBtns() {
Assert.assertTrue(today.checkAppliancesRadioBtn(), "Appliances radio btn is not enabled");
Assert.assertTrue(today.checkArtworkRadioBtn(), "Artwork radio btn is not enabled");
Assert.assertTrue(today.checkBabyProductsRadioBtn(), "Baby products radio btn is not enabled");
Assert.assertTrue(today.checkBeautyRadioBtn(), "Beauty radio btn is not enabled");
Assert.assertTrue(today.checkBooksRadioBtn(), "Books radio btn is not enabled");
Assert.assertTrue(today.checkBusinessIndustrialAndScientificSuppliesRadioBtn(), "Business Industrial And Scientific Supplies radio btn is not enabled");
Assert.assertTrue(today.checkCameraAccessoriesRadioBtn(), "Camera Accessories radio btn is not enabled");
Assert.assertTrue(today.checkCamerasAndPhotographyRadioBtn(), "Cameras And Photography radio btn is not enabled");
Assert.assertTrue(today.checkCarAndMotorbikeAccessoriesRadioBtn(), "Car And Motorbike Accessories radio btn is not enabled");
Assert.assertTrue(today.checkChimneysKitchenRadioBtn(), "Chimneys Kitchen radio btn is not enabled");
Assert.assertTrue(today.checkClothingBabyRadioBtn(), "Clothing Baby radio btn is not enabled");
Assert.assertTrue(today.checkClothingBoysRadioBtn(), "Clothing Boys radio btn is not enabled");
Assert.assertTrue(today.checkClothingGirlsRadioBtn(), "Clothing Girls radio btn is not enabled");
Assert.assertTrue(today.checkClothingMensRadioBtn(), "Clothing Mens radio btn is not enabled");
Assert.assertTrue(today.checkClothingWomensRadioBtn(), "Clothing Womens radio btn is not enabled");
Assert.assertTrue(today.checkClothingAndAccessoriesRadioBtn(), "Clothing And Accessories radio btn is not enabled");
Assert.assertTrue(today.checkComputerComponentsRadioBtn(), "Computer Components radio btn is not enabled");
Assert.assertTrue(today.checkComputersAndAccessoriesRadioBtn(), "Computers And Accessories radio btn is not enabled");
Assert.assertTrue(today.checkDataStorageAndExternalDevicesRadioBtn(), "Data Storage And External Devices radio btn is not enabled");
Assert.assertTrue(today.checkDesktopsRadioBtn(), "Desktops radio btn is not enabled");
Assert.assertTrue(today.checkElectronicsRadioBtn(), "Electronics radio btn is not enabled");
Assert.assertTrue(today.checkElectonicsAccessoriesRadioBtn(), "Electonics Accessories radio btn is not enabled");
Assert.assertTrue(today.checkFurnitureRadioBtn(), "Furniture radio btn is not enabled");
Assert.assertTrue(today.checkGardenAndOutdoorsRadioBtn(), "Garden And Outdoors radio btn is not enabled");
Assert.assertTrue(today.checkGiftsCardsRadioBtn(), "Gifts cards radio btn is not enabled");
Assert.assertTrue(today.checkGroceryRadioBtn(), "Grocery radio btn is not enabled");
Assert.assertTrue(today.checkHandbagsRadioBtn(), "Handbags radio btn is not enabled");
Assert.assertTrue(today.checkHeadphonesRadioBtn(), "Headphones radio btn is not enabled");
Assert.assertTrue(today.checkHealthAndPersonalCareRadioBtn(), "Health And Personal Care radio btn is not enabled");
Assert.assertTrue(today.checkHomeAndDecorRadioBtn(), "Home And Decor radio btn is not enabled");
Assert.assertTrue(today.checkHomeAndKitchenRadioBtn(), "Home And Kitchen radio btn is not enabled");
Assert.assertTrue(today.checkHomeAudioAndAccessoriesRadioBtn(), "Home Audio And Accessories radio btn is not enabled");
Assert.assertTrue(today.checkHomeEntertainmentSystemsRadioBtn(), "Home Entertainment Systems radio btn is not enabled");
Assert.assertTrue(today.checkHomeFurnishingRadioBtn(), "Home furnishing radio btn is not enabled");
Assert.assertTrue(today.checkHomeImproventRadioBtn(), "Home improvement radio btn is not enabled");
Assert.assertTrue(today.checkHomestorageAndOrganisationRadioBtn(), "Home storage And Organisation radio btn is not enabled");
Assert.assertTrue(today.checkHouseholdSuppliesRadioBtn(), "Household Supplies radio btn is not enabled");
Assert.assertTrue(today.checkIndoorLightingRadioBtn(), "Indoor Lighting radio btn is not enabled");
Assert.assertTrue(today.checkJewelleryRadioBtn(), "Jewellery radio btn is not enabled");
Assert.assertTrue(today.checkKeyboardsMouseAndInputRadioBtn(), "Keyboards Mouse And Input radio btn is not enabled");
Assert.assertTrue(today.checkKindleEbooksRadioBtn(), "Kindle Ebooks radio btn is not enabled");
Assert.assertTrue(today.checkKitchenAndDiningRadioBtn(), "Kitchen And Dining radio btn is not enabled");
Assert.assertTrue(today.checkLaptopsRadioBtn(), "Laptops radio btn is not enabled");
Assert.assertTrue(today.checkLargeAppliancesRadioBtn(), "Large Appliances radio btn is not enabled");
Assert.assertTrue(today.checkLuggageAndBagsRadioBtn(), "Luggage And Bags radio btn is not enabled");
Assert.assertTrue(today.checkMobileAccessoriesRadioBtn(), "Mobile Accessories radio btn is not enabled");
Assert.assertTrue(today.checkMobilesRadioBtn(), "Mobiles radio btn is not enabled");
Assert.assertTrue(today.checkMoviesAndTvShowsRadioBtn(), "Movies And tvShows radio btn is not enabled");
Assert.assertTrue(today.checkMp3PlayersAndAccessoriesRadioBtn(), "Mp3 Players And Accessories radio btn is not enabled");
Assert.assertTrue(today.checkMusicRadioBtn(), "Music radio btn is not enabled");
Assert.assertTrue(today.checkMusicalInstrumentsRadioBtn(), "Musical Instruments radio btn is not enabled");
Assert.assertTrue(today.checkNetworkingDevicesRadioBtn(), "Networking Devices radio btn is not enabled");
Assert.assertTrue(today.checkOfficeAndSchoolSuppliesRadioBtn(), "Office And School Supplies radio btn is not enabled");
Assert.assertTrue(today.checkPersonalCareRadioBtn(), "Personal care radio btn is not enabled");
Assert.assertTrue(today.checkPetSuppliesRadioBtn(), "Pet Supplies radio btn is not enabled");
Assert.assertTrue(today.checkShoeCareAndAccessoriesRadioBtn(), "ShoeCare And Accessories radio btn is not enabled");
Assert.assertTrue(today.checkRefrigeratorsRadioBtn(), "Refrigerators radio btn is not enabled");
Assert.assertTrue(today.checkShoesBoysRadioBtn(), "Shoes boys radio btn is not enabled");
Assert.assertTrue(today.checkShoesMensRadioBtn(), "Shoes mens radio btn is not enabled");
Assert.assertTrue(today.checkShoesWomensRadioBtn(), "Shoes womens radio btn is not enabled");
Assert.assertTrue(today.checkShowersRadioBtn(), "Showers radio btn is not enabled");
Assert.assertTrue(today.checkSoftwareRadioBtn(), "Software radio btn is not enabled");
Assert.assertTrue(today.checkSpeakersRadioBtn(), "Speakers radio btn is not enabled");
Assert.assertTrue(today.checkSportingGoodsRadioBtn(), "Sporting Goods radio btn is not enabled");
Assert.assertTrue(today.checkSunglassesMensRadioBtn(), "Sunglasses Mens radio btn is not enabled");
Assert.assertTrue(today.checkSunglassesGirlsRadioBtn(), "Sunglasses Girls radio btn is not enabled");
Assert.assertTrue(today.checkSunglassesWomensRadioBtn(), "Sunglasses womens radio btn is not enabled");
Assert.assertTrue(today.checkTabletsRadioBtn(), "Tablets radio btn is not enabled");
Assert.assertTrue(today.checkTelevisionsRadioBtn(), "Televisions radio btn is not enabled");
Assert.assertTrue(today.checkToysRadioBtn(), "Toys radio btn is not enabled");
Assert.assertTrue(today.checkVideoGamesRadioBtn(), "Video games radio btn is not enabled");
Assert.assertTrue(today.checkWatchesRadioBtn(), "Watches radio btn is not enabled");
Assert.assertTrue(today.checkWatchesKidsRadioBtn(), "Watches kids radio btn is not enabled");
Assert.assertTrue(today.checkWatchesMensRadioBtn(), "Watches mens radio btn is not enabled");
Assert.assertTrue(today.checkWatchesWomensRadioBtn(), "Watches womens radio btn is not enabled");
Assert.assertTrue(today.checkActiveRadioBtn(), "Active radio btn is not enabled");
Assert.assertTrue(today.checkMissedRadioBtn(), "Missed radio btn is not enabled");
Assert.assertTrue(today.checkUpcomingRadioBtn(), "Upcoming radio btn is not enabled");
Assert.assertTrue(today.checkUnder500RadioBtn(), "Under 500 radio btn is not enabled");
Assert.assertTrue(today.checkBetween500And1000RadioBtn(), "Between 500 And 1000 radio btn is not enabled");
Assert.assertTrue(today.checkBetween1000And2000RadioBtn(), "Between 1000 And 2000 radio btn is not enabled");
Assert.assertTrue(today.checkBetween2000And5000RadioBtn(), "Between 2000 And 5000 radio btn is not enabled");
Assert.assertTrue(today.checkAbove5000RadioBtn(), "Above 5000 radio btn is not enabled");
}
@Test
public void verifySideNavBarLinks() {
Assert.assertTrue(today.checkSeeMoreDeptLink(), "See more dept link is not enabled");
Assert.assertTrue(today.checkClearLink(), "clear link is not enabled");
Assert.assertTrue(today.checkDealOfDayLink(), "Deal Of Day link is not enabled");
Assert.assertTrue(today.checkCouponsLink(), "Coupons link is not enabled");
Assert.assertTrue(today.checkPrimeEarlyAccessDealsLink(), "Prime Early Access Deals link is not enabled");
Assert.assertTrue(today.checkAppOnlyAccessDealsLink(), "App Only Access Deals link is not enabled");
Assert.assertTrue(today.checkAppEarlyAccessDealsLink(), "App Early Access Deals link is not enabled");
Assert.assertTrue(today.checkDiscount10perAndAboveLink(), "Discount 10 per And Above link is not enabled");
Assert.assertTrue(today.checkDiscount25perAndAboveLink(), "Discount 25 per And Above link is not enabled");
Assert.assertTrue(today.checkDiscount50perAndAboveLink(), "Discount 50 per And Above link is not enabled");
Assert.assertTrue(today.checkRating4AndAboveLink(), "Rating 4 And Above link is not enabled");
Assert.assertTrue(today.checkRating3AndAboveLink(), "Rating 3 And Above link is not enabled");
Assert.assertTrue(today.checkrating2AndAboveLink(), "Rating 2 And Above link is not enabled");
Assert.assertTrue(today.checkRating1AndAboveLink(), "Rating 1 And Above link is not enabled");
Assert.assertTrue(today.checkLightingDealsLink(), "Lighting Deals link is not enabled");
Assert.assertTrue(today.checkSavingAndSalesLink(), "Saving And Sales link is not enabled");
}
@AfterMethod
public void closeBrowser() {
quit();
}
}
<file_sep>package com.pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.baseClass.LibGlobal;
public class AccountsAndListsDDHome extends LibGlobal {
public AccountsAndListsDDHome() {
PageFactory.initElements(driver, this);
}
@FindBy(xpath="(//a[@class='nav-link nav-item'])[1]")
private WebElement createWishListLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[2]")
private WebElement findWishListLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[3]")
private WebElement wishFromAnyWebsiteLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[4]")
private WebElement babyWishListLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[5]")
private WebElement discoverYourStyleLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[6]")
private WebElement exploreShowroomLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[7]")
private WebElement yourAccountLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[8]")
private WebElement yourOrdersLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[9]")
private WebElement yourWishListLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[10]")
private WebElement yourRecommendationsLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[11]")
private WebElement yourPrimeMembershipLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[12]")
private WebElement yourPrimeVideoLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[13]")
private WebElement yourSubscribeAndSavedItemsLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[14]")
private WebElement membershipsAndSubscriptionLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[15]")
private WebElement yourAmazonBusinessAccountLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[16]")
private WebElement yourSellerAccountLink;
@FindBy(xpath="(//a[@class='nav-link nav-item'])[17]")
private WebElement manageYourContentAndDevicesLink;
public boolean checkCreateWishListLink() {
return isEnabled(createWishListLink);
}
public boolean checkFindWishListLink() {
return isEnabled(findWishListLink);
}
public boolean checkWishFromAnyWebsiteLink() {
return isEnabled(wishFromAnyWebsiteLink);
}
public boolean checkBabyWishListLink() {
return isEnabled(babyWishListLink);
}
public boolean checkDiscoverYourStyleLink() {
return isEnabled(discoverYourStyleLink);
}
public boolean checkExploreShowroomLink() {
return isEnabled(exploreShowroomLink);
}
public boolean checkYourAccountLink() {
return isEnabled(yourAccountLink);
}
public boolean checkYourOrdersLink() {
return isEnabled(yourOrdersLink);
}
public boolean checkYourWishListLink() {
return isEnabled(yourWishListLink);
}
public boolean checkYourRecommendationsLink() {
return isEnabled(yourRecommendationsLink);
}
public boolean checkYourPrimeMembershipLink() {
return isEnabled(yourPrimeMembershipLink);
}
public boolean checkYourPrimeVideoLink() {
return isEnabled(yourPrimeVideoLink);
}
public boolean checkYourSubscribeAndSavedItemsLink() {
return isEnabled(yourSubscribeAndSavedItemsLink);
}
public boolean checkMembershipsAndSubscriptionLink() {
return isEnabled(membershipsAndSubscriptionLink);
}
public boolean checkYourAmazonBusinessAccountLink() {
return isEnabled(yourAmazonBusinessAccountLink);
}
public boolean checkYourSellerAccountLink() {
return isEnabled(yourSellerAccountLink);
}
public boolean checkManageYourContentAndDevicesLink() {
return isEnabled(manageYourContentAndDevicesLink);
}
}<file_sep>package com.test;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.baseClass.LibGlobal;
import com.pom.CustomerServicePage;
import com.pom.HomePage;
public class CustomerServicePageTest extends LibGlobal {
HomePage home;
CustomerServicePage customer;
@BeforeMethod
public void launchCustomerServicePageInAmazon() {
launchBrowser("chrome");
getToUrl("https://www.amazon.in/");
home = new HomePage();
home.getCustomerService();
customer = new CustomerServicePage();
}
@Test
public void verifyAllTabLinks() {
Assert.assertTrue(customer.checkYourOrdersTab(), "Your orders link is not enabled");
Assert.assertTrue(customer.checkReturnsAndRefundsTab(), "Returns And Refunds link is not enabled");
Assert.assertTrue(customer.checkManageAddressTab(), "Manage address link is not enabled");
Assert.assertTrue(customer.checkManagePrimeTab(), "Manage prime link is not enabled");
Assert.assertTrue(customer.checkPaymentSettingsTab(), "Payment Settings link is not enabled");
Assert.assertTrue(customer.checkAccountSettingsTab(), "Account Settings link is not enabled");
Assert.assertTrue(customer.checkCovid19AndAmazonTab(), "Covid19 And Amazon link is not enabled");
Assert.assertTrue(customer.checkDigitalServicesAndDeviceSupportTab(),
"Digital Services And Device Support link is not enabled");
}
@Test
public void verifyMoreSolutions() {
Assert.assertTrue(customer.checkMoreSolutionsTxtBox(), "More Solutions TxtBox is not enabled");
Assert.assertTrue(customer.checkGoMoreSolutionsBtn(), "More Solutions go button is not enabled");
}
@Test
public void verifyRecommendedOptionsAllOptions() {
Assert.assertTrue(customer.checkRecommendedTopics(), "More Solutions TxtBox is not enabled");
customer.mouseOverRecommendedTopics();
Assert.assertTrue(customer.checkWhereIsMyOrderInRecommendedTopics(), "Where Is My Order link is not enabled");
Assert.assertTrue(customer.checkPayingForYourOrderInRecommendedTopics(),
"Paying For Your Order link is not enabled");
Assert.assertTrue(customer.checkDeliveryChargesInRecommendedTopics(), "Delivery Charges link is not enabled");
Assert.assertTrue(customer.checkReturnsAndRefundsInRecommendedTopics(),
"Returns And Refunds link is not enabled");
Assert.assertTrue(customer.checkManageYourAccountInfoInRecommendedTopics(),
"Manage Your Account Info link is not enabled");
Assert.assertTrue(customer.checkPayOnDeliveryInRecommendedTopics(), "Pay On Delivery link is not enabled");
Assert.assertTrue(customer.checkRevisePaymentInRecommendedTopics(), "Revise Payment link is not enabled");
}
@Test
public void verifyShippingAndDeliveryAllOptions() {
Assert.assertTrue(customer.checkShippingAndDelivery(), "Shipping And Delivery link is not enabled");
customer.mouseOverShippingAndDelivery();
Assert.assertTrue(customer.checkAmazonPrimeInShippingAndDelivery(),
"Amazon Prime In ShippingAndDelivery link is not enabled");
Assert.assertTrue(customer.checkShippingSpeedsAndDeliveryChargesInShippingAndDelivery(),
"Shipping Speeds And Delivery Charges In ShippingAndDelivery link is not enabled");
Assert.assertTrue(customer.checkTrackYourPackageInShippingAndDelivery(),
"Track Your Package In ShippingAndDelivery link is not enabled");
Assert.assertTrue(customer.checkContactCourierInShippingAndDelivery(),
"Contact Courier In ShippingAndDelivery link is not enabled");
Assert.assertTrue(customer.checkOrderingRestrictionsInShippingAndDelivery(),
"Ordering Restrictions In ShippingAndDelivery link is not enabled");
Assert.assertTrue(customer.checkMoreInShippingAndDelivery(), "More In ShippingAndDelivery link is not enabled");
}
@Test
public void verifyAmazonPrimeAllOptions() {
Assert.assertTrue(customer.checkAmazonPrime(), "Amazon prime link is not enabled");
customer.mouseOverAmazonPrime();
Assert.assertTrue(customer.checkAboutAmazonPrimeInAmazonPrime(),
"About Amazon Prime In AP link is not enabled");
Assert.assertTrue(customer.checkSignUpForAmazonPrimeInAP(),
"Sign Up For Amazon Prime In AP link is not enabled");
Assert.assertTrue(customer.checkAboutAmazonPrimeMembershipFeeInAP(),
"About Amazon Prime Membership Fee In AP link is not enabled");
Assert.assertTrue(customer.checkAboutPrimeEligibleItemsInAP(),
"About Prime Eligible Items In AP link is not enabled");
Assert.assertTrue(customer.checkAmazonPrimeDeliveryBenefitsInAP(),
"Amazon Prime Delivery Benefits In AP link is not enabled");
Assert.assertTrue(customer.checkMoreInPrime(), "More In prime link is not enabled");
}
@Test
public void verifyPaymentsAndPricingAllOptions() {
Assert.assertTrue(customer.checkPaymentsAndPricing(), "Payments And Pricing link is not enabled");
customer.mouseOverPaymentsAndPricing();
Assert.assertTrue(customer.checkPayOnDeliveryInPaymentsAndPricing(),
"Pay On Delivery In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkEmiInPaymentsAndPricing(), "Emi In payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkCreditDebitCardInPaymentsAndPricing(),
"Credit Debit Card In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkNetBankingInPaymentsAndPricing(),
"NetBanking In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkUnknownChangesInPaymentsAndPricing(),
"Unknown Changes In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkAboutLightingDealsInPaymentsAndPricing(),
"About Lighting Deals In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkUpiInPaymentsAndPricing(), "Upi In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkRevisePaymentInPaymentsAndPricing(),
"Revise Payment In Payments And Pricing link is not enabled");
Assert.assertTrue(customer.checkMoreInPaymentsPricingAndPromotions(),
"More In Payments Pricing And Promotions link is not enabled");
}
@Test
public void verifyAmazonPayAllOptions() {
Assert.assertTrue(customer.checkAmazonPay(), "Amazon pay link is not enabled");
customer.mouseOverAmazonPay();
Assert.assertTrue(customer.checkUsingAmazonPayBalanceInAmazonPay(),
"Using Amazon Pay Balance In Amazon Pay link is not enabled");
Assert.assertTrue(customer.checkViewAmazonPayTransactionsInAmazonPay(),
"View Amazon Pay Transactions In Amazon Pay link is not enabled");
Assert.assertTrue(customer.checkCompleteFullKYCInAmazonPay(),
"Complete Full KYC In Amazon Pay link is not enabled");
Assert.assertTrue(customer.checkLegalInAmazonPay(), "Legal In Amazon Pay link is not enabled");
Assert.assertTrue(customer.checkMoreInAmazonPay(), "More In Amazon Pay link is not enabled");
}
@Test
public void verifyReturnsRefundsAllOptions() {
Assert.assertTrue(customer.checkReturnsRefunds(), "Returns Refunds link is not enabled");
customer.mouseOverReturnsRefunds();
Assert.assertTrue(customer.checkAboutOurReturnPoliciesInReturnsRefunds(),
"About Our Return Policies In Returns Refunds link is not enabled");
Assert.assertTrue(customer.checkHowToReturnAnItemInReturnsRefunds(),
"How To Return An Item In Returns Refunds link is not enabled");
Assert.assertTrue(customer.checkCheckStatusOfReturnInReturnsRefunds(),
"Check Status Of Return In Returns Refunds link is not enabled");
Assert.assertTrue(customer.checkRefundTimelinesInReturnsRefunds(),
"Refund Timelines In Returns Refunds link is not enabled");
Assert.assertTrue(customer.checkMoreInReturnsAndRefunds(), "More In Returns And Refunds link is not enabled");
}
@Test
public void verifyOrderingAllOptions() {
Assert.assertTrue(customer.checkOrdering(), "Ordering link is not enabled");
customer.mouseOverOrdering();
Assert.assertTrue(customer.checkCancelItemsOrOrdersInOrdering(),
"Cancel Items Or Orders In Ordering link is not enabled");
Assert.assertTrue(customer.checkAboutItemsFulfilledByAmazonInOrdering(),
"About Items Fulfilled By Amazon In Ordering link is not enabled");
Assert.assertTrue(customer.checkAboutSellerFulfilledItemsInOrdering(),
"About Seller Fulfilled Items In Ordering link is not enabled");
Assert.assertTrue(customer.checkAboutGiftOrdersInOrdering(),
"About Gift Orders In Ordering link is not enabled");
Assert.assertTrue(customer.checkSearchAndBrowseForItemsInOrdering(),
"Search And Browse For Items In Ordering link is not enabled");
Assert.assertTrue(customer.checkInstallationsInOrdering(), "Installations In Ordering link is not enabled");
Assert.assertTrue(customer.checkMoreInOrdering(), "More In Ordering link is not enabled");
}
@Test
public void verifyManagingYourAccountAllOptions() {
Assert.assertTrue(customer.checkManagingYourAccount(), "Managing Your Account link is not enabled");
customer.mouseOverManagingYourAccount();
Assert.assertTrue(customer.checkManageYourPaymentMethodsInManagingYourAccount(),
"Manage Your Payment Methods In Managing Your Account link is not enabled");
Assert.assertTrue(customer.checkChangeYourAccountSettingInManagingYourAccount(),
"Change Your Account Setting In Managing Your Account link is not enabled");
Assert.assertTrue(customer.checkAboutMessageCenterInManagingYourAccount(),
"About Message Center In Managing Your Account link is not enabled");
Assert.assertTrue(customer.checkConnectYourSocialAccountsToAmazonInManagingYourAccount(),
"Connect Your Social Accounts To Amazon In Managing Your Account link is not enabled");
Assert.assertTrue(customer.checkAboutMobilePhoneNumberAccountsInManagingYourAccount(),
"About Mobile Phone Number Accounts In Managing Your Account link is not enabled");
Assert.assertTrue(customer.checkMoreInManagingYourAccount(),
"More In Managing Your Account link is not enabled");
}
@Test
public void verifyDevicesAndDigitalServicesAllOptions() {
Assert.assertTrue(customer.checkDevicesAndDigitalServices(),
"Devices And Digital Services link is not enabled");
customer.mouseOverDevicesAndDigitalServices();
Assert.assertTrue(customer.checkGetKindleBookOrderRefundInDevicesAndDigitalServices(),
"Get Kindle Book Order Refund In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkCancelKindleUnlimitedSubscriptionInDevicesAndDigitalServices(),
"Cancel Kindle Unlimited Subscription In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkDownloadTheAlexaAppInDevicesAndDigitalServices(),
"Download The Alexa App In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkSetUpYourFireTVInDevicesAndDigitalServices(),
"SetUp Your Fire TV In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkGetHelpPairingYourFireTVRemoteInDevicesAndDigitalServices(),
"Get Help Pairing Your Fire TV Remote In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkSetParentalControlsOnFireTVInDevicesAndDigitalServices(),
"Set Parental Controls On Fire TV In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkFireTVIsntTurningOnInDevicesAndDigitalServices(),
"Fire TV Isnt Turning On In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkCantScreenMirrorOnFireTVDevicesInDevicesAndDigitalServices(),
"Cant Screen Mirror On Fire TV Devices In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkAllDevicesAndDigitalServicesHelpInDevicesAndDigitalServices(),
"All Devices And Digital Services Help In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkManageYourContentAndDevicesInDevicesAndDigitalServices(),
"Manage Your Content And Devices In Devices And Digital Services link is not enabled");
Assert.assertTrue(customer.checkAskTheDigitalAndDeviceCommunityInDevicesAndDigitalServices(),
"Ask The Digital And Device Community In Devices And Digital Services link is not enabled");
}
@Test
public void verifyAmazonBusinessAllOptions() {
Assert.assertTrue(customer.checkAmazonBusiness(), "Amazon Business link is not enabled");
customer.mouseOverAmazonBusiness();
Assert.assertTrue(customer.checkGetStartedWithYourBusinessAccountInAmazonBusiness(),
"Get Started With Your Business Account In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkAboutAmazonBusinessInAmazonBusiness(),
"About Amazon Business In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkRegisteringYourBusinessAccountInAmazonBusiness(),
"Registering Your Business Account In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkAboutGSTInvoiceInAmazonBusiness(),
"About GST Invoice In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkHowToIdentifyProductWithGSTInvoiceInAmazonBusiness(),
"How To Identify Product With GST Invoice In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkHowToDownloadGSTInvoiceInAmazonBusiness(), "How To Download GST Invoice In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkFrequentlyAskedQuestionsInAmazonBusiness(), "How To Download GST Invoice In Amazon Business link is not enabled");
Assert.assertTrue(customer.checkMoreAboutAmazonBusiness(), "More About Amazon Business link is not enabled");
}
@Test
public void verifyOtherTopicsAndHelpSitesAllOptions() {
Assert.assertTrue(customer.checkOtherTopicsAndHelpSites(), "Other Topics And Help Sites link is not enabled");
customer.mouseOverOtherTopicsAndHelpSites();
Assert.assertTrue(customer.checkSellerFulfilledOrdersInOtherTopicsAndHelpSites(),
"Seller Fulfilled Orders In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkContactingAmazonInOtherTopicsAndHelpSites(),
"Contacting Amazon In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkAmazonCoPilotInOtherTopicsAndHelpSites(),
"Amazon Co Pilot In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkSiteFeaturesInOtherTopicsAndHelpSites(),
"Site Features In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkSecurityAndPrivacyInOtherTopicsAndHelpSites(),
"Security And Privacy In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkGiftsAndListsInOtherTopicsAndHelpSites(), "Gifts And Lists In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkHelpForAmazonSellersInOtherTopicsAndHelpSites(), "Help For Amazon Sellers In Other Topics And Help Sites link is not enabled");
Assert.assertTrue(customer.checkFAQsAboutOrdersAndCOVID19VirusInOtherTopicsAndHelpSites(), "FAQs About Orders And COVID19 Virus In Other Topics And Help Sites link is not enabled");
}
@Test
public void verifyCustomerServiceAllOptions() {
Assert.assertTrue(customer.checkCustomerService(), "Customer Service link is not enabled");
customer.mouseOverCustomerService();
Assert.assertTrue(customer.checkAskDigitalAndDeviceCommunityInCustomerService(),
"Ask Digital And Device Community In Customer Service link is not enabled");
Assert.assertTrue(customer.checkTrackYourPackageInCustomerService(),
"Track Your Package In Customer Service link is not enabled");
Assert.assertTrue(customer.checkAboutOurReturnsPoliciesInCustomerService(),
"About Our Returns Policies In Customer Service link is not enabled");
Assert.assertTrue(customer.checkOrderGiftCardsInCustomerService(),
"Order Gift Cards In Customer Service link is not enabled");
Assert.assertTrue(customer.checkContactUsBtnInCustomerService(), "Contact Us Btn In Customer Service link is not enabled");
}
@AfterMethod
private void tearDown() {
quit();
}
}
<file_sep>package com.pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.baseClass.LibGlobal;
public class TodaysdealPage extends LibGlobal {
public TodaysdealPage() {
PageFactory.initElements(driver, this);
}
@FindBy(xpath="(//span[@class='nav-a-content'])[1]")
private WebElement todaysDealsTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[2]")
private WebElement allDealsTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[3]")
private WebElement watchedDealsTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[4]")
private WebElement subscribeAndSaveTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[5]")
private WebElement couponsTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[6]")
private WebElement amazonAssistantTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[7]")
private WebElement clearanceTab;
@FindBy(xpath="(//span[@class='nav-a-content'])[8]")
private WebElement refurbishedAndOpenBoxTab;
@FindBy(xpath="(//input[@type='checkbox'])[43]")
private WebElement appliancesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[44]")
private WebElement artworkRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[45]")
private WebElement babyProductsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[46]")
private WebElement beautyRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[47]")
private WebElement booksRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[48]")
private WebElement businessIndustrialAndScientificSuppliesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[49]")
private WebElement cameraAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[50]")
private WebElement camerasAndPhotographyRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[51]")
private WebElement carAndMotorbikeAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[52]")
private WebElement chimneysKitchenRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[53]")
private WebElement clothingBabyRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[54]")
private WebElement clothingBoysRadioBtn;
@FindBy(xpath="//span[@class='a-expander-prompt']")
private WebElement seeMoreDeptLink;
@FindBy(xpath="(//input[@type='checkbox'])[55]")
private WebElement clothingGirlsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[56]")
private WebElement clothingMensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[57]")
private WebElement clothingWomensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[58]")
private WebElement clothingAndAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[59]")
private WebElement computerComponentsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[60]")
private WebElement computersAndAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[61]")
private WebElement dataStorageAndExternalDevicesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[62]")
private WebElement desktopsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[63]")
private WebElement dslrRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[64]")
private WebElement electronicsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[65]")
private WebElement electonicsAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[66]")
private WebElement furnitureRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[67]")
private WebElement gardenAndOutdoorsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[68]")
private WebElement giftsCardsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[69]")
private WebElement groceryRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[70]")
private WebElement handbagsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[71]")
private WebElement headphonesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[72]")
private WebElement healthAndPersonalCareRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[73]")
private WebElement homeAndDecorRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[74]")
private WebElement homeAndKitchenRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[75]")
private WebElement homeAudioAndAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[76]")
private WebElement homeEntertainmentSystemsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[77]")
private WebElement homeFurnishingRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[78]")
private WebElement homeImproventRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[79]")
private WebElement homestorageAndOrganisationRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[80]")
private WebElement householdSuppliesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[81]")
private WebElement indoorLightingRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[82]")
private WebElement jewelleryRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[83]")
private WebElement keyboardsMouseAndInputRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[84]")
private WebElement kindleEbooksRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[85]")
private WebElement kitchenAndDiningRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[86]")
private WebElement laptopsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[87]")
private WebElement largeAppliancesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[88]")
private WebElement luggageAndBagsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[89]")
private WebElement mobileAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[90]")
private WebElement mobilesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[91]")
private WebElement moviesAndTvShowsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[92]")
private WebElement mp3PlayersAndAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[93]")
private WebElement musicRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[94]")
private WebElement musicalInstrumentsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[95]")
private WebElement networkingDevicesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[96]")
private WebElement officeAndSchoolSuppliesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[97]")
private WebElement personalCareRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[98]")
private WebElement petSuppliesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[99]")
private WebElement refrigeratorsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[100]")
private WebElement shoeCareAndAccessoriesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[101]")
private WebElement shoesBoysRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[102]")
private WebElement shoesMensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[103]")
private WebElement shoesWomensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[104]")
private WebElement showersRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[105]")
private WebElement softwareRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[106]")
private WebElement speakersRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[107]")
private WebElement sportingGoodsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[108]")
private WebElement sunglassesGirlsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[109]")
private WebElement sunglassesMensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[110]")
private WebElement sunglassesWomensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[111]")
private WebElement tabletsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[112]")
private WebElement televisionsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[113]")
private WebElement toysRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[114]")
private WebElement videoGamesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[115]")
private WebElement watchesRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[116]")
private WebElement watchesKidsRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[117]")
private WebElement watchesMensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[118]")
private WebElement watchesWomensRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[119]")
private WebElement activeRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[120]")
private WebElement missedRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[121]")
private WebElement upcomingRadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[122]")
private WebElement under500RadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[123]")
private WebElement between500And1000RadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[124]")
private WebElement between1000And2000RadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[125]")
private WebElement between2000And5000RadioBtn;
@FindBy(xpath="(//input[@type='checkbox'])[126]")
private WebElement above5000RadioBtn;
@FindBy(xpath="(//a[@class='a-link-normal'])[11]")
private WebElement clearLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[12]")
private WebElement dealOfDayLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[13]")
private WebElement couponsLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[14]")
private WebElement primeEarlyAccessDealsLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[15]")
private WebElement appOnlyAccessDealsLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[16]")
private WebElement appEarlyAccessDealsLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[17]")
private WebElement discount10perAndAboveLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[18]")
private WebElement discount25perAndAboveLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[19]")
private WebElement discount50perAndAboveLink;
@FindBy(xpath="(//a[@class='a-link-normal'])[20]")
private WebElement discount70perAndAboveLink;
@FindBy(xpath="(//div[@class='a-row a-spacing-micro'])[10]")
private WebElement rating4AndAboveLink;
@FindBy(xpath="(//div[@class='a-row a-spacing-micro'])[11]")
private WebElement rating3AndAboveLink;
@FindBy(xpath="(//div[@class='a-row a-spacing-micro'])[12]")
private WebElement rating2AndAboveLink;
@FindBy(xpath="(//div[@class='a-row a-spacing-micro'])[13]")
private WebElement rating1AndAboveLink;
@FindBy(xpath="(//a[@class='a-link-normal a-text-bold'])[2]")
private WebElement lightingDealsLink;
@FindBy(xpath="(//a[@class='a-link-normal a-text-bold'])[3]")
private WebElement savingAndSalesLink;
public boolean checkTodaysDealsTab() {
return isEnabled(todaysDealsTab);
}
public boolean checkAllDealsTab() {
return isEnabled(allDealsTab);
}
public boolean checkWatchedDealsTab() {
return isEnabled(watchedDealsTab);
}
public boolean checkSubscribeAndSaveTab() {
return isEnabled(subscribeAndSaveTab);
}
public boolean checkCouponsTab() {
return isEnabled(couponsTab);
}
public boolean checkAmazonAssistantTab() {
return isEnabled(amazonAssistantTab);
}
public boolean checkClearanceTab() {
return isEnabled(clearanceTab);
}
public boolean checkRefurbishedAndOpenBoxTab() {
return isEnabled(refurbishedAndOpenBoxTab);
}
public boolean checkAppliancesRadioBtn() {
return isEnabled(appliancesRadioBtn);
}
public boolean checkArtworkRadioBtn() {
return isEnabled(artworkRadioBtn);
}
public boolean checkBabyProductsRadioBtn() {
return isEnabled(babyProductsRadioBtn);
}
public boolean checkBeautyRadioBtn() {
return isEnabled(beautyRadioBtn);
}
public boolean checkBooksRadioBtn() {
return isEnabled(booksRadioBtn);
}
public boolean checkBusinessIndustrialAndScientificSuppliesRadioBtn() {
return isEnabled(businessIndustrialAndScientificSuppliesRadioBtn);
}
public boolean checkCameraAccessoriesRadioBtn() {
return isEnabled(cameraAccessoriesRadioBtn);
}
public boolean checkCamerasAndPhotographyRadioBtn() {
return isEnabled(camerasAndPhotographyRadioBtn);
}
public boolean checkCarAndMotorbikeAccessoriesRadioBtn() {
return isEnabled(carAndMotorbikeAccessoriesRadioBtn);
}
public boolean checkChimneysKitchenRadioBtn() {
return isEnabled(chimneysKitchenRadioBtn);
}
public boolean checkClothingBabyRadioBtn() {
return isEnabled(clothingBabyRadioBtn);
}
public boolean checkClothingBoysRadioBtn() {
return isEnabled(clothingBoysRadioBtn);
}
public boolean checkSeeMoreDeptLink() {
return isEnabled(seeMoreDeptLink);
}
public boolean checkClothingGirlsRadioBtn() {
return isEnabled(clothingGirlsRadioBtn);
}
public boolean checkClothingMensRadioBtn() {
return isEnabled(clothingMensRadioBtn);
}
public boolean checkClothingWomensRadioBtn() {
return isEnabled(clothingWomensRadioBtn);
}
public boolean checkClothingAndAccessoriesRadioBtn() {
return isEnabled(clothingAndAccessoriesRadioBtn);
}
public boolean checkComputerComponentsRadioBtn() {
return isEnabled(computerComponentsRadioBtn);
}
public boolean checkComputersAndAccessoriesRadioBtn() {
return isEnabled(computersAndAccessoriesRadioBtn);
}
public boolean checkDataStorageAndExternalDevicesRadioBtn() {
return isEnabled(dataStorageAndExternalDevicesRadioBtn);
}
public boolean checkDesktopsRadioBtn() {
return isEnabled(desktopsRadioBtn);
}
public boolean checkElectronicsRadioBtn() {
return isEnabled(electronicsRadioBtn);
}
public boolean checkElectonicsAccessoriesRadioBtn() {
return isEnabled(electonicsAccessoriesRadioBtn);
}
public boolean checkFurnitureRadioBtn() {
return isEnabled(furnitureRadioBtn);
}
public boolean checkGardenAndOutdoorsRadioBtn() {
return isEnabled(gardenAndOutdoorsRadioBtn);
}
public boolean checkGiftsCardsRadioBtn() {
return isEnabled(giftsCardsRadioBtn);
}
public boolean checkGroceryRadioBtn() {
return isEnabled(groceryRadioBtn);
}
public boolean checkHandbagsRadioBtn() {
return isEnabled(handbagsRadioBtn);
}
public boolean checkHeadphonesRadioBtn() {
return isEnabled(headphonesRadioBtn);
}
public boolean checkHealthAndPersonalCareRadioBtn() {
return isEnabled(healthAndPersonalCareRadioBtn);
}
public boolean checkHomeAndDecorRadioBtn() {
return isEnabled(homeAndDecorRadioBtn);
}
public boolean checkHomeAndKitchenRadioBtn() {
return isEnabled(homeAndKitchenRadioBtn);
}
public boolean checkHomeAudioAndAccessoriesRadioBtn() {
return isEnabled(homeAudioAndAccessoriesRadioBtn);
}
public boolean checkHomeEntertainmentSystemsRadioBtn() {
return isEnabled(homeEntertainmentSystemsRadioBtn);
}
public boolean checkHomeFurnishingRadioBtn() {
return isEnabled(homeFurnishingRadioBtn);
}
public boolean checkHomeImproventRadioBtn() {
return isEnabled(homeImproventRadioBtn);
}
public boolean checkHomestorageAndOrganisationRadioBtn() {
return isEnabled(homestorageAndOrganisationRadioBtn);
}
public boolean checkHouseholdSuppliesRadioBtn() {
return isEnabled(householdSuppliesRadioBtn);
}
public boolean checkIndoorLightingRadioBtn() {
return isEnabled(indoorLightingRadioBtn);
}
public boolean checkJewelleryRadioBtn() {
return isEnabled(jewelleryRadioBtn);
}
public boolean checkKeyboardsMouseAndInputRadioBtn() {
return isEnabled(keyboardsMouseAndInputRadioBtn);
}
public boolean checkKindleEbooksRadioBtn() {
return isEnabled(kindleEbooksRadioBtn);
}
public boolean checkKitchenAndDiningRadioBtn() {
return isEnabled(kitchenAndDiningRadioBtn);
}
public boolean checkLaptopsRadioBtn() {
return isEnabled(laptopsRadioBtn);
}
public boolean checkLargeAppliancesRadioBtn() {
return isEnabled(largeAppliancesRadioBtn);
}
public boolean checkLuggageAndBagsRadioBtn() {
return isEnabled(luggageAndBagsRadioBtn);
}
public boolean checkMobileAccessoriesRadioBtn() {
return isEnabled(mobileAccessoriesRadioBtn);
}
public boolean checkMobilesRadioBtn() {
return isEnabled(mobilesRadioBtn);
}
public boolean checkMoviesAndTvShowsRadioBtn() {
return isEnabled(moviesAndTvShowsRadioBtn);
}
public boolean checkMp3PlayersAndAccessoriesRadioBtn() {
return isEnabled(mp3PlayersAndAccessoriesRadioBtn);
}
public boolean checkMusicRadioBtn() {
return isEnabled(musicRadioBtn);
}
public boolean checkMusicalInstrumentsRadioBtn() {
return isEnabled(musicalInstrumentsRadioBtn);
}
public boolean checkNetworkingDevicesRadioBtn() {
return isEnabled(networkingDevicesRadioBtn);
}
public boolean checkOfficeAndSchoolSuppliesRadioBtn() {
return isEnabled(officeAndSchoolSuppliesRadioBtn);
}
public boolean checkPersonalCareRadioBtn() {
return isEnabled(personalCareRadioBtn);
}
public boolean checkPetSuppliesRadioBtn() {
return isEnabled(petSuppliesRadioBtn);
}
public boolean checkShoeCareAndAccessoriesRadioBtn() {
return isEnabled(shoeCareAndAccessoriesRadioBtn);
}
public boolean checkRefrigeratorsRadioBtn() {
return isEnabled(refrigeratorsRadioBtn);
}
public boolean checkShoesBoysRadioBtn() {
return isEnabled(shoesBoysRadioBtn);
}
public boolean checkShoesMensRadioBtn() {
return isEnabled(shoesMensRadioBtn);
}
public boolean checkShoesWomensRadioBtn() {
return isEnabled(shoesWomensRadioBtn);
}
public boolean checkShowersRadioBtn() {
return isEnabled(showersRadioBtn);
}
public boolean checkSoftwareRadioBtn() {
return isEnabled(softwareRadioBtn);
}
public boolean checkSpeakersRadioBtn() {
return isEnabled(speakersRadioBtn);
}
public boolean checkSportingGoodsRadioBtn() {
return isEnabled(sportingGoodsRadioBtn);
}
public boolean checkSunglassesGirlsRadioBtn() {
return isEnabled(sunglassesGirlsRadioBtn);
}
public boolean checkSunglassesMensRadioBtn() {
return isEnabled(sunglassesMensRadioBtn);
}
public boolean checkSunglassesWomensRadioBtn() {
return isEnabled(sunglassesWomensRadioBtn);
}
public boolean checkTabletsRadioBtn() {
return isEnabled(tabletsRadioBtn);
}
public boolean checkTelevisionsRadioBtn() {
return isEnabled(televisionsRadioBtn);
}
public boolean checkToysRadioBtn() {
return isEnabled(toysRadioBtn);
}
public boolean checkVideoGamesRadioBtn() {
return isEnabled(videoGamesRadioBtn);
}
public boolean checkWatchesRadioBtn() {
return isEnabled(watchesRadioBtn);
}
public boolean checkWatchesKidsRadioBtn() {
return isEnabled(watchesKidsRadioBtn);
}
public boolean checkWatchesMensRadioBtn() {
return isEnabled(watchesMensRadioBtn);
}
public boolean checkWatchesWomensRadioBtn() {
return isEnabled(watchesWomensRadioBtn);
}
public boolean checkActiveRadioBtn() {
return isEnabled(activeRadioBtn);
}
public boolean checkMissedRadioBtn() {
return isEnabled(missedRadioBtn);
}
public boolean checkUpcomingRadioBtn() {
return isEnabled(upcomingRadioBtn);
}
public boolean checkUnder500RadioBtn() {
return isEnabled(under500RadioBtn);
}
public boolean checkBetween500And1000RadioBtn() {
return isEnabled(between500And1000RadioBtn);
}
public boolean checkBetween1000And2000RadioBtn() {
return isEnabled(between1000And2000RadioBtn);
}
public boolean checkBetween2000And5000RadioBtn() {
return isEnabled(between2000And5000RadioBtn);
}
public boolean checkAbove5000RadioBtn() {
return isEnabled(above5000RadioBtn);
}
public boolean checkClearLink() {
return isEnabled(clearLink);
}
public boolean checkDealOfDayLink() {
return isEnabled(dealOfDayLink);
}
public boolean checkCouponsLink() {
return isEnabled(couponsLink);
}
public boolean checkPrimeEarlyAccessDealsLink() {
return isEnabled(primeEarlyAccessDealsLink);
}
public boolean checkAppOnlyAccessDealsLink() {
return isEnabled(appOnlyAccessDealsLink);
}
public boolean checkAppEarlyAccessDealsLink() {
return isEnabled(appEarlyAccessDealsLink);
}
public boolean checkDiscount10perAndAboveLink() {
return isEnabled(discount10perAndAboveLink);
}
public boolean checkDiscount25perAndAboveLink() {
return isEnabled(discount25perAndAboveLink);
}
public boolean checkDiscount50perAndAboveLink() {
return isEnabled(discount50perAndAboveLink);
}
public boolean checkRating4AndAboveLink() {
return isEnabled(rating4AndAboveLink);
}
public boolean checkRating3AndAboveLink() {
return isEnabled(rating3AndAboveLink);
}
public boolean checkrating2AndAboveLink() {
return isEnabled(rating2AndAboveLink);
}
public boolean checkRating1AndAboveLink() {
return isEnabled(rating1AndAboveLink);
}
public boolean checkLightingDealsLink() {
return isEnabled(lightingDealsLink);
}
public boolean checkSavingAndSalesLink() {
return isEnabled(savingAndSalesLink);
}
}
<file_sep>package com.pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.baseClass.LibGlobal;
public class Mobilespage extends LibGlobal {
public Mobilespage() {
PageFactory.initElements(driver, this);
}
@FindBy(xpath = "//img[@alt='Electronics']")
private WebElement electronicsTab;
@FindBy(xpath = "(//span[@class='nav-a-content'])[2]")
private WebElement mobilesAndAccDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[3]")
private WebElement laptopAndAccessoriesDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[4]")
private WebElement tvAndHomeEntertainmentDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[5]")
private WebElement audioDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[6]")
private WebElement camerasDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[7]")
private WebElement computerPeriferalsDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[8]")
private WebElement smartTechnologyDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[9]")
private WebElement musicalInstrumentsDD;
@FindBy(xpath = "(//span[@class='nav-a-content'])[10]")
private WebElement officeAndStationaryDD;
@FindBy(xpath = "(//a[@class='a-color-base a-link-normal'])[1]")
private WebElement backToElectronicsLink;
@FindBy(xpath = "(//a[@class='a-color-base a-link-normal'])[2]")
private WebElement mobileAccessoriesLink;
@FindBy(xpath = "(//a[@class='a-color-base a-link-normal'])[3]")
private WebElement simCardsLink;
@FindBy(xpath = "(//a[@class='a-color-base a-link-normal'])[4]")
private WebElement smartPhonesAndBasicMobilesLink;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[1]")
private WebElement madeForAmazonRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[2]")
private WebElement amazonPrimeRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[3]")
private WebElement elegibleForPayOnDeliveryRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[4]")
private WebElement redmiRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[5]")
private WebElement boatRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[6]")
private WebElement oneplusRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[7]")
private WebElement samsungRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[8]")
private WebElement jblRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[9]")
private WebElement ptronRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[10]")
private WebElement noiseRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[11]")
private WebElement todaysDealsRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[12]")
private WebElement apparioRetailRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[13]")
private WebElement shopMagicsRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[14]")
private WebElement sparewareRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[15]")
private WebElement goSaleRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[16]")
private WebElement pankajTelecomRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[17]")
private WebElement raghavEnterpriseRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[18]")
private WebElement dailyShoppersRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[19]")
private WebElement vishalSparesRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[20]")
private WebElement cloudTailRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[21]")
private WebElement cart2IndiaRadioBtn;
@FindBy(xpath = "(//i[@class='a-icon a-icon-checkbox'])[22]")
private WebElement includeOutOfStockRadioBtn;
@FindBy(xpath = "//i[@class='a-icon a-icon-star-medium a-star-medium-4']")
private WebElement rating4StarsAndAbove;
@FindBy(xpath = "//i[@class='a-icon a-icon-star-medium a-star-medium-3']")
private WebElement rating3StarsAndAbove;
@FindBy(xpath = "//i[@class='a-icon a-icon-star-medium a-star-medium-2']")
private WebElement rating2StarsAndAbove;
@FindBy(xpath = "//i[@class='a-icon a-icon-star-medium a-star-medium-1']")
private WebElement rating1StarsAndAbove;
@FindBy(xpath = "//span[text()='Last 30 days']")
private WebElement last30DaysLink;
@FindBy(xpath = "//span[text()='Last 90 days']")
private WebElement last90DaysLink;
@FindBy(xpath = "//span[text()='New']")
private WebElement newLink;
@FindBy(xpath = "//span[text()='Renewed']")
private WebElement renewedLink;
@FindBy(xpath = "//span[text()='Used']")
private WebElement usedLink;
@FindBy(xpath = "//span[text()='Under ₹1,000']")
private WebElement under1000Link;
@FindBy(xpath = "//span[text()='₹1,000 - ₹5,000']")
private WebElement bet1000And5000Link;
@FindBy(xpath = "//span[text()='₹5,000 - ₹10,000']")
private WebElement bet5000And10000Link;
@FindBy(xpath = "//span[text()='₹10,000 - ₹20,000']")
private WebElement bet10000And20000Link;
@FindBy(xpath = "//span[text()='Over ₹20,000']")
private WebElement over20000Link;
@FindBy(xpath = "//span[text()='10% Off or more']")
private WebElement discountMoreThan10percentLink;
@FindBy(xpath = "//span[text()='25% Off or more']")
private WebElement discountMoreThan25percentLink;
@FindBy(xpath = "//span[text()='35% Off or more']")
private WebElement discountMoreThan35percentLink;
@FindBy(xpath = "//span[text()='50% Off or more']")
private WebElement discountMoreThan50percentLink;
public boolean checkElectronicsLink() {
return isEnabled(electronicsTab);
}
public boolean checkmobilesAndAccDD() {
return isEnabled(mobilesAndAccDD);
}
public boolean checkLaptopAndAccessoriesDD() {
return isEnabled(laptopAndAccessoriesDD);
}
public boolean checkTvAndHomeEntertainmentDD() {
return isEnabled(tvAndHomeEntertainmentDD);
}
public boolean checkAudioDD() {
return isEnabled(audioDD);
}
public boolean checkCamerasDD() {
return isEnabled(camerasDD);
}
public boolean checkComputerPeriferalsDD() {
return isEnabled(computerPeriferalsDD);
}
public boolean checkSmartTechnologyDD() {
return isEnabled(smartTechnologyDD);
}
public boolean checkMusicalInstrumentsDD() {
return isEnabled(musicalInstrumentsDD);
}
public boolean checkOfficeAndStationaryDD() {
return isEnabled(officeAndStationaryDD);
}
public boolean checkBackToElectronicsLink() {
return isEnabled(backToElectronicsLink);
}
public boolean checkMobileAccessoriesLink() {
return isEnabled(mobileAccessoriesLink);
}
public boolean checkSimCardsLink() {
return isEnabled(simCardsLink);
}
public boolean checkSmartPhonesAndBasicMobilesLink() {
return isEnabled(smartPhonesAndBasicMobilesLink);
}
public boolean checkMadeForAmazonRadioBtn() {
return isEnabled(madeForAmazonRadioBtn);
}
public boolean checkAmazonPrimeRadioBtn() {
return isEnabled(amazonPrimeRadioBtn);
}
public boolean checkElegibleForPayOnDeliveryRadioBtn() {
return isEnabled(elegibleForPayOnDeliveryRadioBtn);
}
public boolean checkRedmiRadioBtn() {
return isEnabled(redmiRadioBtn);
}
public boolean checkBoatRadioBtn() {
return isEnabled(boatRadioBtn);
}
public boolean checkOneplusRadioBtn() {
return isEnabled(oneplusRadioBtn);
}
public boolean checkSamsungRadioBtn() {
return isEnabled(samsungRadioBtn);
}
public boolean checkJblRadioBtn() {
return isEnabled(jblRadioBtn);
}
public boolean checkPtronRadioBtn() {
return isEnabled(ptronRadioBtn);
}
public boolean checkTodaysDealsRadioBtn() {
return isEnabled(todaysDealsRadioBtn);
}
public boolean checkApparioRetailRadioBtn() {
return isEnabled(apparioRetailRadioBtn);
}
public boolean checkShopMagicsRadioBtn() {
return isEnabled(shopMagicsRadioBtn);
}
public boolean checkSparewareRadioBtn() {
return isEnabled(sparewareRadioBtn);
}
public boolean checkGoSaleRadioBtn() {
return isEnabled(goSaleRadioBtn);
}
public boolean checkNoiseRadioBtn() {
return isEnabled(noiseRadioBtn);
}
public boolean checkPankajTelecomRadioBtn() {
return isEnabled(pankajTelecomRadioBtn);
}
public boolean checkRaghavEnterpriseRadioBtn() {
return isEnabled(raghavEnterpriseRadioBtn);
}
public boolean checkDailyShoppersRadioBtn() {
return isEnabled(dailyShoppersRadioBtn);
}
public boolean checkVishalSparesRadioBtn() {
return isEnabled(vishalSparesRadioBtn);
}
public boolean checkCloudTailRadioBtn() {
return isEnabled(cloudTailRadioBtn);
}
public boolean checkCart2IndiaRadioBtn() {
return isEnabled(cart2IndiaRadioBtn);
}
public boolean checkIncludeOutOfStockRadioBtn() {
return isEnabled(includeOutOfStockRadioBtn);
}
public boolean checkRating4StarsAndAbove() {
return isEnabled(rating4StarsAndAbove);
}
public boolean checkRating3StarsAndAbove() {
return isEnabled(rating3StarsAndAbove);
}
public boolean checkRating2StarsAndAbove() {
return isEnabled(rating2StarsAndAbove);
}
public boolean checkRating1StarsAndAbove() {
return isEnabled(rating1StarsAndAbove);
}
public boolean checkLast30DaysLink() {
return isEnabled(last30DaysLink);
}
public boolean checkLast90DaysLink() {
return isEnabled(last90DaysLink);
}
public boolean checkNewLink() {
return isEnabled(newLink);
}
public boolean checkRenewedLink() {
return isEnabled(renewedLink);
}
public boolean checkUsedLink() {
return isEnabled(usedLink);
}
public boolean checkUnder1000Link() {
return isEnabled(under1000Link);
}
public boolean checkBet1000And5000Link() {
return isEnabled(bet1000And5000Link);
}
public boolean checkBet5000And10000Link() {
return isEnabled(bet5000And10000Link);
}
public boolean checkBet10000And20000Link() {
return isEnabled(bet10000And20000Link);
}
public boolean checkOver20000Link() {
return isEnabled(over20000Link);
}
public boolean checkDiscountMoreThan10percentLink() {
return isEnabled(discountMoreThan10percentLink);
}
public boolean checkDiscountMoreThan25percentLink() {
return isEnabled(discountMoreThan25percentLink);
}
public boolean checkDiscountMoreThan35percentLink() {
return isEnabled(discountMoreThan35percentLink);
}
public boolean checkDiscountMoreThan50percentLink() {
return isEnabled(discountMoreThan50percentLink);
}
}
<file_sep>package com.test;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.baseClass.LibGlobal;
import com.pom.AccountsAndListsDDHome;
import com.pom.HomePage;
public class HomePageTest extends LibGlobal {
HomePage home;
AccountsAndListsDDHome acc;
@BeforeMethod(groups = "only")
public void launchAmazonHomepage() {
launchBrowser("chrome");
getToUrl("https://www.amazon.in/");
home = new HomePage();
acc = new AccountsAndListsDDHome();
}
@Test
public void verifyMainMenuBar() {
boolean checkMainMenuBar = home.checkMainMenuBar();
Assert.assertTrue(checkMainMenuBar);
}
@Test
public void verifyAmazonLogo() {
boolean checkAmazonLogo = home.checkAmazonLogo();
Assert.assertTrue(checkAmazonLogo);
}
@Test
public void verifySelectAddressMenu() {
boolean SelectAddressMenu = home.checkSelectAddressMenu();
Assert.assertTrue(SelectAddressMenu);
}
@Test
public void verifyCategoriesDD() {
boolean checkCategoriesDD = home.checkCategoriesDD();
Assert.assertTrue(checkCategoriesDD);
}
@Test
public void verifyLanguageDD() {
boolean checkLanguageDD = home.checkLanguageDD();
Assert.assertTrue(checkLanguageDD);
}
@Test
public void verifySignInDD() {
boolean checkSignInDD = home.checkSignInDD();
Assert.assertTrue(checkSignInDD);
}
@Test
public void verifyReturnsAndOrdersMenu() {
boolean checkReturnsAndOrdersMenu = home.checkReturnsAndOrdersMenu();
Assert.assertTrue(checkReturnsAndOrdersMenu);
}
@Test
public void verifyCartMenu() {
boolean checkCartMenu = home.checkCartMenu();
Assert.assertTrue(checkCartMenu);
}
@Test
public void verifyGiftCardsNavBar() {
boolean checkGiftCardsNavBar = home.checkGiftCardsNavBar();
Assert.assertTrue(checkGiftCardsNavBar);
}
@Test
public void verifyBestSellersNavBar() {
boolean checkBestSellersNavBar = home.checkBestSellersNavBar();
Assert.assertTrue(checkBestSellersNavBar);
}
@Test
public void verifyMobilesNavBar() {
boolean checkMobilesNavBar = home.checkMobilesNavBar();
Assert.assertTrue(checkMobilesNavBar);
}
@Test
public void verifyTodaysDealsNavBar() {
boolean checkTodaysDealsNavBar = home.checkTodaysDealsNavBar();
Assert.assertTrue(checkTodaysDealsNavBar);
}
@Test
public void verifyNewReleasesNavBar() {
boolean checkNewReleasesNavBar = home.checkNewReleasesNavBar();
Assert.assertTrue(checkNewReleasesNavBar);
}
@Test
public void verifyCustomerServiceNavBar() {
boolean checkCustomerServiceNavBar = home.checkCustomerServiceNavBar();
Assert.assertTrue(checkCustomerServiceNavBar);
}
@Test
public void verifyScrollImageRight() {
boolean checkScrollImageRight = home.checkScrollImageRight();
Assert.assertTrue(checkScrollImageRight);
}
@Test
public void verifyScrollImageLeft() {
boolean checkScrollImageLeft = home.checkScrollImageLeft();
Assert.assertTrue(checkScrollImageLeft);
}
@Test
public void verifyBackToTopLink() {
boolean checkBackToTopLink = home.checkBackToTopLink();
Assert.assertTrue(checkBackToTopLink);
}
@Test
public void verifyAboutUsLink() {
boolean checkAboutUsLink = home.checkAboutUsLink();
Assert.assertTrue(checkAboutUsLink);
}
@Test
public void verifyCarrersLink() {
boolean checkCarrersLink = home.checkCarrersLink();
Assert.assertTrue(checkCarrersLink);
}
@Test
public void verifyPressReleasesLink() {
boolean checkPressReleasesLink = home.checkPressReleasesLink();
Assert.assertTrue(checkPressReleasesLink);
}
@Test
public void verifyAmazonCaresLink() {
boolean checkAmazonCaresLink = home.checkAmazonCaresLink();
Assert.assertTrue(checkAmazonCaresLink);
}
@Test
public void verifyGiftASmileLink() {
boolean checkGiftASmileLink = home.checkGiftASmileLink();
Assert.assertTrue(checkGiftASmileLink);
}
@Test
public void verifyFacebookLink() {
boolean checkFacebookLink = home.checkFacebookLink();
Assert.assertTrue(checkFacebookLink);
}
@Test
public void verifyTwitterLink() {
boolean checkTwitterLink = home.checkTwitterLink();
Assert.assertTrue(checkTwitterLink);
}
@Test
public void verifyInstagramLink() {
boolean checkInstagramLink = home.checkInstagramLink();
Assert.assertTrue(checkInstagramLink);
}
@Test
public void verifySellOnAmazon() {
boolean checkSellOnAmazon = home.checkSellOnAmazon();
Assert.assertTrue(checkSellOnAmazon);
}
@Test
public void verifySellUnderAmazonAceleratorLink() {
boolean checkSellUnderAmazonAceleratorLink = home.checkSellUnderAmazonAceleratorLink();
Assert.assertTrue(checkSellUnderAmazonAceleratorLink);
}
@Test
public void verifyBecomeAnAffiliateLink() {
boolean checkBecomeAnAffiliateLink = home.checkBecomeAnAffiliateLink();
Assert.assertTrue(checkBecomeAnAffiliateLink);
}
@Test
public void verifyFulfilmentByAmazonLink() {
boolean checkFulfilmentByAmazonLink = home.checkFulfilmentByAmazonLink();
Assert.assertTrue(checkFulfilmentByAmazonLink);
}
@Test
public void verifyAdvertiseYourProductsLink() {
boolean checkAdvertiseYourProductsLink = home.checkAdvertiseYourProductsLink();
Assert.assertTrue(checkAdvertiseYourProductsLink);
}
@Test
public void verifyAmazonPayOnMerchantsLink() {
boolean checkAmazonPayOnMerchantsLink = home.checkAmazonPayOnMerchantsLink();
Assert.assertTrue(checkAmazonPayOnMerchantsLink);
}
@Test
public void verifyCovid19AndAmazonLink() {
boolean checkCovid19AndAmazonLink = home.checkCovid19AndAmazonLink();
Assert.assertTrue(checkCovid19AndAmazonLink);
}
@Test
public void verifyYourAccountLink() {
boolean checkYourAccountLink = home.checkYourAccountLink();
Assert.assertTrue(checkYourAccountLink);
}
@Test
public void verifyReturnCentreLink() {
boolean checkReturnCentreLink = home.checkReturnCentreLink();
Assert.assertTrue(checkReturnCentreLink);
}
@Test
public void verifyPurchaseProtectionLink() {
boolean checkPurchaseProtectionLink = home.checkPurchaseProtectionLink();
Assert.assertTrue(checkPurchaseProtectionLink);
}
@Test
public void verifyAmazonAppDownloadLink() {
boolean checkAmazonAppDownloadLink = home.checkAmazonAppDownloadLink();
Assert.assertTrue(checkAmazonAppDownloadLink);
}
@Test
public void verifyAmazonAssistantDownloadLink() {
boolean checkAmazonAssistantDownloadLink = home.checkAmazonAssistantDownloadLink();
Assert.assertTrue(checkAmazonAssistantDownloadLink);
}
@Test
public void verifyHelpLink() {
boolean checkHelpLink = home.checkHelpLink();
Assert.assertTrue(checkHelpLink);
}
@Test
public void verifyAustraliaLink() {
boolean checkAustraliaLink = home.checkAustraliaLink();
Assert.assertTrue(checkAustraliaLink);
}
@Test
public void verifyBrazilLink() {
boolean checkBrazilLink = home.checkBrazilLink();
Assert.assertTrue(checkBrazilLink);
}
@Test
public void verifyCanadaLink() {
boolean checkCanadaLink = home.checkCanadaLink();
Assert.assertTrue(checkCanadaLink);
}
@Test
public void verifyChinaLink() {
boolean checkChinaLink = home.checkChinaLink();
Assert.assertTrue(checkChinaLink);
}
@Test
public void verifyFranceLink() {
boolean checkFranceLink = home.checkFranceLink();
Assert.assertTrue(checkFranceLink);
}
@Test
public void verifyGermanyLink() {
boolean checkGermanyLink = home.checkGermanyLink();
Assert.assertTrue(checkGermanyLink);
}
@Test
public void verifyItalyLink() {
boolean checkItalyLink = home.checkItalyLink();
Assert.assertTrue(checkItalyLink);
}
@Test
public void verifyJapanLink() {
boolean checkJapanLink = home.checkJapanLink();
Assert.assertTrue(checkJapanLink);
}
@Test
public void verifyMexicoLink() {
boolean checkMexicoLink = home.checkMexicoLink();
Assert.assertTrue(checkMexicoLink);
}
@Test
public void verifyNetherlandsLink() {
boolean checkNetherlandsLink = home.checkNetherlandsLink();
Assert.assertTrue(checkNetherlandsLink);
}
@Test
public void verifySingaporeLink() {
boolean SingaporeLink = home.checkSingaporeLink();
Assert.assertTrue(SingaporeLink);
}
@Test
public void verifySpainLink() {
boolean checkSpainLink = home.checkSpainLink();
Assert.assertTrue(checkSpainLink);
}
@Test
public void verifyUnitedArabEmiratesLink() {
boolean checkUnitedArabEmiratesLink = home.checkUnitedArabEmiratesLink();
Assert.assertTrue(checkUnitedArabEmiratesLink);
}
@Test
public void verifyUkLink() {
boolean checkUkLink = home.checkUkLink();
Assert.assertTrue(checkUkLink);
}
@Test
public void verifyUsLink() {
boolean checkUsLink = home.checkUsLink();
Assert.assertTrue(checkUsLink);
}
@Test
public void verifyAbeBooksLink() {
boolean checkAbeBooksLink = home.checkAbeBooksLink();
Assert.assertTrue(checkAbeBooksLink);
}
@Test
public void verifyAmazonWebServicesLink() {
boolean checkAmazonWebServicesLink = home.checkAmazonWebServicesLink();
Assert.assertTrue(checkAmazonWebServicesLink);
}
@Test
public void verifyAudibleLink() {
boolean checkAudibleLink = home.checkAudibleLink();
Assert.assertTrue(checkAudibleLink);
}
@Test
public void verifyDpReviewLink() {
boolean checkDpReviewLink = home.checkDpReviewLink();
Assert.assertTrue(checkDpReviewLink);
}
@Test
public void verifyImbdLink() {
boolean checkImbdLink = home.checkImbdLink();
Assert.assertTrue(checkImbdLink);
}
@Test
public void verifyShopBopLink() {
boolean checkShopBopLink = home.checkShopBopLink();
Assert.assertTrue(checkShopBopLink);
}
@Test
public void verifyAmazonBusinessLink() {
boolean checkShopBopLink = home.checkShopBopLink();
Assert.assertTrue(checkShopBopLink);
}
@Test
public void verifyPrimeNowLink() {
boolean checkShopBopLink = home.checkShopBopLink();
Assert.assertTrue(checkShopBopLink);
}
@Test
public void verifyAmazonPrimeMusicLink() {
boolean checkShopBopLink = home.checkShopBopLink();
Assert.assertTrue(checkShopBopLink);
}
@Test
public void verifyConditionsOfUseAndSaleLink() {
boolean checkConditionsOfUseAndSaleLink = home.checkConditionsOfUseAndSaleLink();
Assert.assertTrue(checkConditionsOfUseAndSaleLink);
}
@Test
public void verifyPrivacyNoticeLink() {
boolean checkPrivacyNoticeLink = home.checkPrivacyNoticeLink();
Assert.assertTrue(checkPrivacyNoticeLink);
}
@Test
public void verifyInterestBasedAdsLink() {
boolean checkInterestBasedAdsLink = home.checkInterestBasedAdsLink();
Assert.assertTrue(checkInterestBasedAdsLink);
}
@Test
public void changePincodeTest() throws InterruptedException {
home.changePincode("440001");
Thread.sleep(2000);
Assert.assertTrue(home.retrivePincode().contains("440001"));
}
@Test
public void chooseFromCategories() {
home.selectFromCategories("Amazon Devices");
}
@Test
public void searchForProduct() {
home.searchProducts("headphones");
}
@Test
public void changeLangToHindi() {
home.changeLanguageToHindi();
}
@Test
public void changeCountrytoAus() {
home.changeCountryToAustralia();
}
@Test(groups = "only")
public void checkAllLinksAvailInAccountsDD() {
home.mouseOverAccountsAndLists();
Assert.assertTrue(acc.checkCreateWishListLink(), "Wish list link is not enabled");
Assert.assertTrue(acc.checkFindWishListLink(), "Find wish list link is not enabled");
Assert.assertTrue(acc.checkWishFromAnyWebsiteLink(), "Wish from any website link is not enabled");
Assert.assertTrue(acc.checkBabyWishListLink(), "Baby wish list link is not enabled");
Assert.assertTrue(acc.checkDiscoverYourStyleLink(), "Discover your style link is not enabled");
Assert.assertTrue(acc.checkExploreShowroomLink(), "Explore showroom link is not enabled");
Assert.assertTrue(acc.checkYourAccountLink(), "Your account link is not enabled");
Assert.assertTrue(acc.checkYourOrdersLink(), "Your Orders link is not enabled");
Assert.assertTrue(acc.checkYourWishListLink(), "Your Wish list link is not enabled");
Assert.assertTrue(acc.checkYourRecommendationsLink(), "Your recommendations link is not enabled");
Assert.assertTrue(acc.checkYourPrimeMembershipLink(), "Your prime membership link is not enabled");
Assert.assertTrue(acc.checkYourPrimeVideoLink(), "Your prime video link is not enabled");
Assert.assertTrue(acc.checkYourSubscribeAndSavedItemsLink(), "Your subscribe and saved items link is not enabled");
Assert.assertTrue(acc.checkMembershipsAndSubscriptionLink(), "Memberships and subscription link is not enabled");
Assert.assertTrue(acc.checkYourAmazonBusinessAccountLink(), "Amazon business account link link is not enabled");
Assert.assertTrue(acc.checkYourSellerAccountLink(), "Your seller account link is not enabled");
Assert.assertTrue(acc.checkManageYourContentAndDevicesLink(), "Manage your content and devices link is not enabled");
}
@AfterMethod
public void quitBrowser() {
quit();
}
}
| 603b1df8456f3917605584b535e01a2a2b75457c | [
"Java"
] | 9 | Java | AmanK1010/AmazonProjectE2E | 232ae3e8dd5ee16d259222fa985fcafaa6c60099 | 595025425a956777a17e5c99217af5467550c13a |
refs/heads/main | <repo_name>MartinesKenyi/tabla-node<file_sep>/app.js
const { crearArchivo } = require('./helpers/multiplicar');
const argv = require('./config/yargs');
console.clear();
console.log(argv)
crearArchivo(argv.base, argv.listar, argv.hasta)
.then(nombreArchivo => { console.log(nombreArchivo)})
.catch(console.log);<file_sep>/salida/info.md
# informacion basica
Esta carperta es para alamacenar todos los doc de la tabla de multiplicacion
# base
--base o --b => numero a multiplicar
# listar
--listar o --l => para mostrar o listar en consola
# hasta
--hasta o --h => hasta que numero multiplicar | 1ab19779709065a7929310a2645984d54195361b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | MartinesKenyi/tabla-node | 234d0280600ff0c10fe6b6f09b2a11a39db54cab | d412775dc2682d08ba22e43e3fcb095f3cf3f685 |
refs/heads/master | <repo_name>AdiviaGP/crud<file_sep>/app/Http/Controllers/departmentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\department;
class departmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tampil = department::all();
return view('department', compact('tampil'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('tambah_department');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$tambah = new department;
$tambah -> nama_department = $request -> nama_department;
$tambah -> save();
return redirect()->back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$tampil = department::find($id);
return view('edit_department',compact('tampil'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$tampil = department::find($id);
$tampil -> nama_department = $request -> nama_department;
$tampil -> save();
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$delete = department::find($id);
$delete -> delete();
return redirect()->back();
}
}
| 739f38ad7411535ac32a9be74fe2f9930c63b5ec | [
"PHP"
] | 1 | PHP | AdiviaGP/crud | fa2edc56712b19ed9f09de5ee00e77ff5b7100ec | 51ae8427b618548540c6f4bb45cdeb0fbbababd7 |
refs/heads/master | <file_sep>import httplib2
import requests
def call_api(url, authen, data, method):
try:
if method == "GET" or method == "POST" or method =="PUT" or method =='':
response = requests.request(method,url,auth=(authen),data=data)
print(response.status_code)
if response.status_code >= 200 and response.status_code < 300:
status='OK'
elif response.status_code >= 400 and response.status_code < 500:
status='Erreur de paramètre'
elif response.status_code >= 500:
status='Erreur de serveur'
else:
status='Erreur inconnu'
print('Le status est '+status)
print(response.headers)
if not response.content:
print('Pas de contenu dans la réponse')
else:
print(response.content)
else:
print('Méthode non autorisée')
exit()
except ConnectionError:
print('Erreur de connexion est survenue'+response.reason)
except TimeoutError:
print('Connexion timeout')
return response
def main():
#url = 'https://sts.cdiscount.com/users/httpIssue.svc/?realm=https://wsvc.cdiscount.com/MarketplaceAPIService.svc'
authen=('***','***')
headers=('')
data=('')
method='GET'
call_api(url,authen,data,method)
if __name__ == '__main__':
main() | 39c708cd27b8fabebd8209ecfde8cd5eaa5104a8 | [
"Python"
] | 1 | Python | gauxinh/soundcloudpy | 29a89e5adce5aa3543c449666f5c5ab97454d9c4 | 948c6d2d06ffede2c474d1cc02b4ba75b8dfaf48 |
refs/heads/master | <repo_name>teskadera/dominoes_bot<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'cinch', '2.3.1'
group :development, :test do
gem 'minitest', '~> 5.8', '>= 5.8.3'
gem 'guard-minitest', '2.4.4'
gem 'minitest-reporters', '1.0.5'
end
<file_sep>/bin/dominoes_bot
#!/usr/bin/env ruby
#require 'dominoes_bot'
require "cinch"
<file_sep>/dominoes_bot.gemspec
Gem::Specification.new do |s|
s.name = 'dominoes_bot'
s.version = '0.0.1'
s.date = '2016-02-09'
s.summary = "A dominoes game via an IRC bot"
s.description = "My first shot at making an IRC bot, for a game my family often plays."
s.description += " When run on Heroku, run heroku scale web=0 bot=1"
s.homepage = "https://github.com/teskadera/dominoes_bot"
s.authors = ["<NAME>"]
s.email = ['<EMAIL>']
s.files = Dir["{lib}/**/*.rb", "bin/*", "LICENSE", "*.md"]
s.bindir = 'bin'
s.executables << 'dominoes_bot'
s.require_path = 'lib'
s.license = 'MIT'
s.add_development_dependency 'minitest', '~> 5.8', '>= 5.8.3'
s.add_development_dependency 'guard-minitest', '2.4.4'
s.add_development_dependency 'minitest-reporters', '1.0.5'
s.add_runtime_dependency 'cinch', '2.3.1'
end<file_sep>/test/test_helper.rb
# require 'test_helper' to use this
require "minitest/reporters"
Minitest::Reporters.use!
| 69d9eeab3e09aee2e8f9f85de648d2109a0d1306 | [
"Ruby"
] | 4 | Ruby | teskadera/dominoes_bot | f2caa68c8eda5568bd8ab521889e3bc33c52500a | c5d200c0e096bb5af6c9700bb626eb28ab257259 |
refs/heads/master | <file_sep>namespace ParseLogs.Models
{
public static class Messages
{
public const string IIS_WAITING = "Saving IIS log entries to database...";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace ParseLogs.Lib
{
public static class Utility
{
/// <summary>
/// Split the string
/// </summary>
/// <param name="stringToSplit"></param>
/// <param name="delimiter"></param>
/// <param name="qualifier"></param>
/// <returns></returns>
public static List<string> SplitString(string stringToSplit, char delimiter = ' ', char qualifier = '"')
{
var parts = stringToSplit.Split(qualifier)
.Select((element, index) => index % 2 == 0
? element.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries)
: new string[] { element })
.SelectMany(element => element).ToList();
return parts;
}
/// <summary>
/// Rotating characters to show activity.
/// </summary>
/// <param name="top"></param>
/// <param name="left"></param>
/// <param name="frameDelay"></param>
/// <param name="charFrames"></param>
public static void SpinnerProgress(int top = 0, int left = 0, int frameDelay = 500, string charFrames = @"|/-\")
{
foreach (char frame in charFrames)
{
Console.CursorTop = top;
Console.CursorLeft = left;
Thread.Sleep(frameDelay);
Console.Write(frame);
}
}
}
}
<file_sep>using ParseLogs.Lib;
using ParseLogs.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
namespace ParseLogs
{
class Program
{
static void Main(string[] args)
{
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
string logDirectory = ConfigurationManager.AppSettings["LogFilesDirectory"];
string databaseTable = ConfigurationManager.AppSettings["DatabaseTable"];
int maxEntries = Convert.ToInt32(ConfigurationManager.AppSettings["MaxEntriesToSaveToDatabase"]);
string logFile = logDirectory + @"\" + Guid.NewGuid().ToString().Split('-')[0] + ".log";
string headers = IIS.GetHeadersFromLogFile(logDirectory);
Console.Write("Merging all IIS Logs from directory...\n");
IIS.MergeIISLogsFromDirectory(headers, logDirectory, logFile);
Console.Write(Messages.IIS_WAITING);
try
{
// Let's make a mapping function to match class property names.
// If property is not assigned, then the column is ignored from
// the IIS file.
Func<string, IISEntry> mapper = line => new IISEntry()
{
logfile = Utility.SplitString(line)[0].Replace("PROD-Server_", "").Replace(".log", ""),
datestamp = Convert.ToDateTime(Utility.SplitString(line)[1] + " " + Utility.SplitString(line)[2]),
cs_method = Utility.SplitString(line)[4],
cs_uri_stem = Utility.SplitString(line)[5],
cs_uri_query = Utility.SplitString(line)[6] == "-" ? null : Utility.SplitString(line)[6],
cs_username = null,
c_ip = Utility.SplitString(line)[9] == "-" ? null : Utility.SplitString(line)[9],
cs_User_Agent = Utility.SplitString(line)[10],
cs_referer = Utility.SplitString(line)[11] == "-" ? null : Utility.SplitString(line)[11].Replace("https://[WEBSITE]", ""),
sc_status = Utility.SplitString(line)[12],
sc_win32_status = null,
time_taken_ms = Convert.ToInt32(Utility.SplitString(line)[15])
//sc_bytes = Utility.SplitString(line)[9],
//cs_bytes = Utility.SplitString(line)[10],
//s_computername = Utility.SplitString(line)[6].Substring(Math.Max(0, Utility.SplitString(line)[6].Length - 1)),
//time_local = null,
//s_contentpath = null,
};
List<IISEntry> entries = IIS.GetIISEntries(logFile, mapper, maxEntries);
IIS.SaveIISLogFileToDatabase(entries, connectionString, databaseTable, maxEntries);
Console.WriteLine("Complete!");
}
catch (Exception e)
{
Console.WriteLine("Stopped! Error: \n\n" + e.Message);
}
finally
{
// Let's delete the temp file if one was created.
File.Delete(logFile);
}
Console.WriteLine("done");
Console.ReadLine();
}
}
}<file_sep>using FastMember;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
namespace ParseLogs.Models
{
public static class IIS
{
/// <summary>
/// Dynamically bulk save.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iisEntries"></param>
/// <param name="connectionString"></param>
/// <param name="databaseTable"></param>
/// <param name="maxEntries"></param>
public static void SaveIISLogFileToDatabase<T>(IEnumerable<T> iisEntries, string connectionString, string databaseTable, int maxEntries = 100000)
{
string[] propertyNames = (new IISEntry()).GetType().GetProperties().Select(property => property.Name).ToArray();
using (var bcp = new SqlBulkCopy(connectionString))
{
using (var reader = ObjectReader.Create(iisEntries, propertyNames))
{
bcp.BatchSize = 5000;
bcp.BulkCopyTimeout = 30;
bcp.NotifyAfter = 1000;
bcp.SqlRowsCopied += (sender, e) =>
{
// Console.WriteLine("Wrote " + e.RowsCopied.ToString() + " records.");
var percentProgress = Math.Round((e.RowsCopied / (maxEntries * 1.0)) * 100, 0);
Console.CursorLeft = Messages.IIS_WAITING.Length + 1;
Console.CursorTop = 1;
Console.WriteLine(percentProgress.ToString() + "% complete.");
};
bcp.DestinationTableName = databaseTable;
// An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
// Additional information: A transport-level error has occurred when receiving results from the server.
// (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
bcp.WriteToServer(reader);
}
}
}
/// <summary>
/// Get List of all IIS entries.
/// </summary>
/// <param name="logFile"></param>
/// <param name="mapper"></param>
/// <param name="maxEntries"></param>
/// <returns></returns>
public static List<IISEntry> GetIISEntries(string logFile, Func<string, IISEntry> mapper, int maxEntries = 1000000)
{
List<IISEntry> list = new List<IISEntry>();
// Open the file stream
using (FileStream fs = File.Open(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// Represents the entire line in the file.
string line;
// Skip the headers.
sr.ReadLine();
// If there's a problem mapping columns from the IIS Log to an IISEntry object, let's save to a log file.
// List<string> errorLines = new List<string>();
int lineCount = 0;
// Read the Line into the string variable, ommitting headers if they were inserted already
while ((line = sr.ReadLine()) != null && lineCount <= maxEntries)
{
// Ignore IIS log comments.
if (line.IndexOf("#", 0) != 0)
{
try
{
IISEntry entry = mapper(line);
list.Add(entry);
}
catch
{
// TODO: Do something in case error.
}
lineCount++;
}
}
}
}
}
return list;
}
/// <summary>
/// Merges all IIS Logs in a directory into 1 IIS Log file, after scrubbing them. Removes all # comments and keeps headers.
/// Prepends the column "logfile" to signify the file associated with the log entries.
/// </summary>
/// <param name="headers"></param>
/// <param name="logDirectory"></param>
/// <param name="saveToFilePath"></param>
public static void MergeIISLogsFromDirectory(string headers, string logDirectory, string saveToFilePath)
{
var iisLogFiles = Directory.GetFiles(logDirectory, "*.log", SearchOption.AllDirectories);
var iisLogFilesForToday = new List<string>();
// Let's just get the files that were generated today.
foreach (var item in iisLogFiles)
{
// Go far back 0 days; meaning today's files. If 1, then goes back 1 day, 2, then two days, and so on.
int dateOffset = 0;
if (File.GetLastWriteTime(item) >= DateTime.Now.AddDays(-dateOffset).Date)
{
iisLogFilesForToday.Add(item);
}
}
// Loop through the files in directory.
using (StreamWriter sw = new StreamWriter(saveToFilePath))
{
sw.WriteLine(headers);
foreach (string logFilePath in iisLogFilesForToday)
{
ScrubIISLog(sw, logFilePath);
}
}
}
/// <summary>
/// Gets a string containing log file header names, comma separated.
/// </summary>
/// <returns></returns>
public static string GetHeadersFromLogFile(string logDirectory)
{
string headers = "";
string firstFile = Directory.GetFiles(logDirectory).First();
using (FileStream fs = File.Open(firstFile, FileMode.Open, FileAccess.Read))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// Represents the entire line in the file.
string line;
while ((line = sr.ReadLine()) != null)
{
string fieldsHeader = "#Fields";
if (line.IndexOf(fieldsHeader, 0) == 0)
{
headers = line.Replace(fieldsHeader + ": ", "");
headers = "logfile " + headers;
break;
}
}
}
}
}
return headers;
}
/// <summary>
/// Cleans up IIS logs by removing all headers except the first one.
/// </summary>
/// <param name="sw"></param>
/// <param name="path"></param>
public static void ScrubIISLog(StreamWriter sw, string path)
{
// Open the file stream
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// Represents the entire line in the file.
string line;
// Read the Line into the string variable, ommitting headers if they were inserted already
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf("#", 0) != 0)
{
sw.WriteLine(path.Split('\\').Last() + " " + line);
}
}
}
}
}
}
}
}<file_sep># IIS Log Parser
Combines all the IIS log files inside a directory and combines it into one, removing log comments. Then it dumps it in a database table. It uses [fast-member](https://github.com/mgravell/fast-member) and SQLBulkCopy to import gigs of data in a short amount of time.
## Usage
First, create a mapping function that maps column headers from the log to the IISEntry class properties. The array index is the column order number:
```csharp
Func<string, IISEntry> mapper = line => new IISEntry()
{
logfile = Utility.SplitString(line)[0]),
datestamp = Convert.ToDateTime(Utility.SplitString(line)[1] + " " + Utility.SplitString(line)[2]),
cs_method = Utility.SplitString(line)[4],
cs_uri_stem = Utility.SplitString(line)[5],
cs_uri_query = Utility.SplitString(line)[6] == "-" ? null : Utility.SplitString(line)[6],
cs_username = null,
c_ip = Utility.SplitString(line)[9] == "-" ? null : Utility.SplitString(line)[9],
cs_User_Agent = Utility.SplitString(line)[10],
cs_referer = Utility.SplitString(line)[11] == "-" ? null : Utility.SplitString(line)[11],
sc_status = Utility.SplitString(line)[12],
sc_win32_status = null,
time_taken_ms = Convert.ToInt32(Utility.SplitString(line)[15])
};
```
Then make a list of entries from the files in a directory.
```csharp
List<IISEntry> entries = IIS.GetIISEntries(logFile, mapper, maxEntries);
```
Lastly, save it to a database table.
```csharp
IIS.SaveIISLogFileToDatabase(entries, connectionString, databaseTable, maxEntries);
```
# Setup
First create the table. SQL file inside config/
```sql
CREATE TABLE [dbo].[IISLog](
[logfile] [NVARCHAR](255) NULL,
[datestamp] [DATETIME] NULL,
[cs_method] [NVARCHAR](255) NULL,
[cs_uri_stem] [NVARCHAR](4000) NULL,
[cs_uri_query] [NVARCHAR](4000) NULL,
[cs_username] [NVARCHAR](255) NULL,
[c_ip] [NVARCHAR](255) NULL,
[cs_User_Agent] [NVARCHAR](4000) NULL,
[cs_referer] [NVARCHAR](4000) NULL,
[sc_status] [NVARCHAR](255) NULL,
[sc_win32_status] [NVARCHAR](255) NULL,
[time_taken_ms] [INT] NULL
) ON [PRIMARY]
GO
```
Lastly, update the App.config to target your environment.
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License
[MIT](https://choosealicense.com/licenses/mit/)
<file_sep>public class IISEntry
{
public string logfile { get; set; }
public DateTime datestamp { get; set; }
public string cs_uri_stem { get; set; }
public string cs_uri_query { get; set; }
public string s_contentpath { get; set; }
public string sc_status { get; set; }
public string s_computername { get; set; }
public string cs_referer { get; set; }
public string sc_win32_status { get; set; }
public string sc_bytes { get; set; }
public string cs_bytes { get; set; }
public string c_ip { get; set; }
public string cs_method { get; set; }
public int time_taken_ms { get; set; }
public Nullable<DateTime> time_local { get; set; }
public string cs_User_Agent { get; set; }
public string cs_username { get; set; }
} | 2ebdbbc37bf152c6fb23b8ae302727dfb2088da5 | [
"Markdown",
"C#"
] | 6 | C# | shinylightdev/ParseLogs | 323fd67656f2ef4f1de44c573faccd678aaee43f | f52fff16359b3cab37bd89f518d6b52baed2c382 |
refs/heads/master | <file_sep>using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RFIDApp.Models;
namespace RFIDApp.Functions
{
public static class Create
{
[FunctionName("Create")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
[Table("RFID", Connection = "AzureWebJobsStorage")] IAsyncCollector<RFIDTable> rfidTableCollector,
ILogger log)
{
log.LogInformation("Create HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var rfidDto = JsonConvert.DeserializeObject<CreateRFIDDto>(requestBody);
if (rfidDto?.TagId == null)
{
return new BadRequestObjectResult("TagId value is missing");
}
var rfid = new RFIDTable(rfidDto.TagId);
await rfidTableCollector.AddAsync(rfid);
return new OkObjectResult($"RFID tag id: {rfid.TagId} is saved to table storage");
}
}
}
<file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Cosmos.Table;
using RFIDApp.Models;
namespace RFIDApp.Functions
{
public static class Authentication
{
[FunctionName("Authentication")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
[Table("RFID", Connection = "AzureWebJobsStorage")] CloudTable cloudTable,
ILogger log)
{
log.LogInformation("Authentication HTTP trigger function processed a request.");
string tagId = req.Query["tagId"];
var operation = TableOperation.Retrieve<RFIDTable>("RFID", tagId);
var query = await cloudTable.ExecuteAsync(operation);
var rfid = query.Result;
return new OkObjectResult(rfid != null);
}
}
}
<file_sep>using System;
namespace RFIDApp.Models
{
public class CreateRFIDDto
{
public string TagId { get; set; }
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Xunit;
using RFIDApp.Functions;
using RFIDApp.Models;
using Newtonsoft.Json;
using RFIDApp.Tests.Helpers;
using Microsoft.Extensions.Logging.Abstractions;
namespace RFIDApp.Tests
{
public class RFIDFunctionTests
{
private readonly ILogger logger = NullLoggerFactory.Instance.CreateLogger("Null Logger");
[Fact]
public async void Http_trigger_create_should_return_rfid_tagAsync()
{
var rfid = new RFIDTable("0E00010001");
var request = TestFactory.CreateHttpRequestWithBody(JsonConvert.SerializeObject(rfid));
var collector = new AsyncCollector<RFIDTable>();
OkObjectResult response = (OkObjectResult)await Create.Run(request, collector, logger);
Assert.Equal($"RFID tag id: {rfid.TagId} is saved to table storage", response.Value);
}
[Fact]
public async void Http_trigger_create_empty_tagid_should_return_bad_request_object_result()
{
var rfid = new RFIDTable(null);
var request = TestFactory.CreateHttpRequestWithBody(JsonConvert.SerializeObject(rfid));
var collector = new AsyncCollector<RFIDTable>();
BadRequestObjectResult response = (BadRequestObjectResult)await Create.Run(request, collector, logger);
Assert.Equal("TagId value is missing", response.Value);
}
[Fact]
public async void Http_trigger_create_null_body_result_should_return_bad_request_object_result()
{
var request = TestFactory.CreateHttpRequestWithBody(null);
var collector = new AsyncCollector<RFIDTable>();
BadRequestObjectResult response = (BadRequestObjectResult)await Create.Run(request, collector, logger);
Assert.Equal("TagId value is missing", response.Value);
}
[Fact]
public async void Http_trigger_authentication_should_return_true()
{
var request = TestFactory.CreateHttpRequestWithQueryString("tagId", "0E00010001");
OkObjectResult response = (OkObjectResult)await Authentication.Run(request, new MockCloudTable(), logger);
Assert.Equal(true, response.Value);
}
[Fact]
public async void Http_trigger_authentication_should_return_false()
{
var request = TestFactory.CreateHttpRequestWithQueryString("tagId", "0E00010003");
OkObjectResult response = (OkObjectResult)await Authentication.Run(request, new MockCloudTable(), logger);
Assert.Equal(false, response.Value);
}
}
}
<file_sep>using Microsoft.Azure.Cosmos.Table;
namespace RFIDApp.Models
{
public class RFIDTable : TableEntity
{
public RFIDTable() { }
public RFIDTable(string tagId)
{
RowKey = tagId;
PartitionKey = "RFID";
TagId = tagId;
}
public string TagId { get; set; }
}
}
<file_sep>using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
namespace RFIDApp.Tests.Helpers
{
public class MockCloudTable : CloudTable
{
public MockCloudTable() : base(new Uri("http://127.0.0.1:10002/devstoreaccount1/RFID"))
{
}
public MockCloudTable(Uri tableAddress) : base(tableAddress)
{ }
public MockCloudTable(StorageUri tableAddress, StorageCredentials credentials) : base(tableAddress, credentials)
{ }
public MockCloudTable(Uri tableAbsoluteUri, StorageCredentials credentials) : base(tableAbsoluteUri, credentials)
{ }
public async override Task<TableResult> ExecuteAsync(TableOperation operation)
{
var rowKey = operation
.GetType()
.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(prop => prop.Name == "RowKey")
.GetValue(operation);
return await Task.FromResult(new TableResult
{
Result = TestFactory.Data().FirstOrDefault(x => x.RowKey.Equals(rowKey)),
HttpStatusCode = 200
});
}
}
}
<file_sep>using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Primitives;
using RFIDApp.Models;
namespace RFIDApp.Tests
{
public class TestFactory
{
public static IEnumerable<RFIDTable> Data()
{
return new List<RFIDTable>
{
new RFIDTable("0E00010001"),
new RFIDTable("0E00020002"),
new RFIDTable("0E00030003")
};
}
private static Dictionary<string, StringValues> CreateDictionary(string key, string value)
{
var qs = new Dictionary<string, StringValues>
{
{ key, value }
};
return qs;
}
public static HttpRequest CreateHttpRequestWithQueryString(string queryStringKey, string queryStringValue)
{
var context = new DefaultHttpContext();
var request = context.Request;
request.Query = new QueryCollection(CreateDictionary(queryStringKey, queryStringValue));
return request;
}
public static HttpRequest CreateHttpRequestWithBody(string body)
{
var context = new DefaultHttpContext();
var request = context.Request;
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(body);
writer.Flush();
stream.Position = 0;
request.Body = stream;
return request;
}
}
}
| f235c153afa93285e73fed838ed8da1128fa9783 | [
"C#"
] | 7 | C# | eblomst/CleverInterview | b515dd0f7863c7b358cdb7d16c7d93ccb36fe0d0 | 2b2a1f50571fb3979d875a0880b521eed4c93f26 |
refs/heads/main | <file_sep>from __future__ import print_function, division
from torch.utils.data import Dataset, DataLoader
import scipy.io as scp
from keras.utils import to_categorical
import numpy as np
import torch
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from matplotlib import pyplot as plt
from scipy.stats.stats import pearsonr
from block import fusions
twenty_six_labels = {'Affection': ['loving', 'friendly'], 'Anger': ['anger', 'furious', 'resentful', 'outraged', 'vengeful'],
'Annoyance': ['annoy', 'frustrated', 'irritated', 'agitated', 'bitter', 'insensitive', 'exasperated', 'displeased'],
'Anticipation': ['optimistic', 'hopeful', 'imaginative', 'eager'],
'Aversion': ['disgusted', 'horrified', 'hateful'],
'Confidence': ['confident', 'proud', 'stubborn', 'defiant', 'independent', 'convincing'],
'Disapproval': ['disapproving', 'hostile', 'unfriendly', 'mean', 'disrespectful', 'mocking', 'condescending', 'cunning', 'manipulative', 'nasty', 'deceitful', 'conceited', 'sleazy', 'greedy', 'rebellious', 'petty'],
'Disconnection': ['indifferent', 'bored', 'distracted', 'distant', 'uninterested', 'self-centered', 'lonely', 'cynical', 'restrained', 'unimpressed', 'dismissive'] ,
'Disquietment': ['worried', 'nervous', 'tense', 'anxious','afraid', 'alarmed', 'suspicious', 'uncomfortable', 'hesitant', 'reluctant', 'insecure', 'stressed', 'unsatisfied', 'solemn', 'submissive'] ,
'Doubt/Conf': ['confused', 'skeptical', 'indecisive'] ,
'Embarrassment': ['embarrassed', 'ashamed', 'humiliated'] ,
'Engagement': ['curious', 'serious', 'intrigued', 'persistent', 'interested', 'attentive', 'fascinated'] ,
'Esteem': ['respectful', 'grateful'] ,
'Excitement': ['excited', 'enthusiastic', 'energetic', 'playful', 'impatient', 'panicky', 'impulsive', 'hasty'] ,
'Fatigue': ['tired', 'sleepy', 'drowsy'] ,
'Fear': ['scared', 'fearful', 'timid', 'terrified'] ,
'Happiness': ['cheerful', 'delighted', 'happy', 'amused', 'laughing', 'thrilled', 'smiling', 'pleased', 'overwhelmed', 'ecstatic', 'exuberant'] ,
'Pain': ['pain'] ,
'Peace': ['content', 'relieved', 'relaxed', 'calm', 'quiet', 'satisfied', 'reserved', 'carefree'] ,
'Pleasure': ['funny', 'attracted', 'aroused', 'hedonistic', 'pleasant', 'flattered', 'entertaining', 'mesmerized'] ,
'Sadness': ['sad', 'melancholy', 'upset', 'disappointed', 'discouraged', 'grumpy', 'crying', 'regretful', 'grief-stricken', 'depressed', 'heartbroken', 'remorseful', 'hopeless', 'pensive', 'miserable'] ,
'Sensitivity': ['apologetic', 'nostalgic'] ,
'Suffering': ['offended', 'hurt', 'insulted', 'ignorant', 'disturbed', 'abusive', 'offensive'],
'Surprise': ['surprise', 'surprised', 'shocked', 'amazed', 'startled', 'astonished', 'speechless', 'disbelieving', 'incredulous'],
'Sympathy': ['kind', 'compassionate', 'supportive', 'sympathetic', 'encouraging', 'thoughtful', 'understanding', 'generous', 'concerned', 'dependable', 'caring', 'forgiving', 'reassuring', 'gentle'],
'Yearning': ['jealous', 'determined', 'aggressive', 'desperate', 'focused', 'dedicated', 'diligent'] ,
'None': ['None']}
class MovieGraphDataset(Dataset):
def __init__(self, data):
self.data = data
self.movie_idx = list(self.data.keys()) # ['tt03045', 'tt0840830' ...] etc
self.num_samples = len(list(self.data.keys())) # 51 movies ideally
self.new_data = {}
for movie in self.movie_idx:
num_clips = list(self.data[movie].keys())
self.new_data[movie] = []
self.new_data[movie].append(len(num_clips))
self.new_data[movie].append( np.array([self.data[movie][clip]['face'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['va'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['embed_description'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['embed_situation'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['embed_scene'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['embed_transcript'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['emotions'] for clip in num_clips]) )
for f in range(len(num_clips)):
emot_labels = self.new_data[movie][7][f]
if len(emot_labels) == 0:
emot_labels.append('None')
labels = list(twenty_six_labels.keys())
integer_mapping = {x: i for i, x in enumerate(labels)}
vec = [integer_mapping[word] for word in labels]
encoded = to_categorical(vec)
emot_encoding = []
for emot in emot_labels:
emot_encoding.append(list(encoded[integer_mapping[emot]]))
emot_labels = [sum(x) for x in zip(*emot_encoding)]
self.new_data[movie][7][f] = emot_labels
self.new_data[movie][7] = np.array(list(self.new_data[movie][7]))
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
idx = self.movie_idx[idx]
F = self.new_data[idx][1]
Va = self.new_data[idx][2]
emb_desc = self.new_data[idx][3]
emb_sit = self.new_data[idx][4]
emb_sce = self.new_data[idx][5]
emb_trans = self.new_data[idx][6]
y = self.new_data[idx][7]
combined = np.hstack([F, Va, emb_desc, emb_sit, emb_sce, emb_trans])
F = torch.Tensor(F)
Va = torch.Tensor(Va)
emb_desc = torch.Tensor(emb_desc)
emb_sit = torch.Tensor(emb_sit)
emb_sce = torch.Tensor(emb_sce)
emb_trans = torch.Tensor(emb_trans)
# Instantiate fusion classes
fusion1 = fusions.Block([F.shape[1], Va.shape[1]], emb_desc.shape[1])
fusion2 = fusions.Block([emb_desc.shape[1], emb_desc.shape[1]], F.shape[1] + Va.shape[1] + emb_desc.shape[1])
fusion3 = fusions.Block([emb_sit.shape[1], emb_sce.shape[1]], emb_trans.shape[1])
fusion4 = fusions.Block([emb_trans.shape[1], emb_trans.shape[1]], emb_sit.shape[1] + emb_sce.shape[1] + emb_trans.shape[1])
# compute fusions
temp_output_fusion1 = fusion1([F, Va])
first_three= fusion2([temp_output_fusion1, emb_desc])
temp_output_fusion2 = fusion3([emb_sit, emb_sce])
second_three = fusion4([temp_output_fusion2, emb_trans])
fusion5 = fusions.Block([first_three.shape[1], second_three.shape[1]], first_three.shape[1]+second_three.shape[1])
final_fused = fusion5([first_three, second_three])
return combined, y, F, Va, emb_desc, emb_sit, emb_sce, emb_trans
def adjust_learning_rate(optimizer, epoch, lr):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if epoch == 100:
lr = lr * 0.1
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy_multihots(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
# maxk = max(topk)
# batch_size = target.size(0)
batch_size = 1
_, pred = output.topk(1, 1, True, True)
target_value = torch.gather(target, 1, pred)
# target_inds_one = (target != 0).nonzero()
correct_k = (target_value > 0).float().sum(0, keepdim=False).sum(0, keepdim=True)
correct_k /= target.shape[0]
res = (correct_k.mul_(100.0))
return res
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
<file_sep>from __future__ import division
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import warnings
warnings.filterwarnings('ignore')
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
def pad_shift(x, shift, padv=0.0):
"""Shift 3D tensor forwards in time with padding."""
if shift > 0:
padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv
return torch.cat((padding, x[:, :-shift, :]), dim=1)
elif shift < 0:
padding = torch.ones(x.size(0), -shift, x.size(2)).to(x.device) * padv
return torch.cat((x[:, -shift:, :], padding), dim=1)
else:
return x
def convolve(x, attn):
"""Convolve 3D tensor (x) with local attention weights (attn)."""
stacked = torch.stack([pad_shift(x, i) for
i in range(attn.shape[2])], dim=-1)
return torch.sum(attn.unsqueeze(2) * stacked, dim=-1)
class MovieNet(nn.Module):
"""Multimodal encoder-decoder LSTM model.
modalities -- list of names of each input modality
dims -- list of dimensions for input modalities
embed_dim -- dimensions of embedding for feature-level fusion
h_dim -- dimensions of LSTM hidden state
n_layers -- number of LSTM layers
attn_len -- length of local attention window
"""
def __init__(self, args, device=torch.device('cuda:0')):
super(MovieNet, self).__init__()
self.face_len = args['Face_length']
self.va_len = args['Va_length']
self.audio_len = args['audio_length']
self.scene_length = args['scene_length']
self.out_layer = args['out_layer']
self.total_mod_len = self.face_len + self.va_len +self.audio_len + self.scene_length
# self.total_mod_len = 3*(self.text_len)
self.embed_dim = args['embed_dim']
self.h_dim = args['h_dim']
self.n_layers = args['n_layers']
self.attn_len = args['attn_len']
self.dropout=0.5
self.face_linear = nn.Linear(self.face_len, self.h_dim, bias=True)
self.va_linear = nn.Linear(self.va_len, self.h_dim, bias=True)
self.audio_linear = nn.Linear(self.audio_len, self.h_dim, bias=True)
self.scene_linear = nn.Linear(self.scene_length, self.h_dim, bias=True)
self.att_linear1 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.att_linear2 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.att_linear3 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.att_linear4 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.att_linear5 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.att_linear6 = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim * 2, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim * 2, 1)
self.unimodal_face = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim, 1), nn.LeakyReLU())
self.unimodal_va = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim, 1), nn.LeakyReLU())
self.unimodal_audio = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim, 1), nn.LeakyReLU())
self.unimodal_scene = nn.Sequential(nn.Dropout(self.dropout),nn.Linear(self.h_dim, 1), nn.LeakyReLU()) #nn.Linear(self.h_dim,1)
self.shared_encoder = cLSTM(4,self.h_dim, batch_first=True).cuda(device=device)
self.enc_h0 = nn.Parameter(torch.rand(self.n_layers, 1, self.h_dim))
self.enc_c0 = nn.Parameter(torch.rand(self.n_layers, 1, self.h_dim))
# Decodes targets and LSTM hidden states
# self.decoder = nn.LSTM(1 + self.h_dim, self.h_dim, self.n_layers, batch_first=True)
self.decoder = nn.LSTM(6, self.h_dim, self.n_layers, batch_first=True)
self.dec_h0 = nn.Parameter(torch.rand(self.n_layers, 1, self.h_dim))
self.dec_c0 = nn.Parameter(torch.rand(self.n_layers, 1, self.h_dim))
# Final MLP output network
self.out = nn.Sequential(nn.Linear(self.h_dim, 2),#128
# nn.LeakyReLU(),
# nn.Linear(512, 8),
nn.LeakyReLU(),
nn.Linear(2, self.out_layer))
# Store module in specified device (CUDA/CPU)
self.device = (device if torch.cuda.is_available() else
torch.device('cpu'))
self.to(self.device)
def forward(self, x, face_features, va_features, scene_features, audio_features, target=None, tgt_init=0.0):
# Get batch dim
x = x.float()
face_features=face_features.float()
va_features=va_features.float()
audio_features=audio_features.float()
scene_features=scene_features.float()
batch_size, seq_len = x.shape[0], x.shape[1]
# Set initial hidden and cell states for encoder
h0 = self.enc_h0.repeat(1, batch_size, 1)
c0 = self.enc_c0.repeat(1, batch_size, 1)
# Convert raw features into equal-dimensional embeddings
# embed = self.embed(x)
face_features_rep = self.face_linear(face_features)
va_features_rep = self.va_linear(va_features)
audio_features_rep = self.audio_linear(audio_features)
scene_features_rep = self.scene_linear(scene_features)
concat_features = torch.cat([face_features_rep, va_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_1 = self.att_linear1(concat_features).squeeze(-1)
att_1 = torch.softmax(att_1, dim=-1)
concat_features = torch.cat([face_features_rep, audio_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_2 = self.att_linear2(concat_features).squeeze(-1)
att_2 = torch.softmax(att_2, dim=-1)
concat_features = torch.cat([face_features_rep, scene_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_3 = self.att_linear3(concat_features).squeeze(-1)
att_3 = torch.softmax(att_3, dim=-1)
concat_features = torch.cat([va_features_rep, audio_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_4 = self.att_linear4(concat_features).squeeze(-1)
att_4 = torch.softmax(att_4, dim=-1)
concat_features = torch.cat([va_features_rep, scene_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_5 = self.att_linear5(concat_features).squeeze(-1)
att_5 = torch.softmax(att_5, dim=-1)
concat_features = torch.cat([audio_features_rep, scene_features_rep], dim=-1)
# concat_features = torch.tanh(concat_features)
att_6 = self.att_linear6(concat_features).squeeze(-1)
att_6 = torch.softmax(att_6, dim=-1)
unimodal_va_input= va_features_rep
unimodal_va_input = self.unimodal_va(unimodal_va_input).squeeze(-1)
unimodal_va_input = torch.softmax(unimodal_va_input, dim=-1)
unimodal_face_input= face_features_rep
unimodal_face_input = self.unimodal_face(unimodal_face_input).squeeze(-1)
unimodal_face_input = torch.softmax(unimodal_face_input, dim=-1)
unimodal_audio_input= audio_features_rep
unimodal_audio_input = self.unimodal_audio(unimodal_audio_input).squeeze(-1)
unimodal_audio_input = torch.softmax(unimodal_audio_input, dim=-1)
unimodal_scene_input= scene_features_rep
unimodal_scene_input = self.unimodal_scene(unimodal_scene_input).squeeze(-1)
unimodal_scene_input = torch.softmax(unimodal_scene_input, dim=-1)
# print(unimodal_face_input.shape, unimodal_va_input.shape, unimodal_audio_input.shape, unimodal_scene_input.shape)
enc_input_unimodal_cat=torch.cat([unimodal_face_input, unimodal_va_input, unimodal_audio_input, unimodal_scene_input], dim=-1)
# print(enc_input_unimodal_cat.shape, batch_size, seq_len)
enc_input_unimodal_cat = enc_input_unimodal_cat.reshape(batch_size, seq_len, 4)
attn=torch.cat([att_1, att_2, att_3, att_4, att_5, att_6], dim=-1)
attn = attn.reshape(batch_size, seq_len, self.attn_len)
enc_out, _ = self.shared_encoder(enc_input_unimodal_cat)
# Undo the packing
# enc_out, _ = pad_packed_sequence(enc_out, batch_first=True)
# Convolve output with attention weights
# i.e. out[t] = a[t,0]*in[t] + ... + a[t,win_len-1]*in[t-(win_len-1)]
context = convolve(enc_out, attn)
# Set initial hidden and cell states for decoder
h0 = self.dec_h0.repeat(1, batch_size, 1)
c0 = self.dec_c0.repeat(1, batch_size, 1)
if target is not None:
# print(target[0].shape)
# exit()
target_0 = target[0].float().reshape(batch_size, seq_len, 1)
target_0 = torch.nn.Parameter(target_0).cuda()
target_1 = target[1].float().reshape(batch_size, seq_len, 1)
target_1 = torch.nn.Parameter(target_1).cuda()
# print(pad_shift(target, 1, tgt_init), context.shape)
# Concatenate targets from previous timesteps to context
dec_in = torch.cat([pad_shift(target_0, 1, tgt_init),pad_shift(target_1, 1, tgt_init), context], 2)
dec_out, _ = self.decoder(dec_in, (h0, c0))
# Undo the packing
dec_out = dec_out.reshape(-1, self.h_dim)
# dec_in = context
# dec_out, _ = self.decoder(dec_in, (h0, c0))
# dec_out = dec_out.reshape(-1, self.h_dim)
predicted = self.out(dec_out).view(batch_size, seq_len, self.out_layer)
else:
# Use earlier predictions to predict next time-steps
predicted = []
p = torch.ones(batch_size, 1).to(self.device) * tgt_init
h, c = h0, c0
for t in range(seq_len):
# Concatenate prediction from previous timestep to context
i = torch.cat([p, context[:, t, :]], dim=1).unsqueeze(1)
# Get next decoder LSTM state and output
o, (h, c) = self.decoder(i, (h, c))
# Computer prediction from output state
p = self.out(o.view(-1, self.h_dim))
predicted.append(p.unsqueeze(1))
predicted = torch.cat(predicted, dim=1)
# Mask target entries that exceed sequence lengths
# predicted = predicted * mask.float()
return predicted, enc_input_unimodal_cat, self.shared_encoder, att_1, att_2, att_3, att_4, att_5, att_6
<file_sep>from __future__ import print_function
import torch
from co_attn_GC_model import MovieNet
from utils import MovieDataset, adjust_learning_rate, eval_ccc
from torch.utils.data import DataLoader
import time
import math
import warnings
import pickle
import numpy as np
from matplotlib import pyplot as plt
warnings.filterwarnings("ignore")
from scipy.stats.stats import pearsonr
from block import fusions
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
args = {}
## Network Arguments
args['F_length'] = 32
args['A_length'] = 88
args['T_length'] = 300
args['dropout_prob'] = 0.5
args['use_cuda'] = True
args['encoder_size'] = 64
args['decoder_size'] = 128
args['dyn_embedding_size'] = 32
args['input_embedding_size'] = 32
args['train_flag'] = True
args['model_path'] = 'trained_models/rnned_finetune_traf_5_3.tar'
args['optimizer'] = 'adam'
args['embed_dim'] = 128
args['h_dim'] = 512
args['n_layers'] = 1
args['attn_len'] = 3
num_epochs = 10
batch_size = 1
lr=1e-4
with open('../data_dicts/train.pickle', 'rb') as handle:
train_raw = pickle.load(handle)
with open('../data_dicts/val.pickle', 'rb') as handle:
val_raw = pickle.load(handle)
with open('../data_dicts/test.pickle', 'rb') as handle:
test_raw = pickle.load(handle)
for key in list(test_raw.keys()):
is_any_nan = []
seq_len = test_raw[key][0]
f = test_raw[key][2]
is_any_nan.append(True in np.isnan(f))
a = test_raw[key][1]
is_any_nan.append(True in np.isnan(a))
t = test_raw[key][3]
is_any_nan.append(True in np.isnan(t))
if True in is_any_nan:
print(key, is_any_nan)
## Initialize data loaders
trSet = MovieDataset(train_raw)
valSet = MovieDataset(val_raw)
testSet= MovieDataset(test_raw)
trDataloader = DataLoader(trSet,batch_size=batch_size,shuffle=True,num_workers=8)
valDataloader = DataLoader(valSet,batch_size=batch_size,shuffle=True,num_workers=8)
testLoader = DataLoader(testSet,batch_size=batch_size,shuffle=True,num_workers=8)
# Initialize network
net = MovieNet(args)
print(net)
pytorch_total_params = sum(p.numel() for p in net.parameters() if p.requires_grad)
print(pytorch_total_params)
if args['use_cuda']:
net = net.cuda()
## Initialize optimizer
optimizer = torch.optim.RMSprop(net.parameters(), lr=lr) if args['optimizer']== 'rmsprop' else torch.optim.Adam(net.parameters(),lr=lr, weight_decay=0.9)
crossEnt = torch.nn.BCELoss()
mse = torch.nn.MSELoss(reduction='sum')
## Variables holding train and validation loss values:
train_loss = []
val_loss = []
ccc = []
prev_val_loss = math.inf
for epoch_num in range(num_epochs):
# """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
adjust_learning_rate(optimizer, epoch_num, lr)
## Train:_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
net.train()
# Variables to track training performance:
avg_tr_loss = 0
CCC = 0
for i, data in enumerate(trDataloader):
st_time = time.time()
train, labels, F, A, T = data
if args['use_cuda']:
train = torch.nn.Parameter(train).cuda()
F = torch.nn.Parameter(F).cuda()
A = torch.nn.Parameter(A).cuda()
T = torch.nn.Parameter(T).cuda()
labels = torch.nn.Parameter(labels).cuda()
train.requires_grad_()
F.requires_grad_()
A.requires_grad_()
T.requires_grad_()
labels.requires_grad_()
# Forward pass
emot_score, input_clstm, shared_encoder = net(train, F, A, T, labels)
train_model_gista(shared_encoder, input_clstm, lam=6.6, lam_ridge=1e-4, lr=0.001, max_iter=50, check_every=1000, truncation=64)
# GC_est = shared_encoder.GC().cpu().data.numpy()
# print('pred: ', emot_score, 'labels: ', labels)
emot_score = emot_score.squeeze(dim=0)
# if torch.max(emot_score) != 0:
# emot_score = ((emot_score - torch.min(emot_score))/(torch.max(emot_score) - torch.min(emot_score)))*100
labels = labels.squeeze(dim=0)
labels = (labels - torch.min(labels))/(torch.max(labels) - torch.min(labels))
# l = maskedMSE(emot_score, labels)
l = mse(emot_score, labels)
# Backprop and update weights
optimizer.zero_grad()
l.backward(retain_graph=True)
a = torch.nn.utils.clip_grad_norm_(net.parameters(), 10)
optimizer.step()
# Track average train loss and average train time:
batch_time = time.time()-st_time
avg_tr_loss += l.item()
# Calculate CCC Value
CCC += eval_ccc(emot_score, labels, CCC)
# print(CCC)
print("Epoch no:",epoch_num+1, "| Avg train loss:",format(avg_tr_loss/len(trSet),'0.4f'), "| Training CCC Value:", format(CCC/len(trSet)) )
# _________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
## Validate:______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
# net.eval()
avg_val_loss = 0
CCC = 0
for i, data in enumerate(valDataloader):
st_time = time.time()
val, labels, F, A, T = data
if args['use_cuda']:
val = torch.nn.Parameter(val, requires_grad=False).cuda()
F = torch.nn.Parameter(F, requires_grad=False).cuda()
A = torch.nn.Parameter(A, requires_grad=False).cuda()
T = torch.nn.Parameter(T, requires_grad=False).cuda()
labels = torch.nn.Parameter(labels, requires_grad=False).cuda()
# Forward pass
emot_score, embed, shared_encoder = net(val, F, A, T, labels)
emot_score = emot_score.squeeze(dim=1)
# if torch.max(emot_score) != 0:
# emot_score = ((emot_score - torch.min(emot_score)) / (torch.max(emot_score) - torch.min(emot_score))) * 100
labels = (labels - torch.min(labels))/(torch.max(labels) - torch.min(labels))
labels = labels.squeeze(dim=0)
l = mse(emot_score, labels)
avg_val_loss += l.item()
# Compute CCC
CCC += eval_ccc(emot_score, labels, CCC)
ccc.append(CCC/len(valSet))
# Print validation loss and update display variables
print('Validation loss :',format(avg_val_loss/len(valSet),'0.4f'), "| Validation CCC Value:", format(CCC/len(valSet)))
print("===================================================================================== \n" )
#__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
# ccc_smooth = signal.savgol_filter(l2_norm_bo, 97, 3)
# lr_ave = signal.savgol_filter(l2_norm_lr, 97, 3)
plt.plot(ccc)
plt.show()
torch.save(net.state_dict(), args['model_path'])
## Test:______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
# net.eval()
avg_test_loss = 0
CCC = 0
for i, data in enumerate(testLoader):
st_time = time.time()
test, labels, F, A, T = data
if args['use_cuda']:
test = torch.nn.Parameter(test, requires_grad=False).cuda()
F = torch.nn.Parameter(F, requires_grad=False).cuda()
A = torch.nn.Parameter(A, requires_grad=False).cuda()
T = torch.nn.Parameter(T, requires_grad=False).cuda()
labels = torch.nn.Parameter(labels, requires_grad=False).cuda()
# Forward pass
emot_score, embed, shared_encoder = net(test, F, A, T, labels)
emot_score = emot_score.squeeze(dim=1)
# if torch.max(emot_score) != 0:
# emot_score = ((emot_score - torch.min(emot_score)) / (torch.max(emot_score) - torch.min(emot_score))) * 100
labels = (labels - torch.min(labels))/(torch.max(labels) - torch.min(labels))
labels = labels.squeeze(dim=0)
l = mse(emot_score, labels)
avg_test_loss += l.item()
# Compute CCC
CCC += eval_ccc(emot_score, labels, CCC)
ccc.append(CCC/len(testSet))
# Print test loss and update display variables
print('Test loss :',format(avg_test_loss/len(testSet),'0.4f'), "| Test CCC Value:", format(CCC/len(testSet)))
print("===================================================================================== \n" )
<file_sep>from __future__ import print_function
import torch
from model_co_atnn_GC import MovieNet
from utils_co_attn import MovieGraphDataset, adjust_learning_rate, AverageMeter, accuracy_multihots
from torch.utils.data import DataLoader
import time
import math
import warnings
import pickle
import numpy as np
from matplotlib import pyplot as plt
warnings.filterwarnings("ignore")
from scipy.stats.stats import pearsonr
from block import fusions
import torch.nn.functional as F
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
args = {}
# MG DIMS
args['Face_length'] = 204
args['Va_length'] = 41
args['trans_length'] = 300
args['scene_length'] = 300
args['desc_length'] = 300
args['sit_length'] = 300
args['out_layer'] = 27
args['dropout_p rob'] = 0.5
args['use_cuda'] = True
args['encoder_size'] = 64
args['decoder_size'] = 128
args['dyn_embedding_size'] = 32
args['input_embedding_size'] = 32
args['train_flag'] = True
args['model_path'] = 'trained_models/rnned_finetune_traf_5_3.tar'
args['optimizer'] = 'adam'
args['embed_dim'] = 128
args['h_dim'] = 512
args['n_layers'] = 1
args['attn_len'] = 15
num_epochs = 10
batch_size = 1
lr = 1e-2
with open('./data_dicts/train.pickle', 'rb') as handle:
u = pickle._Unpickler(handle)
u.encoding = 'latin1'
train_raw = u.load()
with open('./data_dicts/val.pickle', 'rb') as handle:
v = pickle._Unpickler(handle)
v.encoding = 'latin1'
val_raw = v.load()
with open('./data_dicts/test.pickle', 'rb') as handle:
v = pickle._Unpickler(handle)
v.encoding = 'latin1'
test_raw = v.load()
## Initialize data loaders
trSet = MovieGraphDataset(train_raw)
valSet = MovieGraphDataset(val_raw)
testSet = MovieGraphDataset(test_raw)
trDataloader = DataLoader(trSet, batch_size=batch_size, shuffle=True, num_workers=8)
valDataloader = DataLoader(valSet, batch_size=batch_size, shuffle=True, num_workers=8)
testDataLoader = DataLoader(testSet, batch_size=batch_size, shuffle=True, num_workers=8)
# Initialize network
net = MovieNet(args)
print(net)
if args['use_cuda']:
net = net.cuda()
## Initialize optimizer
optimizer = torch.optim.RMSprop(net.parameters(), lr=lr) if args['optimizer']== 'rmsprop' else torch.optim.Adam(net.parameters(),lr=lr, weight_decay=0.9)
crossEnt = torch.nn.BCELoss()
mse = torch.nn.MSELoss(reduction='sum')
train_loss = []
val_loss = []
prev_val_loss = math.inf
for epoch_num in range(num_epochs):
adjust_learning_rate(optimizer, epoch_num, lr)
## Train
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
net.train()
epoch_loss = 0
acc = 0
for i, data in enumerate(trDataloader):
st_time = time.time()
train, labels, F, Va, emb_desc, emb_sit, emb_sce, emb_trans = data
if args['use_cuda']:
train = torch.nn.Parameter(train).cuda()
labels = torch.nn.Parameter(labels).cuda()
F = torch.nn.Parameter(F).cuda()
Va = torch.nn.Parameter(Va).cuda()
emb_desc = torch.nn.Parameter(emb_desc).cuda()
emb_sit = torch.nn.Parameter(emb_sit).cuda()
emb_sce = torch.nn.Parameter(emb_sce).cuda()
emb_trans = torch.nn.Parameter(emb_trans).cuda()
train.requires_grad_()
labels.requires_grad_()
F.requires_grad_()
Va.requires_grad_()
emb_desc.requires_grad_()
emb_sit.requires_grad_()
emb_sce.requires_grad_()
emb_trans.requires_grad_()
# Forward pass
emot_score, input_clstm, shared_encoder = net(train, F, Va, emb_desc, emb_sit, emb_sce, emb_trans, labels)
train_model_gista(shared_encoder, input_clstm, lam=6.6, lam_ridge=1e-4, lr=0.001, max_iter=10, check_every=1000, truncation=64)
# GC_est = shared_encoder.GC().cpu().data.numpy()
emot_score = emot_score.squeeze(dim=0)
labels = labels.squeeze(dim=0)
log_softmax = torch.nn.LogSoftmax(dim=1)
log_softmax_output = log_softmax(emot_score)
loss = - torch.sum(log_softmax_output * labels) / emot_score.shape[0]
losses.update(loss.item(), train.size(0))
prec1 = accuracy_multihots(emot_score, labels, topk=(1, 3))
top1.update(prec1[0], train.size(0))
acc += prec1[0]
epoch_loss += loss
optimizer.zero_grad()
loss.backward()
a = torch.nn.utils.clip_grad_norm_(net.parameters(), 10)
optimizer.step()
print("Epoch no:",epoch_num+1, "| Avg train loss:", format(epoch_loss/len(trSet),'0.4f'), "| Training Accuracy Value:", format(acc/len(trSet)) )
## Validate
net.eval()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
epoch_loss = 0
acc = 0
for i, data in enumerate(valDataloader):
st_time = time.time()
val, labels, F, Va, emb_desc, emb_sit, emb_sce, emb_trans = data
if args['use_cuda']:
val = torch.nn.Parameter(val, requires_grad=False).cuda()
labels = torch.nn.Parameter(labels, requires_grad=False).cuda()
F = torch.nn.Parameter(F, requires_grad=False).cuda()
Va = torch.nn.Parameter(Va, requires_grad=False).cuda()
emb_desc = torch.nn.Parameter(emb_desc, requires_grad=False).cuda()
emb_sit = torch.nn.Parameter(emb_sit, requires_grad=False).cuda()
emb_sce = torch.nn.Parameter(emb_sce, requires_grad=False).cuda()
emb_trans = torch.nn.Parameter(emb_trans, requires_grad=False).cuda()
# Forward pass
emot_score, input_clstm, shared_encoder = net(val, F, Va, emb_desc, emb_sit, emb_sce, emb_trans, labels)
emot_score = emot_score.squeeze(dim=0)
labels = labels.squeeze(dim=0)
log_softmax = torch.nn.LogSoftmax(dim=1)
log_softmax_output = log_softmax(emot_score)
loss = - torch.sum(log_softmax_output * labels) / emot_score.shape[0]
losses.update(loss.item(), val.size(0))
prec1 = accuracy_multihots(emot_score, labels, topk=(1, 3))
top1.update(prec1[0], val.size(0))
epoch_loss += loss
acc += prec1[0]
print("Epoch no:",epoch_num+1, "| Avg validation loss:", format(epoch_loss/len(valSet),'0.4f'), "| Validation Accuracy Value:", format(acc/len(valSet)))
print('---------------------------------------')
testDataLoader = DataLoader(testSet, batch_size=batch_size, shuffle=True, num_workers=8)
## Test
net.eval()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
avg_test_loss = 0
acc = 0
for i, data in enumerate(testDataLoader):
st_time = time.time()
test, labels, F, Va, emb_desc, emb_sit, emb_sce, emb_trans = data
if args['use_cuda']:
test = torch.nn.Parameter(test, requires_grad=False).cuda()
labels = torch.nn.Parameter(labels, requires_grad=False).cuda()
F = torch.nn.Parameter(F, requires_grad=False).cuda()
Va = torch.nn.Parameter(Va, requires_grad=False).cuda()
emb_desc = torch.nn.Parameter(emb_desc, requires_grad=False).cuda()
emb_sit = torch.nn.Parameter(emb_sit, requires_grad=False).cuda()
emb_sce = torch.nn.Parameter(emb_sce, requires_grad=False).cuda()
emb_trans = torch.nn.Parameter(emb_trans, requires_grad=False).cuda()
# Forward pass
emot_score, input_clstm, shared_encoder = net(test, F, Va, emb_desc, emb_sit, emb_sce, emb_trans, labels)
emot_score = emot_score.squeeze(dim=0)
labels = labels.squeeze(dim=0)
log_softmax = torch.nn.LogSoftmax(dim=1)
log_softmax_output = log_softmax(emot_score)
loss = - torch.sum(log_softmax_output * labels) / emot_score.shape[0]
losses.update(loss.item(), val.size(0))
prec1 = accuracy_multihots(emot_score, labels, topk=(1, 3))
top1.update(prec1[0], val.size(0))
avg_test_loss += loss
acc += prec1[0]
print('Test loss :',format(avg_test_loss/len(testSet),'0.4f'), "| Test Accuracy Value:", format(acc/len(testSet)))
print("===================================================================================== \n" )
<file_sep>from __future__ import print_function
import torch
from model_co_attn_GC import MovieNet
from utils_co_attn_GC import adjust_learning_rate, MediaEvalDataset, prsn, save_ckp, load_ckp
from torch.utils.data import DataLoader
import time
import math
import warnings
import pickle
import numpy as np
from matplotlib import pyplot as plt
warnings.filterwarnings("ignore")
from scipy.stats.stats import pearsonr
from block import fusions
import torch.nn.functional as F
from scipy.stats.mstats import pearsonr
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
args = {}
best_model_path="./best_model"
checkpoint_path="./checkpoints"
valid_loss_min=np.Inf
## Network Arguments
args['Face_length'] = 204
args['Va_length'] = 317
args['audio_length'] = 1583
args['scene_length'] = 4096
args['out_layer'] = 2
args['dropout_prob'] = 0.5
args['use_cuda'] = True
args['encoder_size'] = 64
args['decoder_size'] = 128
args['dyn_embedding_size'] = 32
args['input_embedding_size'] = 32
args['train_flag'] = True
args['model_path'] = 'trained_models/media_eval_model.tar'
args['optimizer'] = 'adam'
args['embed_dim'] = 512
args['h_dim'] = 512
args['n_layers'] = 1
args['attn_len'] = 6
num_epochs = 20
batch_size = 1
lr=1e-4
GC_est=None
with open('./data_dicts/train.pickle', 'rb') as handle:
u = pickle._Unpickler(handle)
u.encoding = 'latin1'
train_raw = u.load()
with open('./data_dicts/val.pickle', 'rb') as handle:
v = pickle._Unpickler(handle)
v.encoding = 'latin1'
# train_raw = pickle.load(handle)
val_raw = v.load()
with open('./data_dicts/test.pickle', 'rb') as handle:
v = pickle._Unpickler(handle)
v.encoding = 'latin1'
# train_raw = pickle.load(handle)
test_raw = v.load()
trSet = MediaEvalDataset(train_raw)
valSet = MediaEvalDataset(val_raw)
testSet = MediaEvalDataset(test_raw)
trDataloader = DataLoader(trSet,batch_size=batch_size,shuffle=True,num_workers=8)
valDataloader = DataLoader(valSet,batch_size=batch_size,shuffle=True,num_workers=8)
testDataloader = DataLoader(testSet,batch_size=batch_size,shuffle=True,num_workers=8)
# Initialize network
net = MovieNet(args)
if args['use_cuda']:
net = net.cuda()
## Initialize optimizer
optimizer = torch.optim.RMSprop(net.parameters(), lr=lr) if args['optimizer']== 'rmsprop' else torch.optim.Adam(net.parameters(),lr=lr, weight_decay=0.9)
# scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=0.01, max_lr=0.1)
crossEnt = torch.nn.BCELoss()
mse = torch.nn.MSELoss(reduction='sum')
for epoch_num in range(num_epochs):
# """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
adjust_learning_rate(optimizer, epoch_num, lr)
## Train:_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
net.train()
# Variables to track training performance:
avg_tr_loss = 0
for i, data in enumerate(trDataloader):
st_time = time.time()
train, labels, F, Va, scene, audio = data
labels1 = labels[0]
labels2= labels[1]
if args['use_cuda']:
train = torch.nn.Parameter(train).cuda()
labels1 = torch.nn.Parameter(labels1).cuda()
labels2 = torch.nn.Parameter(labels2).cuda()
F = torch.nn.Parameter(F).cuda()
Va = torch.nn.Parameter(Va).cuda()
scene = torch.nn.Parameter(scene).cuda()
audio = torch.nn.Parameter(audio).cuda()
train.requires_grad_()
labels1.requires_grad_()
labels2.requires_grad_()
F.requires_grad_()
Va.requires_grad_()
scene.requires_grad_()
audio.requires_grad_()
# Forward pass
emot_score, input_clstm, shared_encoder, att_1, att_2, att_3, att_4, att_5, att_6 = net(train, F, Va, scene, audio, labels)
train_model_gista(shared_encoder, input_clstm, lam=0.5, lam_ridge=1e-4, lr=0.001, max_iter=1, check_every=1000, truncation=64)
GC_est = shared_encoder.GC().cpu().data.numpy()
emot_score = emot_score.squeeze(dim=0)
labels1 = labels1.T
labels2 = labels2.T
emot_score = (2*(emot_score - torch.min(emot_score))/(torch.max(emot_score) - torch.min(emot_score))) -1
l = mse(emot_score[:,0].unsqueeze(dim=1), labels1) + mse(emot_score[:,1].unsqueeze(dim=1), labels2)
# Backprop and update weights
optimizer.zero_grad()
l.backward()
a = torch.nn.utils.clip_grad_norm_(net.parameters(), 10)
optimizer.step()
# scheduler.step()
avg_tr_loss += l.item()
# print(GC_est)
print("Epoch no:",epoch_num+1, "| Avg train loss:",format(avg_tr_loss/len(trSet),'0.4f') )
# _________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
## Validate:______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
net.eval()
valmse = 0
aromse = 0
valpcc = 0
aropcc = 0
for i, data in enumerate(valDataloader):
st_time = time.time()
val, labels, F, Va, scene, audio = data
labels1 = labels[0]
labels2 = labels[1]
if args['use_cuda']:
val = torch.nn.Parameter(val).cuda()
labels1 = torch.nn.Parameter(labels1).cuda()
labels2 = torch.nn.Parameter(labels2).cuda()
F = torch.nn.Parameter(F).cuda()
Va = torch.nn.Parameter(Va).cuda()
scene = torch.nn.Parameter(scene).cuda()
audio = torch.nn.Parameter(audio).cuda()
# Forward pass
emot_score, input_clstm, shared_encoder, att_1, att_2, att_3, att_4, att_5, att_6 = net(val, F, Va, scene, audio, labels)
emot_score = emot_score.squeeze(dim=0)
labels1 = labels1.T
labels2 = labels2.T
emot_score = (2*(emot_score - torch.min(emot_score))/(torch.max(emot_score) - torch.min(emot_score))) -1
# labels1 = (2*(labels1 - torch.min(labels1)))/(torch.max(labels1) - torch.min(labels1)) -1
# labels2 = (2*(labels2 - torch.min(labels2)))/(torch.max(labels2) - torch.min(labels2)) -1
valmse += mse(emot_score[:, 0].unsqueeze(dim=1), labels1)/labels1.shape[0]
aromse += mse(emot_score[:, 1].unsqueeze(dim=1), labels2)/labels2.shape[0]
valpcc += pearsonr(emot_score[:, 0].unsqueeze(dim=1).cpu().detach().numpy(), labels1.cpu().detach().numpy())[0]
aropcc += pearsonr(emot_score[:, 1].unsqueeze(dim=1).cpu().detach().numpy(), labels2.cpu().detach().numpy())[0]
epoch_valmse = valmse/len(valSet)
epoch_aromse = aromse/len(valSet)
epoch_valpcc = valpcc / len(valSet)
epoch_aropcc = aropcc / len(valSet)
val_loss=epoch_valmse
# val_loss=(epoch_aromse+epoch_valmse)/2
print("Epoch Valence MSE:", epoch_valmse.item() , "Epoch Arousal MSE:", epoch_aromse.item(),"\nEpoch Valence PCC:", epoch_valpcc.item() ,
"Epoch Arousal PCC:", epoch_aropcc.item(),"\n","==========================")
checkpoint = {
'epoch': epoch_num + 1,
'valid_loss_min_valence': epoch_valmse,
'valid_loss_min_arousal': epoch_aromse,
'state_dict': net.state_dict(),
'optimizer': optimizer.state_dict(),
}
# save checkpoint
save_ckp(checkpoint, False, checkpoint_path+"/train_co_attn_GC_current_checkpoint.pt", best_model_path+"/train_co_attn_GC_best_model.pt")
## TODO: save the model if validation loss has decreased
if val_loss <= valid_loss_min:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(valid_loss_min,val_loss))
# save checkpoint as best model
save_ckp(checkpoint, True, checkpoint_path+"/train_co_attn_GC_current_checkpoint.pt", best_model_path+"/train_co_attn_GC_best_model.pt")
valid_loss_min = val_loss
net=MovieNet(args)
net, optimizer, start_epoch, valid_loss_min_valence, valid_loss_min_arousal = load_ckp(best_model_path+"/train_co_attn_GC_best_model.pt", net, optimizer)
net.eval()
testmse = 0
aromse = 0
testpcc = 0
aropcc = 0
for i, data in enumerate(testDataloader):
st_time = time.time()
test, labels, F, Va, scene, audio = data
labels1 = labels[0]
labels2 = labels[1]
if args['use_cuda']:
test = torch.nn.Parameter(test).cuda()
labels1 = torch.nn.Parameter(labels1).cuda()
labels2 = torch.nn.Parameter(labels2).cuda()
F = torch.nn.Parameter(F).cuda()
Va = torch.nn.Parameter(Va).cuda()
scene = torch.nn.Parameter(scene).cuda()
audio = torch.nn.Parameter(audio).cuda()
# Forward pass
emot_score, input_clstm, shared_encoder, att_1, att_2, att_3, att_4, att_5, att_6 = net(test, F, Va, scene, audio, labels)
print(att_1, att_2, att_3, att_4, att_5, att_6)
emot_score = emot_score.squeeze(dim=0)
labels1 = labels1.T
labels2 = labels2.T
emot_score = (2*(emot_score - torch.min(emot_score))/(torch.max(emot_score) - torch.min(emot_score))) -1
print(emot_score)
# labels1 = (2*(labels1 - torch.min(labels1)))/(torch.max(labels1) - torch.min(labels1)) -1
# labels2 = (2*(labels2 - torch.min(labels2)))/(torch.max(labels2) - torch.min(labels2)) -1
testmse += mse(emot_score[:, 0].unsqueeze(dim=1), labels1)/labels1.shape[0]
aromse += mse(emot_score[:, 1].unsqueeze(dim=1), labels2)/labels2.shape[0]
testpcc += pearsonr(emot_score[:, 0].unsqueeze(dim=1).cpu().detach().numpy(), labels1.cpu().detach().numpy())[0]
aropcc += pearsonr(emot_score[:, 1].unsqueeze(dim=1).cpu().detach().numpy(), labels2.cpu().detach().numpy())[0]
test_testmse = testmse/len(testSet)
test_aromse = aromse/len(testSet)
test_testpcc = testpcc / len(testSet)
test_aropcc = aropcc / len(testSet)
print("Test Valence MSE:", test_testmse.item() , "Test Arousal MSE:", test_aromse.item(),"\Test Valence PCC:", test_testpcc.item() ,
"Test Arousal PCC:", test_aropcc.item(),"\n","==========================")
import csv
with open("GC_LIRIS.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(GC_est)
<file_sep>from __future__ import division
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import warnings
warnings.filterwarnings('ignore')
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
def pad_shift(x, shift, padv=0.0):
"""Shift 3D tensor forwards in time with padding."""
if shift > 0:
padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv
return torch.cat((padding, x[:, :-shift, :]), dim=1)
elif shift < 0:
padding = torch.ones(x.size(0), -shift, x.size(2)).to(x.device) * padv
return torch.cat((x[:, -shift:, :], padding), dim=1)
else:
return x
def convolve(x, attn):
"""Convolve 3D tensor (x) with local attention weights (attn)."""
stacked = torch.stack([pad_shift(x, i) for
i in range(attn.shape[2])], dim=-1)
return torch.sum(attn.unsqueeze(2) * stacked, dim=-1)
class MovieNet(nn.Module):
def __init__(self, args, device=torch.device('cuda:0')):
super(MovieNet, self).__init__()
self.face_len = args['Face_length']
self.audio_len = args['Va_length']
self.text_len = args['trans_length']
self.scene_length = args['scene_length']
self.desc_length = args['desc_length']
self.sit_length = args['sit_length']
self.out_layer = args['out_layer']
self.total_mod_len = self.face_len + self.audio_len +self.text_len + self.desc_length + self.sit_length + self.scene_length
# self.total_mod_len = 3*(self.text_len)
self.embed_dim = args['embed_dim']
self.h_dim = args['h_dim']
self.n_layers = args['n_layers']
self.attn_len = args['attn_len']
self.text_linear = nn.Linear(self.text_len, self.h_dim, bias=True)
self.face_linear = nn.Linear(self.face_len, self.h_dim, bias=True)
self.audio_linear = nn.Linear(self.audio_len, self.h_dim, bias=True)
self.scene_linear = nn.Linear(self.scene_length, self.h_dim, bias=True)
self.desc_linear = nn.Linear(self.desc_length, self.h_dim, bias=True)
self.sit_linear = nn.Linear(self.sit_length, self.h_dim, bias=True)
self.att_linear = nn.Linear(self.h_dim * 2, 1)
self.unimodal_text = nn.Linear(self.h_dim,1)
self.unimodal_face = nn.Linear(self.h_dim,1)
self.unimodal_audio = nn.Linear(self.h_dim,1)
self.unimodal_scene = nn.Linear(self.h_dim,1)
self.unimodal_desc = nn.Linear(self.h_dim,1)
self.unimodal_sit = nn.Linear(self.h_dim,1)
# Create raw-to-embed FC+Dropout layer for each modality
# self.embed = nn.Sequential(nn.Dropout(0.1),
# nn.Linear( self.total_mod_len, self.embed_dim),
# nn.ReLU())
# # self.add_module('embed_{}'.format(m), self.embed[m])
# # Layer that computes attention from embeddings
# self.attn = nn.Sequential(nn.Linear(self.embed_dim, self.embed_dim),
# nn.ReLU(),
# nn.Linear(self.embed_dim, self.attn_len),
# nn.Softmax(dim=1))
# Encoder computes hidden states from embeddings for each modality
self.shared_encoder = cLSTM(6,self.h_dim, batch_first=True).cuda(device=device)
# self.encoder = nn.LSTM(self.embed_dim, self.h_dim, self.n_layers, batch_first=True)
self.enc_h0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
self.enc_c0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
# Decodes targets and LSTM hidden states
# self.decoder = nn.LSTM(1 + self.h_dim, self.h_dim, self.n_layers, batch_first=True)
self.decoder = nn.LSTM(6, self.h_dim, self.n_layers, batch_first=True)
self.dec_h0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
self.dec_c0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
# Final MLP output network
self.out = nn.Sequential(nn.Dropout(0.1),nn.Linear(self.h_dim, 512),
nn.ReLU(),
# nn.Linear(self.h_dim, 512),
# nn.ReLU(),
# nn.Linear(self.h_dim, 512),
# nn.ReLU(),
nn.Linear(512, self.out_layer))
# Store module in specified device (CUDA/CPU)
self.device = (device if torch.cuda.is_available() else
torch.device('cpu'))
self.to(self.device)
def forward(self, x, face_features, audio_features, desc_features, sit_features , scene_features, text_features , target=None, tgt_init=0.0):
# Get batch dim
# print(face_features.shape, audio_features.shape, desc_features.shape, sit_features.shape, scene_features.shape, text_features.shape)
# exit()
# # F, Va, emb_desc, emb_sit, emb_sce, emb_trans
x = x.float()
face_features=face_features.float()
audio_features=audio_features.float()
text_features=text_features.float()
batch_size, seq_len = x.shape[0], x.shape[1]
# Set initial hidden and cell states for encoder
h0 = self.enc_h0.repeat(1, batch_size, 1)
c0 = self.enc_c0.repeat(1, batch_size, 1)
# Convert raw features into equal-dimensional embeddings
# embed = self.embed(x)
# Compute attention weights
text_features_rep = self.text_linear(text_features)
face_features_rep = self.face_linear(face_features)
audio_features_rep = self.audio_linear(audio_features)
scene_features_rep = self.scene_linear(scene_features)
desc_features_rep = self.desc_linear(desc_features)
sit_features_rep = self.sit_linear(sit_features)
# attention multiplexers
# pairwise text
concat_features = torch.cat([text_features_rep, audio_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_1 = self.att_linear(concat_features).squeeze(-1)
att_1 = torch.softmax(att_1, dim=-1)
concat_features = torch.cat([text_features_rep, face_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_2 = self.att_linear(concat_features).squeeze(-1)
att_2 = torch.softmax(att_2, dim=-1)
concat_features = torch.cat([text_features_rep, scene_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_3 = self.att_linear(concat_features).squeeze(-1)
att_3 = torch.softmax(att_3, dim=-1)
concat_features = torch.cat([text_features_rep, desc_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_4 = self.att_linear(concat_features).squeeze(-1)
att_4 = torch.softmax(att_4, dim=-1)
concat_features = torch.cat([text_features_rep, sit_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_5 = self.att_linear(concat_features).squeeze(-1)
att_5 = torch.softmax(att_5, dim=-1)
concat_features = torch.cat([face_features_rep, audio_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_6 = self.att_linear(concat_features).squeeze(-1)
att_6 = torch.softmax(att_6, dim=-1)
concat_features = torch.cat([face_features_rep, scene_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_7 = self.att_linear(concat_features).squeeze(-1)
att_7 = torch.softmax(att_7, dim=-1)
concat_features = torch.cat([face_features_rep, desc_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_8 = self.att_linear(concat_features).squeeze(-1)
att_8 = torch.softmax(att_8, dim=-1)
concat_features = torch.cat([face_features_rep, sit_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_9 = self.att_linear(concat_features).squeeze(-1)
att_9 = torch.softmax(att_9, dim=-1)
# pairwise audio
concat_features = torch.cat([audio_features_rep, scene_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_10 = self.att_linear(concat_features).squeeze(-1)
att_10 = torch.softmax(att_10, dim=-1)
concat_features = torch.cat([audio_features_rep, desc_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_11 = self.att_linear(concat_features).squeeze(-1)
att_11 = torch.softmax(att_11, dim=-1)
concat_features = torch.cat([audio_features_rep, sit_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_12 = self.att_linear(concat_features).squeeze(-1)
att_12 = torch.softmax(att_12, dim=-1)
# pairwise scene
concat_features = torch.cat([scene_features_rep, desc_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_13 = self.att_linear(concat_features).squeeze(-1)
att_13 = torch.softmax(att_13, dim=-1)
concat_features = torch.cat([scene_features_rep, sit_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_14 = self.att_linear(concat_features).squeeze(-1)
att_14 = torch.softmax(att_14, dim=-1)
# pairwise desc
concat_features = torch.cat([desc_features_rep, sit_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_15 = self.att_linear(concat_features).squeeze(-1)
att_15 = torch.softmax(att_15, dim=-1)
unimodal_text_input= torch.tanh(text_features_rep)
unimodal_text_input = self.unimodal_text(unimodal_text_input).squeeze(-1)
unimodal_text_input = torch.softmax(unimodal_text_input, dim=-1)
unimodal_face_input= torch.tanh(face_features_rep)
unimodal_face_input = self.unimodal_face(unimodal_face_input).squeeze(-1)
unimodal_face_input = torch.softmax(unimodal_face_input, dim=-1)
unimodal_audio_input= torch.tanh(audio_features_rep)
unimodal_audio_input = self.unimodal_audio(unimodal_audio_input).squeeze(-1)
unimodal_audio_input = torch.softmax(unimodal_audio_input, dim=-1)
unimodal_scene_input= torch.tanh(scene_features_rep)
unimodal_scene_input = self.unimodal_text(unimodal_scene_input).squeeze(-1)
unimodal_scene_input = torch.softmax(unimodal_scene_input, dim=-1)
unimodal_desc_input= torch.tanh(desc_features_rep)
unimodal_desc_input = self.unimodal_face(unimodal_desc_input).squeeze(-1)
unimodal_desc_input = torch.softmax(unimodal_desc_input, dim=-1)
unimodal_sit_input= torch.tanh(sit_features_rep)
unimodal_sit_input = self.unimodal_audio(unimodal_sit_input).squeeze(-1)
unimodal_sit_input = torch.softmax(unimodal_sit_input, dim=-1)
enc_input_unimodal_cat=torch.cat([unimodal_text_input, unimodal_face_input, unimodal_audio_input, unimodal_scene_input, unimodal_desc_input, unimodal_sit_input], dim=-1)
enc_input_unimodal_cat = enc_input_unimodal_cat.reshape(batch_size, seq_len, 6)
attn=torch.cat([att_1, att_2, att_3, att_4, att_5, att_6, att_7, att_8, att_9, att_10, att_11, att_12, att_13, att_14, att_15], dim=-1)
attn = attn.reshape(batch_size, seq_len, self.attn_len)
enc_out, _ = self.shared_encoder(enc_input_unimodal_cat)
context = convolve(enc_out, attn)
# Set initial hidden and cell states for decoder
h0 = self.dec_h0.repeat(1, batch_size, 1)
c0 = self.dec_c0.repeat(1, batch_size, 1)
if target is not None:
target = target.float()
# Concatenate targets from previous timesteps to context
dec_in = context
# Pack the input to mask padded entries
# dec_in = pack_padded_sequence(dec_in, lengths, batch_first=True)
# Forward propagate decoder LSTM
dec_out, _ = self.decoder(dec_in, (h0, c0))
# Undo the packing
# dec_out, _ = pad_packed_sequence(dec_out, batch_first=True)
# Flatten temporal dimension
dec_out = dec_out.reshape(-1, self.h_dim)
# Compute predictions from decoder outputs
predicted = self.out(dec_out).view(batch_size, seq_len, self.out_layer)
else:
# Use earlier predictions to predict next time-steps
predicted = []
p = torch.ones(batch_size, 1).to(self.device) * tgt_init
h, c = h0, c0
for t in range(seq_len):
# Concatenate prediction from previous timestep to context
i = torch.cat([p, context[:, t, :]], dim=1).unsqueeze(1)
# Get next decoder LSTM state and output
o, (h, c) = self.decoder(i, (h, c))
# Computer prediction from output state
p = self.out(o.view(-1, self.h_dim))
predicted.append(p.unsqueeze(1))
predicted = torch.cat(predicted, dim=1)
# Mask target entries that exceed sequence lengths
# predicted = predicted * mask.float()
return predicted, enc_input_unimodal_cat, self.shared_encoder
<file_sep>from __future__ import print_function, division
from torch.utils.data import Dataset, DataLoader
import scipy.io as scp
import numpy as np
import torch
from matplotlib import pyplot as plt
from scipy.stats.stats import pearsonr
from block import fusions
#__________________________________________________________________________________________________________________________
# New Dataloader for MovieClass
### Dataset class for the NGSIM datase
class MovieDataset(Dataset):
def __init__(self, data):
self.data = data
self.movie_idx = list(self.data.keys())
self.num_samples = len(list(self.data.keys()))
pass
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
idx = self.movie_idx[idx]
F = self.data[idx][2]
A = self.data[idx][1]
T = self.data[idx][3]
y = self.data[idx][4]
combined = np.hstack([F, A, T])
#shape: timestamps*sum of dim_modality
# Convert to torch tensors
F = torch.Tensor(F)
A = torch.Tensor(A)
T = torch.Tensor(T)
# y = torch.Tensor(y)
# Instantiate fusion classes
FA = fusions.Block([F.shape[1], A.shape[1]], T.shape[1])
FAT = fusions.Block([T.shape[1], T.shape[1]], F.shape[1]+A.shape[1]+T.shape[1])
# compute fusions
temp_output_FA = FA([F, A])
final_FAT = FAT([temp_output_FA, T])
# return final_FAT.cpu().detach().numpy(), y
return combined, y, F, A, T
#________________________________________________________________________________________________________________________________________
def adjust_learning_rate(optimizer, epoch, lr):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if epoch == 100:
lr = lr * 0.1
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def eval_ccc(emot_score, labels, CCC):
"""Computes concordance correlation coefficient."""
emot_mu = torch.mean(emot_score)
emot_sigma = torch.std(emot_score)
labels_mu = torch.mean(labels)
labels_sigma = torch.std(labels)
vx = emot_score - emot_mu
vy = labels - labels_mu
prsn_corr = torch.mean(vx * vy)
CCC = (2 * prsn_corr) / (emot_sigma ** 2 + labels_sigma ** 2 + (emot_mu - labels_mu) ** 2)
return CCC<file_sep>from __future__ import print_function, division
from torch.utils.data import Dataset, DataLoader
import scipy.io as scp
from keras.utils import to_categorical
import numpy as np
import torch
from matplotlib import pyplot as plt
from scipy.stats.stats import pearsonr
from block import fusions
import shutil
#___________________________________________________________________________________________________________________________
# New Dataloader for MovieClass
class MediaEvalDataset(Dataset):
def __init__(self, data):
self.data = data
self.movie_idx = list(self.data.keys()) # ['tt03045', 'tt0840830' ...] etc
self.num_samples = len(list(self.data.keys())) # 51 movies ideally
self.new_data = {}
for movie in self.movie_idx:
num_clips = list(self.data[movie].keys())
self.new_data[movie] = []
self.new_data[movie].append(len(num_clips))
self.new_data[movie].append( np.array([self.data[movie][clip]['face'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['va'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['scene'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['audio'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['valence'] for clip in num_clips]) )
self.new_data[movie].append( np.array([self.data[movie][clip]['arousal'] for clip in num_clips]) )
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
idx = self.movie_idx[idx]
F = self.new_data[idx][1]
Va = self.new_data[idx][2]
scene = self.new_data[idx][3]
audio = self.new_data[idx][4]
y = [self.new_data[idx][5][:10], self.new_data[idx][6][:10]]
combined = np.hstack([F, Va, scene, audio])
return combined[:10], y, F[:10], Va[:10], scene[:10], audio[:10]
#________________________________________________________________________________________________________________________________________
def adjust_learning_rate(optimizer, epoch, lr):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if epoch == 100:
lr = lr * 0.1
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def prsn(emot_score, labels):
"""Computes concordance correlation coefficient."""
labels_mu = torch.mean(labels)
emot_mu = torch.mean(emot_score)
vx = emot_score - emot_mu
vy = labels - labels_mu
# prsn_corr = torch.mean(vx * vy)
prsn_corr = torch.sum(vx * vy) / (torch.sqrt(torch.sum(vx ** 2)) * torch.sqrt(torch.sum(vy ** 2)))
return prsn_corr
def save_ckp(state, is_best, checkpoint_path, best_model_path):
"""
state: checkpoint we want to save
is_best: is this the best checkpoint; min validation loss
checkpoint_path: path to save checkpoint
best_model_path: path to save best model
"""
f_path = checkpoint_path
# save checkpoint data to the path given, checkpoint_path
torch.save(state, f_path)
# if it is a best model, min validation loss
if is_best:
best_fpath = best_model_path
# copy that checkpoint file to best path given, best_model_path
shutil.copyfile(f_path, best_fpath)
def load_ckp(checkpoint_fpath, model, optimizer):
"""
checkpoint_path: path to save checkpoint
model: model that we want to load checkpoint parameters into
optimizer: optimizer we defined in previous training
"""
# load check point
checkpoint = torch.load(checkpoint_fpath)
# initialize state_dict from checkpoint to model
model.load_state_dict(checkpoint['state_dict'])
# initialize optimizer from checkpoint to optimizer
optimizer.load_state_dict(checkpoint['optimizer'])
# initialize valid_loss_min from checkpoint to valid_loss_min
valid_loss_min_valence = checkpoint['valid_loss_min_valence']
valid_loss_min_arousal = checkpoint['valid_loss_min_arousal']
# return model, optimizer, epoch value, min validation loss
return model, optimizer, checkpoint['epoch'], valid_loss_min_valence.item(), valid_loss_min_arousal.item()
<file_sep># emotion-timeseries
Code Repository for the paper: "Affect2MM: Affective Analysis of Multimedia Content Using Emotion Causality".
Training and Testing Codes for all three datasets.
1. SENDv1 Dataset
2. MovieGraphs Dataset
3. LIRIS-ACCEDE Dataset
<file_sep>from __future__ import division
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from clstm import cLSTM, train_model_gista, train_model_adam, cLSTMSparse
def pad_shift(x, shift, padv=0.0):
"""Shift 3D tensor forwards in time with padding."""
if shift > 0:
padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv
return torch.cat((padding, x[:, :-shift, :]), dim=1)
elif shift < 0:
padding = torch.ones(x.size(0), -shift, x.size(2)).to(x.device) * padv
return torch.cat((x[:, -shift:, :], padding), dim=1)
else:
return x
def convolve(x, attn):
"""Convolve 3D tensor (x) with local attention weights (attn)."""
stacked = torch.stack([pad_shift(x, i) for
i in range(attn.shape[2])], dim=-1)
return torch.sum(attn.unsqueeze(2) * stacked, dim=-1)
class MovieNet(nn.Module):
"""Multimodal encoder-decoder LSTM model.
modalities -- list of names of each input modality
dims -- list of dimensions for input modalities
embed_dim -- dimensions of embedding for feature-level fusion
h_dim -- dimensions of LSTM hidden state
n_layers -- number of LSTM layers
attn_len -- length of local attention window
"""
def __init__(self, args, device='cuda:0'):
# device=torch.device('cuda:0')
super(MovieNet, self).__init__()
self.face_len = args['F_length']
self.audio_len = args['A_length']
self.text_len = args['T_length']
self.total_mod_len = self.face_len + self.audio_len +self.text_len
# self.total_mod_len = 3*(self.text_len)
self.embed_dim = args['embed_dim']
self.h_dim = args['h_dim']
self.n_layers = args['n_layers']
self.attn_len = args['attn_len']
# linear for word-guided visual attention
self.text_linear = nn.Linear(self.text_len, self.h_dim, bias=True)
self.face_linear = nn.Linear(self.face_len, self.h_dim, bias=True)
self.audio_linear = nn.Linear(self.audio_len, self.h_dim, bias=True)
self.att_linear = nn.Linear(self.h_dim * 2, 1)
self.unimodal_text = nn.Linear(self.h_dim,1)
self.unimodal_face = nn.Linear(self.h_dim,1)
self.unimodal_audio = nn.Linear(self.h_dim,1)
# Create raw-to-embed FC+Dropout layer for each modality
# self.embed = nn.Sequential(nn.Dropout(0.5),
# nn.Linear( self.total_mod_len, self.embed_dim),
# nn.ReLU())
# self.add_module('embed_{}'.format(m), self.embed[m])
# Layer that computes attention from embeddings
# self.attn = nn.Sequential(nn.Linear(self.embed_dim, self.embed_dim),
# nn.ReLU(),
# nn.Linear(self.embed_dim, self.attn_len),
# nn.Softmax(dim=1))
# Encoder computes hidden states from embeddings for each modality
# self.encoder = nn.LSTM(self.embed_dim, self.h_dim, self.n_layers, batch_first=True)
self.shared_encoder = cLSTM(3,self.h_dim, batch_first=True).cuda(device=device)
# self.encoder = cLSTMSparse(self.embed_dim,self.h_dim, batch_first=True)
self.enc_h0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
self.enc_c0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
# Decodes targets and LSTM hidden states
self.decoder = nn.LSTM(1 + self.attn_len, self.h_dim, self.n_layers, batch_first=True)
# self.decoder = cLSTMSparse(1 + self.embed_dim, self.sparsity, self.h_dim, batch_first=True)
self.dec_h0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
self.dec_c0 = nn.Parameter(torch.zeros(self.n_layers, 1, self.h_dim))
# Final MLP output network
self.out = nn.Sequential(nn.Linear(self.h_dim, 4),
nn.ReLU(),
nn.Linear(4, 1))
# Store module in specified device (CUDA/CPU)
self.device = (device if torch.cuda.is_available() else
torch.device('cpu'))
self.to(self.device)
def forward(self, x, face_features, audio_features, text_features, target=None, tgt_init=0.0):
# Get batch dim
x = x.float()
batch_size, seq_len = x.shape[0], x.shape[1]
# Set initial hidden and cell states for encoder
h0 = self.enc_h0.repeat(1, batch_size, 1)
c0 = self.enc_c0.repeat(1, batch_size, 1)
text_features_rep = self.text_linear(text_features)
face_features_rep = self.face_linear(face_features)
audio_features_rep = self.audio_linear(audio_features)
concat_features = torch.cat([text_features_rep, face_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_1 = self.att_linear(concat_features).squeeze(-1)
att_1 = torch.softmax(att_1, dim=-1)
concat_features = torch.cat([face_features_rep, audio_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_2 = self.att_linear(concat_features).squeeze(-1)
att_2 = torch.softmax(att_2, dim=-1)
concat_features = torch.cat([text_features_rep, audio_features_rep], dim=-1)
concat_features = torch.tanh(concat_features)
att_3 = self.att_linear(concat_features).squeeze(-1)
att_3 = torch.softmax(att_3, dim=-1)
unimodal_text_input= torch.tanh(text_features_rep)
unimodal_text_input = self.unimodal_text(unimodal_text_input).squeeze(-1)
unimodal_text_input = torch.softmax(unimodal_text_input, dim=-1)
unimodal_face_input= torch.tanh(face_features_rep)
unimodal_face_input = self.unimodal_face(unimodal_face_input).squeeze(-1)
unimodal_face_input = torch.softmax(unimodal_face_input, dim=-1)
unimodal_audio_input= torch.tanh(audio_features_rep)
unimodal_audio_input = self.unimodal_audio(unimodal_audio_input).squeeze(-1)
unimodal_audio_input = torch.softmax(unimodal_audio_input, dim=-1)
enc_input_unimodal_cat=torch.cat([unimodal_text_input, unimodal_face_input, unimodal_audio_input], dim=-1)
enc_input_unimodal_cat = enc_input_unimodal_cat.reshape(batch_size, seq_len, self.attn_len)
attn=torch.cat([att_1, att_2, att_3], dim=-1)
attn = attn.reshape(batch_size, seq_len, self.attn_len)
enc_out, _ = self.shared_encoder(enc_input_unimodal_cat)
context = convolve(enc_out, attn)
# Set initial hidden and cell states for decoder
h0 = self.dec_h0.repeat(1, batch_size, 1)
c0 = self.dec_c0.repeat(1, batch_size, 1)
if target is not None:
target = target.float()
# Concatenate targets from previous timesteps to context
dec_in = torch.cat([pad_shift(target, 1, tgt_init), context], 2)
dec_out, _ = self.decoder(dec_in, (h0, c0))
# Undo the packing
# dec_out, _ = pad_packed_sequen,ce(dec_out, batch_first=True)
# Flatten temporal dimension
dec_out = dec_out.reshape(-1, self.h_dim)
# Compute predictions from decoder outputs
predicted = self.out(dec_out).view(batch_size, seq_len, 1)
else:
# Use earlier predictions to predict next time-steps
predicted = []
p = torch.ones(batch_size, 1).to(self.device) * tgt_init
h, c = h0, c0
for t in range(seq_len):
# Concatenate prediction from previous timestep to context
i = torch.cat([p, context[:, t, :]], dim=1).unsqueeze(1)
# Get next decoder LSTM state and output
o, (h, c) = self.decoder(i, (h, c))
# Computer prediction from output state
p = self.out(o.view(-1, self.h_dim))
predicted.append(p.unsqueeze(1))
predicted = torch.cat(predicted, dim=1)
# Mask target entries that exceed sequence lengths
# predicted = predicted * mask.float()
return predicted, enc_input_unimodal_cat, self.shared_encoder
| e9684246a7dd77d2b4c2102054c1c594412d337c | [
"Markdown",
"Python"
] | 10 | Python | sucv/emotion-timeseries | c146cb1c2122007e75f2143c63cfee342dcd01cc | 4f1059a9a1fc92dbb4e0b541e29ddf5e32857d0a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.