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 | <repo_name>deepak3698/Music-Mixer<file_sep>/main.py
import os
import pandas as pd
from pydub import AudioSegment
from gtts import gTTS
print("hello deepak--It is an Music Mixer App")
def textToSpeech(text, filename):
mytext = str(text)
language = 'hi'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save(filename)
def mergeAudios(audios):
combined = AudioSegment.empty()
for audio in audios:
combined += AudioSegment.from_mp3(audio)
return combined
def generateSkeleton():
audio = AudioSegment.from_mp3('yaara_song.mp3')
# First_Part #1
start = 1000
finish = 5000
audioProcessed = audio[start:finish]
audioProcessed.export("1s.mp3", format="mp3")
# First_Part #2
start = 5000
finish = 10000
audioProcessed = audio[start:finish]
audioProcessed.export("2s.mp3", format="mp3")
# First_Part #3
start = 10000
finish = 13000
audioProcessed = audio[start:finish]
audioProcessed.export("3s.mp3", format="mp3")
# First_Part #4
start = 13000
finish = 17000
audioProcessed = audio[start:finish]
audioProcessed.export("4s.mp3", format="mp3")
def generateAnnouncement(filename):
df = pd.read_excel(filename)
for index,item in df.iterrows():
# 2 - Generate Name
textToSpeech(item['name'], '1d.mp3')
# 4 - Generate Bs Kya
textToSpeech(item['cp1'], '2d.mp3')
# # 6 - Generate Badhiya
textToSpeech(item['cp2'], '3d.mp3')
dt1=["1s","1d","2s","2d","3s","3d","4s"]
audios = [f"{i}.mp3" for i in dt1]
announcement = mergeAudios(audios)
announcement.export("final.mp3", format="mp3")
if __name__ == "__main__":
print("Generating Voices...")
generateSkeleton()
print("Final Song...")
generateAnnouncement("myVoice.xlsx")
| 526c27fd2a7e4c66339f1a661316bc816733475b | [
"Python"
] | 1 | Python | deepak3698/Music-Mixer | 42da0a4df9a880c991c5d117509d69f25d637f29 | 166e30b85271372a3b5fc672ed258fc272ed8752 |
refs/heads/master | <repo_name>Benkevych/viktoriia<file_sep>/app/scripts/main.js
$('.carousel').on('slid.bs.carousel', function () {
if ($('#item2-1').hasClass('active')) {
$('#left1').removeClass('hide');
} else {
$('#left1').addClass('hide');
}
if ($('#item1-1').hasClass('active')) {
$('#right1').removeClass('hide');
} else {
$('#right1').addClass('hide');
}
if ($('#item2-2').hasClass('active')) {
$('#left2').removeClass('hide');
} else {
$('#left2').addClass('hide');
}
if ($('#item1-2').hasClass('active')) {
$('#right2').removeClass('hide');
} else {
$('#right2').addClass('hide');
}
});
| 05c8478d85de8efb4aaf0b497d952c32f1cdaad1 | [
"JavaScript"
] | 1 | JavaScript | Benkevych/viktoriia | c432a378dd40bf2914ebd0a6c1b56490d0a8a7e6 | 7b7e5bf67aeb55f44f279a59a6bb4c6df9b15a0c |
refs/heads/master | <file_sep>from pynput import mouse, keyboard
import time
from queue import Queue
import logging
stop_flag = False
class MouseEvent():
def __init__(self, action, x, y, button=None, pressed=None, time=None):
'''
Args:
action: {"move", "click", "scroll"}
x:
'''
self.action = action
self.x = x
self.y = y
self.button = button
self.pressed = pressed
self.time = time
def dump(self):
return "action:{}, x={}, y={}\n".format(self.action, self.x, self.y)
class KeyBoardEvent():
def __init__(self, action, key, time=None):
self.action = action
self.key = key
def dump(self):
return "action:{}, key{}\n".format(self.action, self.key)
class MouseRecoder():
def __init__(self, event_queue):
''' q is event queue '''
self.event_queue = event_queue
# ...or, in a non-blocking fashion:
self.listener = mouse.Listener(
on_move=self.on_move,
on_click=self.on_click,
on_scroll=self.on_scroll,
)
# listener.start()
# listener.join()
def start(self):
self.listener.start()
def join(self):
self.listener.join()
def on_move(self, x, y):
if stop_flag: return False
logging.debug('Pointer moved to {0}'.format((x, y)))
e = MouseEvent("move", x, y)
self.event_queue.put(e)
def on_click(self, x, y, button, pressed):
if stop_flag: return False
logging.debug('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
e = MouseEvent("click", x, y, button, pressed)
self.event_queue.put(e)
if not pressed:
# Stop listener
return False
def on_scroll(self, x, y, dx, dy):
if stop_flag:
logging.info("scroll stop_flag")
return False
logging.debug('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y)))
e = MouseEvent("scroll", x, y)
self.event_queue.put(e)
class KeyBoardRecoder():
def __init__(self, event_queue):
''' q is event queue '''
self.event_queue = event_queue
self.listener = keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
)
def start(self):
self.listener.start()
def join(self):
self.listener.join()
def on_press(self, key):
if stop_flag:
logging.info("press stop_flag")
return False
try:
logging.debug('alphanumeric key {0} pressed'.format(key.char))
except AttributeError:
logging.debug('special key {0} pressed'.format(key))
e = KeyBoardEvent("press", key)
self.event_queue.put(e)
def on_release(self, key):
if stop_flag:
logging.info("release stop_flag")
return False
logging.debug('{0} released'.format(key))
e = KeyBoardEvent("release", key)
self.event_queue.put(e)
if key == keyboard.Key.esc:
# Stop listener
return False
class Actions:
def __init__(self):
pass
def load_data(self, filename):
pass
class Recoder():
def __init__(self):
self.q = Queue()
self.mouse_recoder = MouseRecoder(self.q)
self.keyboard_recoder = KeyBoardRecoder(self.q)
def start(self):
self.mouse_recoder.start()
self.keyboard_recoder.start()
def phony_action(self):
mouse_controller = mouse.Controller()
mouse_controller.move(1, 1)
keyboard_controller = keyboard.Controller()
keyboard_controller.release(keyboard.Key.space)
def stop(self):
global stop_flag
stop_flag = True
self.phony_action()
self.join()
def join(self):
self.mouse_recoder.join()
self.keyboard_recoder.join()
def show_queue(self):
data = list(self.q.queue)
return data
def save_data(self, filename):
event_data = list(self.q.queue)
with open(filename, 'w') as fd:
for event in event_data:
line = event.dump()
fd.write(line)
if __name__ == "__main__":
recoder = Recoder()
recoder.start()
print("action size:", recoder.q.qsize())
time.sleep(5)
print("action size:", recoder.q.qsize())
recoder.stop()
print("action size:", recoder.q.qsize())
recoder.save_data("recoder_info.txt")<file_sep>#-*- coding:utf-8 -*-
import os
import sys
import time
import datetime
import pyautogui
import pyperclip
from io import BytesIO
import win32clipboard
import threading
import chardet
work_dir=os.path.dirname(os.path.abspath(__file__))
print("work_dir:", work_dir)
data_file = os.path.join(work_dir, "data.txt")
def get_from_clipboard():
win32clipboard.OpenClipboard()
copy_text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
win32clipboard.CloseClipboard()
return copy_text
def is_send_success(w):
x, y = w.left + w.width//2, w.top + w.height//2
pyautogui.click(x=x, y=y)
pyautogui.hotkey("ctrl", "a")
pyautogui.hotkey("ctrl", "c")
data = get_from_clipboard()
#encodeing = chardet.detect(data)
#data = data[-100:]
try:
#data = data.decode('GB2312')
data = data.decode('gbk')
except UnicodeDecodeError:
print("====UnicodeDecodeError===")
return False
content = data.strip().split('\n')
print("reply_content:", content[-1])
if "内容重复了" in content[-1]:
return False
elif '成功' in content[-1]:
return True
else:
return False
def send_to_clipboard(img):
output = BytesIO()
img.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
def zhifou_send(data):
data = "【#" + data + "#】"
pyautogui.hotkey("ctrl", "alt", "s")
pyautogui.hotkey("ctrl", "a")
pyautogui.press(["backspace"]*10)
pyautogui.typewrite("zhifou")
pyautogui.press("enter")
#pyautogui.press("enter")
time.sleep(2)
# open dialog
pyautogui.press("enter")
time.sleep(2)
# clean date content
pyautogui.hotkey("ctrl", "a")
pyautogui.press(["backspace"]*3)
time.sleep(1)
pyautogui.press("enter")
# send content
pyperclip.copy(data)
pyautogui.hotkey('ctrl', 'v')
time.sleep(1)
print("send:", data)
pyautogui.press("enter")
# send date
now_time = datetime.datetime.now()
now_time = now_time.strftime("%Y-%m-%d %H:%M:%S")
pyautogui.typewrite(now_time)
# screen shot
w = pyautogui.getFocusedWindow()
# wait reply
time.sleep(5)
status = is_send_success(w)
im = pyautogui.screenshot(region=(w.topleft[0], w.topleft[1], w.width, w.height))
return status, im
def screenshot_send(data):
pyautogui.hotkey("ctrl", "alt", "s")
pyautogui.hotkey("ctrl", "a")
pyautogui.press(["backspace"]*10)
pyautogui.typewrite("meiri")
#pyautogui.typewrite("zhifou")
pyautogui.press("enter")
time.sleep(1)
pyautogui.press("enter")
pyautogui.press("enter")
time.sleep(1)
send_to_clipboard(data)
#pyperclip.copy(data)
pyautogui.hotkey('ctrl', 'v')
time.sleep(1)
print("send")
pyautogui.press("enter")
def read_data(data_file):
data = []
fd = open(data_file, encoding="utf-8")
for line in fd:
line = line.strip()
if len(line) < 10: continue
data.append(line.strip())
fd.close()
return data
def update_data(all_data, data):
if len(all_data) < len(data):
print("found new data: {}".format(len(data) - len(all_data)))
all_data += data[len(all_data):]
return all_data
def popo_task():
all_data = []
count = 5
while True:
data = read_data(data_file)
all_data = update_data(all_data, data)
is_success, im = zhifou_send(all_data[count])
if not is_success:
count += 1
continue
screenshot_send(im)
print("send {}th/{}total, {}".format(count, len(all_data), all_data[count]))
count += 1
if(count >= len(all_data)):
count=0
sys.exit(1)
#time.sleep(5)
time.sleep(24*60*60)
def format_timedelta(td):
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
def start_task(task_func, start_time):
# 获取现在时间
now_time = datetime.datetime.now()
start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
start_time = start_time - now_time
if start_time.total_seconds() < 0:
print("==== start_time set Error =======")
#sys.exit(1)
else:
print("task will start after {}".format(format_timedelta(start_time)))
timer = threading.Timer(start_time.total_seconds(), task_func)
timer.start()
timer.join()
def main():
#start_time = "2019-05-28 10:40:00"
start_time = "2019-07-03 09:00:00"
start_task(popo_task, start_time)
if __name__ == '__main__':
main()
<file_sep>#-*- coding:utf-8 -*-
import os
import time
import pyautogui
import pyperclip
work_dir=os.path.dirname(os.path.abspath(__file__))
print("work_dir:", work_dir)
data_file = os.path.join(work_dir, "data.txt")
def zhifou_send(data):
#data = "【#" + data + "#】"
pyautogui.hotkey("ctrl", "alt", "s")
pyautogui.hotkey("ctrl", "a")
pyautogui.press(["backspace"]*10)
pyautogui.typewrite("zhifou")
pyautogui.press("enter")
time.sleep(1)
pyautogui.press("enter")
pyautogui.press("enter")
time.sleep(1)
pyperclip.copy(data)
pyautogui.hotkey('ctrl', 'v')
time.sleep(1)
print("send")
pyautogui.press("enter")
def read_data(data_file):
data = []
fd = open(data_file, encoding="utf-8")
for line in fd:
line = line.strip()
if len(line) < 10: continue
data.append(line.strip())
fd.close()
return data
def update_data(all_data, data):
if len(all_data) < len(data):
print("found new data: {}".format(len(data) - len(all_data)))
all_data += data[len(all_data):]
return all_data
def main():
all_data = []
count = 0
while True:
data = read_data(data_file)
all_data = update_data(all_data, data)
zhifou_send(all_data[count])
print("send {}th, {}".format(count, all_data[count]))
count += 1
if(count >= len(all_data)): count=0
time.sleep(3)
#time.sleep(24*60*60)
if __name__ == '__main__':
main()
## print("start")
## data = read_data(data_file)
## print(data)
<file_sep>from pynput import mouse, keyboard
import functools
from queue import Queue
class MouseEvent():
def __init__(self, x, y):
self.x = x
self.y = y
class KeyBoardRecoder():
def __init__(self, event_queue):
''' q is event queue '''
self.event_queue = event_queue
self.listener = keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
)
def start(self):
self.listener.start()
def join(self):
self.listener.join()
def on_press(self, key):
try:
print('alphanumeric key {0} pressed'.format(key.char))
except AttributeError:
print('special key {0} pressed'.format(key))
def on_release(self, key):
print('{0} released'.format(key))
if key == keyboard.Key.esc:
# Stop listener
return False
if __name__ == "__main__":
q = Queue()
keyboard_recoder = KeyBoardRecoder(q)
keyboard_recoder.start()
keyboard_recoder.join()<file_sep>from pynput import mouse, keyboard
import time
from queue import Queue
import logging
from recoder import MouseEvent, KeyBoardEvent
class Actions:
def __init__(self):
pass
def load_data(self, filename):
pass
class MouseExecuter:
def __init__(self):
self.mouse_controller = mouse.Controller()
def execute(self, event):
if event.action == "move":
logging.debug("move: {}, {}".format(event.x, event.y))
self.mouse_controller.position = (event.x, event.y)
elif event.action == "scroll":
self.mouse_controller.scroll(event.x, event.y)
elif event.action == "click":
if event.pressed == True:
self.mouse_controller.press(event.button)
elif event.pressed == False:
self.mouse_controller.press(event.button)
#self.mouse_controller.click(mouse.Button.left, 2)
class KeyBoardExecuter:
def __init__(self):
self.mouse_controller = mouse.Controller()
def execute(self, event):
pass
class Executer:
def __init__(self, event_list = None):
self.event_list = event_list
self.mouse_executer = MouseExecuter()
self.keyboard_executer = KeyBoardExecuter()
def execute(self, event):
if isinstance(event, MouseEvent):
self.mouse_executer.execute(event)
elif isinstance(event, KeyBoardEvent):
self.keyboard_executer.execute(event)
def run(self):
for event in self.event_list:
time.sleep(0.1)
self.execute(event)
def parse_event(self, line):
line = line.strip().split(',')
data = dict(x.split('=') for x in line)
if data['action'] in ["move", "click", "scroll"]:
action = data.get("action")
x = int(data.get("x"))
y = int(data.get("y"))
button = data.get("button", None)
pressed = data.get("pressed", None)
time = data.get("time", None)
return MouseEvent(action, x, y, button, pressed, time)
elif data["action"] in ["press", "release"]:
action = data.get("action")
key = data.get("key", None)
return KeyBoardEvent(action, key)
def load_data(self, filename):
self.event_list = []
with open(filename, 'r') as fd:
for line in fd:
event = self.parse_event(line)
self.event_list.append(event)
if __name__ == "__main__":
# q = Queue()
# q.put(MouseEvent("move", 0,0))
# q.put(MouseEvent("move", 10,10))
# q.put(MouseEvent("move", 50,50))
# q.put(MouseEvent("move", 100,100))
# q.put(MouseEvent("move", 200,200))
#executer = Executer(list(q.queue))
executer = Executer()
executer.load_data("recoder_info.txt")
executer.run()
<file_sep>from pynput import mouse, keyboard
import functools
from queue import Queue
import logging
class MouseEvent():
def __init__(self, action, x, y, button=None, pressed=None, time=None):
self.action = action
self.x = x
self.y = y
class KeyBoardEvent():
def __init__(self, key, time=None):
self.key = key
class MouseRecoder():
def __init__(self, event_queue):
''' q is event queue '''
self.event_queue = event_queue
# ...or, in a non-blocking fashion:
self.listener = mouse.Listener(
on_move=self.on_move,
on_click=self.on_click,
on_scroll=self.on_scroll,
)
# listener.start()
# listener.join()
def start(self):
self.listener.start()
def join(self):
self.listener.join()
def on_move(self, x, y):
logging.debug('Pointer moved to {0}'.format((x, y)))
e = MouseEvent("move", x, y)
self.event_queue.put(e)
def on_click(self, x, y, button, pressed):
logging.debug('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
e = MouseEvent("click", x, y, button, pressed)
self.event_queue.put(e)
if not pressed:
# Stop listener
return False
def on_scroll(self, x, y, dx, dy):
logging.debug('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y)))
e = MouseEvent("scroll", x, y)
self.event_queue.put(e)
class KeyBoardRecoder():
def __init__(self, event_queue):
''' q is event queue '''
self.event_queue = event_queue
self.listener = keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
)
def start(self):
self.listener.start()
def join(self):
self.listener.join()
def on_press(self, key):
try:
logging.debug('alphanumeric key {0} pressed'.format(key.char))
e = KeyBoardEvent(key)
self.event_queue.put(e)
except AttributeError:
logging.debug('special key {0} pressed'.format(key))
e = KeyBoardEvent(key)
self.event_queue.put(e)
def on_release(self, key):
logging.debug('{0} released'.format(key))
e = KeyBoardEvent(key)
self.event_queue.put(e)
if key == keyboard.Key.esc:
# Stop listener
return False
#class Actions():
class Recoder():
def __init__(self):
self.q = Queue()
self.mouse_recoder = MouseRecoder(self.q)
self.keyboard_recoder = KeyBoardRecoder(self.q)
def start(self):
self.mouse_recoder.start()
self.keyboard_recoder.start()
def join(self):
self.mouse_recoder.join()
self.keyboard_recoder.join()
def show_queue(self):
data = list(self.q)
return data
#class Executer():
| 3381d7d041fbfd3910101b629f1bd59a7ed090ad | [
"Python"
] | 6 | Python | osljw/workspace | 6eb6f2a299ffd9df0f15ae4ff50801e28dbd0c8e | c1b625bf6461e4850fbeb0d33d6c86546638f770 |
refs/heads/master | <file_sep>using System;
using System.Globalization;
namespace ExcerciciosEstatic {
class Program {
static void Main(string[] args) {
Console.Write("Quantos dolares você vai comprar");
double valorCompra = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.WriteLine("Valor a ser pago em reais = " +
Calculadora.ConversorMoeda(valorCompra).ToString("F2", CultureInfo.InvariantCulture)
);
}
}
}
<file_sep>using System;
using System.Globalization;
namespace EntradaDados {
class Program {
static void Main(string[] args) {
/*
//string s = Console.ReadLine();
string[] vet = Console.ReadLine().Split(' ');
string item1 = vet[0];
string item2 = vet[1];
string item3 = vet[2];
Console.WriteLine($"{item1}, {item2}, {item3}");*/
int num1 = int.Parse(Console.ReadLine());
char genero = char.Parse(Console.ReadLine());
double numDouble = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.WriteLine("Você digitou");
Console.WriteLine(num1);
Console.WriteLine(genero);
Console.WriteLine(numDouble);
}
}
}
<file_sep>using System;
using System.Xml.Linq;
using Herancas.Entities;
namespace Herancas
{
class Program
{
static void Main(string[] args)
{
/*
BusinessAccount account = new BusinessAccount(8010, "Angelina", 100.00, 500.00);
Console.WriteLine(account.Balance);
account.Deposit(200.00);
Console.WriteLine(account.Balance);
account.Loan(400.00);
Console.WriteLine(account.Balance);
account.WithDraw(600);
Console.WriteLine(account.Balance);*/
/*
Account acc = new Account(8010, "Antonia", 300.00);
BusinessAccount bacc = new BusinessAccount(8788, "Evelyn", 8000.00, 1000.00);
//UPCASTING
Account acc1 = bacc;
Account acc2 = new BusinessAccount(1522, "Anna", 0.0, 300);
Account acc3 = new SavingsAccount(0025, "Mary", 2000, 150);
//DOWN CASTING
BusinessAccount acc4 = (BusinessAccount)acc2;
if (acc3 is BusinessAccount)
{
BusinessAccount acc5 = (BusinessAccount)acc3;
}
if (acc3 is SavingsAccount)
{
//SavingsAccount acc5 = (SavingsAccount)acc3;
SavingsAccount acc5 = acc3 as SavingsAccount;
acc5.UpdateBalance();
Console.WriteLine("UpdateBalance");
}*/
Account acc1 = new Account(0258, "Dailton", 500.0);
Account acc2 = new SavingsAccount(0003, "Martha", 500.0, 0.01);
acc1.WithDraw(10.00);
acc2.WithDraw(10.00);
Console.WriteLine(acc1.Balance);
Console.WriteLine(acc2.Balance);
}
}
}
<file_sep>using System;
namespace Polimorfismo02.Entities
{
class UsedProduct : Product
{
public DateTime ManufactureDate { get; set; }
public UsedProduct()
{
}
public UsedProduct(string name, double price, DateTime manufactureDate)
{
ManufactureDate = manufactureDate;
}
public override string PriceTag()
{
return "Name (used) $ " +
Price + "(Manufacture Date: " + ManufactureDate.ToString("dd/MM/yyyy") + ")";
}
}
}
<file_sep>namespace ExercicioClass {
class Pessoa {
public string nome;
public int idade;
public char genero;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
namespace ExemplosList {
class Program {
static void Main(string[] args) {
List<string> times = new List<string>();
//add list
times.Add("Palmeiras");
times.Add("PSG");
times.Add("Barcelona");
times.Add("Real Madrid");
times.Insert(1, "Manchester");
times.Add("Polonia");
foreach(string t in times) {
Console.WriteLine(t);
}
Console.WriteLine("List count: " + times.Count);
string s1 = times.Find(x => x[0] == 'P' || x[0] == 'p');
string s2 = times.FindLast(x=> x[0] =='P' || x[0] == 'p');
int s3 = times.FindIndex(x => x[0] == 'P');
int s4 = times.FindLastIndex(x => x[0] == 'P');
Console.WriteLine("First 'P' " + s1);
Console.WriteLine("Last 'P' " + s2);
Console.WriteLine("FindIndex 'P' " + s3);
Console.WriteLine("FindLastIndex 'P' " + s4);
List<string> times2 = times.FindAll(x => x.Length == 3 || x[0] == 'P');
Console.WriteLine("==================================");
foreach (string t2 in times2) {
Console.WriteLine(t2);
}
Console.WriteLine("==============================");
//times.Remove("PSG");
//times.RemoveAt(3);
times.RemoveRange(1,2);
foreach (string t in times) {
Console.WriteLine(t);
}
Console.WriteLine("==============================");
times.RemoveAll(x => x[0] == 'P');
foreach (string t in times) {
Console.WriteLine(t);
}
/*static bool Test(string s) {
return s[0] == 'P';
}*/
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace ExemploEncapsulamento {
class Cliente {
private string _nome;
private string _email;
private int _idade;
public double Salario { get; private set; }
public Cliente() {
}
public Cliente(string _nome, string _email) {
this._nome = _nome;
this._email = _email;
}
/*
public string GetNome() {
return _nome;
}
public string GetEmail() {
return _email;
}
public double GetSalario() {
return _salario;
}
public void setNome(string nome) {
if (nome != null && nome.Length > 1) {
_nome = nome;
}
}
public void SetSalario(double salario) {
_salario = salario;
}*/
//properties
public string Nome {
get { return _nome; }
set {
if (value != null && value.Length > 1) {
_nome = value;
}
}
}
public string Email {
get { return _email; }
set {
if (value != null && value.Length > 1) {
_email = value;
}
}
}
public override string ToString() {
return "O Funcionário " +
_nome +
" Email: " + _email +
" Recebe $" +
_salario.ToString("F2", CultureInfo.InvariantCulture) +
" de salário";
}
}
}
<file_sep>using System;
using System.Globalization;
namespace ExcerciciosEstatic {
class Calculadora {
private static double CotacaoDolar = 3.10;
private static double IOF = 6.0;
public static double ConversorMoeda(double valor) {
double calcValorCotacao = valor * CotacaoDolar;
return (calcValorCotacao * IOF / 100) + (calcValorCotacao);
}
}
}
<file_sep>using System;
namespace ExercicioVetores {
class Program {
static void Main(string[] args) {
Room[] numRooms = new Room[10];
Console.Write("Quantos quartos serão alugados?");
int n = int.Parse(Console.ReadLine());
for (int i = 0; i <= n;i++) {
Console.WriteLine();
Console.WriteLine($"Aluguel #{i}:");
Console.Write("Nome: ");
string name = Console.ReadLine();
Console.Write("Email: ");
string email = Console.ReadLine();
Console.Write("Quarto: ");
int quarto = int.Parse(Console.ReadLine());
numRooms[quarto] = new Room(name, email);
}
Console.WriteLine();
Console.WriteLine("Quartos oculpados:");
for (int i = 0; i< numRooms.Length;i++) {
if(numRooms[i] != null) {
Console.WriteLine(i + ": " + numRooms[i]);
}
}
}
}
}
<file_sep>using System;
using Composition2.Entities;
namespace Composition2
{
class Program
{
static void Main(string[] args)
{
Comment com1 = new Comment("Have a nice trip!");
Comment com2 = new Comment("Wowww that's awesome!");
Comment com3 = new Comment("Nice :DDD");
Post p1 = new Post(
DateTime.Parse("21/03/2020 13:05:50"),
"Traveling to China",
"I'm going visit this country!",
12
);
p1.AddComment(com1);
p1.AddComment(com2);
p1.AddComment(com3);
Console.WriteLine(p1);
}
}
}
<file_sep>using System;
namespace ExemploEncapsulamento {
class Program {
static void Main(string[] args) {
Cliente c = new Cliente("Dailton", "<EMAIL>");
c.Nome = "D";
Console.WriteLine(c.Nome);
}
}
}
<file_sep>using System;
using System.Globalization;
namespace ExercicioClass {
class Program {
static void Main(string[] args) {
/*
*EXERCICIO 1
*
*
Pessoa pessoa1, pessoa2;
pessoa1 = new Pessoa();
pessoa2 = new Pessoa();
Console.WriteLine("Dados da primeia Pessoa 1");
pessoa1.nome = Console.ReadLine();
pessoa1.idade = int.Parse(Console.ReadLine());
pessoa1.genero = char.Parse(Console.ReadLine());
Console.WriteLine("Dados da primeia Pessoa 2");
pessoa2.nome = Console.ReadLine();
pessoa2.idade = int.Parse(Console.ReadLine());
pessoa2.genero = char.Parse(Console.ReadLine());
Console.WriteLine($"Nome: {pessoa1.nome} \n Idade: {pessoa1.idade} \n Genero: {pessoa1.genero}");
Console.WriteLine($"Nome: {pessoa2.nome} \n Idade: {pessoa2.idade} \n Genero: {pessoa2.genero}");
string maisvelho;
if(pessoa1.idade > pessoa2.idade) {
maisvelho = $"A pessoa mais velha é {pessoa1.nome}";
}
else {
maisvelho = $"A pessoa mais velha é {pessoa2.nome}";
}
Console.WriteLine(maisvelho);*/
Funcionario fun1, fun2;
fun1 = new Funcionario();
fun2 = new Funcionario();
Console.WriteLine("Dados do primeiro funcionario");
fun1.nome = Console.ReadLine();
fun1.salario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.WriteLine("Dados do segundo funcionario");
fun2.nome = Console.ReadLine();
fun2.salario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Console.WriteLine("Nome: {0} \n Salário: {1} ", fun1.nome, fun1.salario.ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine("Nome: {0} \n Salário: {1} ", fun2.nome, fun2.salario.ToString("F2", CultureInfo.InvariantCulture));
double mediaSalario = (fun1.salario + fun2.salario) / 2.0;
Console.WriteLine("O salário medio é " + mediaSalario.ToString("F2", CultureInfo.InvariantCulture));
}
}
}
<file_sep>using System;
using System.Globalization;
namespace OOExemplo04 {
class Program {
static void Main(string[] args) {
Console.WriteLine("Entre com os dados do produto");
Console.Write("Nome");
string nome = Console.ReadLine();
Console.Write("Preço");
double preco = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Produto p = new Produto(nome, preco);
Console.WriteLine();
Console.WriteLine("Dados do produto " + p);
}
}
}
<file_sep>using System;
namespace ExemploMatrizes {
class Program {
static void Main(string[] args) {
Console.Write("Informe a quantidade da matriz");
int n = int.Parse(Console.ReadLine());
int[,] mat = new int[n, n];
for (int i = 0; i < n; i++) {
string[] values = Console.ReadLine().Split(' ');
for (int j = 0; j < n; j++) {
mat[i, j] = int.Parse(values[j]);
}
}
Console.WriteLine("Main diagonal");
for (int i = 0; i < n; i++) {
Console.Write(mat[i, i] + " ");
}
Console.WriteLine();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(mat[i,j] < 0) {
count++;
}
}
}
Console.WriteLine("Negative numbers " + count);
/* string[,] mat = new string[2, 3];
Console.WriteLine(mat.Length);
Console.WriteLine("rank numero de dimensoes da matriz " +mat.Rank); //
Console.WriteLine("quantidade de linhas da primeira coluna " +mat.GetLength(0)); //
Console.WriteLine("qtd linhas segunda coluna " + mat.GetLength(1)); //
Console.WriteLine("qtd linhas terceira coluna " + mat.GetLength(2)); //*/
}
}
}
<file_sep>using System;
namespace ModificadorParam {
class Program {
static void Main(string[] args) {
int s1 = Calculator.sum(1, 2, 3);
int s2 = Calculator.sum(3, 8, 9);
int a = 10;
Calculator.triple(ref a);
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(a);
string[] vect = new string[] {"aline", "maria", "cirilo" };
foreach (string nomes in vect) {
Console.WriteLine(nomes);
}
}
}
}
<file_sep>using System;
namespace StructsDados {
class Program {
static void Main(string[] args) {
Point p;
p.X = 10;
p.Y = 20;
//Trabalhando com Nullable
Nullable<double> x = null;
//forma mais simples nullable opcional
double? y = 10;
//operador de coalescência nula
double a = x ?? 0.5;
double b = y ?? 20;
Console.WriteLine(p);
Console.WriteLine();
Console.WriteLine(x.GetValueOrDefault());
Console.WriteLine(y.GetValueOrDefault());
Console.WriteLine(x.HasValue);
Console.WriteLine(y.HasValue);
if (x.HasValue)
Console.WriteLine(x.Value);
else
Console.WriteLine("x é null");
if (y.HasValue)
Console.WriteLine(y.Value);
else
Console.WriteLine("y é null");
//
Console.WriteLine(a);
Console.WriteLine(b);
}
}
}
<file_sep>using System;
using System.Globalization;
namespace FuncoesString {
class Program {
static void Main(string[] args) {
/*
string original = "abcde FGHIJ ABC abc DEFG ";
string toUpper = original.ToUpper();
string toLower = original.ToLower();
Console.WriteLine(original);
Console.WriteLine(toUpper);
Console.WriteLine(toLower);*/
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.ParseExact("2000-08-10", "yyyy-MM-dd", CultureInfo.InvariantCulture);
DateTime d3 = DateTime.Parse("2000-05-23 00:03:18");
//TimeSpan
TimeSpan t1 = new TimeSpan(0, 1, 40);
TimeSpan t2 = new TimeSpan();
TimeSpan t3 = new TimeSpan(1000000000L);
TimeSpan t4 = new TimeSpan(1, 2, 40, 30);
//TimeSpan.from
TimeSpan t5 = TimeSpan.FromDays(2.5);
TimeSpan t6 = TimeSpan.FromHours(2);
//Propriedades DateTime
DateTime d = new DateTime(2000, 8, 15, 13, 45, 58, 275);
Console.WriteLine(d.ToLongDateString());
Console.WriteLine("==================");
Console.WriteLine(d);
Console.WriteLine("(1) Date " +d.Date);
Console.WriteLine("(2) Day " +d.Day);
Console.WriteLine("(3) DayOfWeek " +d.DayOfWeek);
Console.WriteLine("(4) Month " +d.Month);
Console.WriteLine("(5) Year " +d.Year);
Console.WriteLine("=============");
Console.WriteLine(d1);
Console.WriteLine(d1.Ticks);
Console.WriteLine(d2);
Console.WriteLine(d3);
Console.WriteLine(t1);
Console.WriteLine(t1.Ticks);
Console.WriteLine(t2);
Console.WriteLine(t3);
Console.WriteLine(t4);
Console.WriteLine(t5);
Console.WriteLine(t6);
Console.WriteLine("=========================");
DateTime dtAtual = DateTime.Now;
DateTime dtVencimento = dtAtual.AddDays(3);
Console.WriteLine("Data atual " + dtAtual);
Console.WriteLine("Data vencimento " + dtVencimento);
Console.WriteLine("=============================");
Console.WriteLine("Diferença entre duas datas");
DateTime dt1 = new DateTime(2018, 3, 10);
DateTime dt2 = new DateTime(2018, 3, 14);
TimeSpan dDiff = dt2.Subtract(dt1);
Console.WriteLine("a diferença é " + dDiff.Days);
}
}
}
<file_sep>using System;
using System.Globalization;
namespace Exercicios01 {
class Program {
static void Main(string[] args) {
/*
Console.WriteLine("Informe o primeiro numero :");
int num = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o segundo numero :");
int num2 = int.Parse(Console.ReadLine());
int soma = num + num2;
Console.WriteLine($"A soma dos valores é : {soma}");*/
//Fórmula da área: area = π.raio2
//Considere o valor de π = 3.14159
double pi = 3.14159;
Console.WriteLine("Informe o dado de netrada para saber a area do circulo");
double area = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
double resultado = (pi * Math.Pow(area, 2));
Console.WriteLine("A = " +resultado.ToString("F4", CultureInfo.InvariantCulture));
}
}
}
| 9263c06c2e2b0428626245c7f5ed86882985a3d3 | [
"C#"
] | 18 | C# | dailtonduraes/chsarp | c8af349cf966b0cf396ff4d1baa382244be32618 | 5732872587c6289175c1123de89a2c40d7af4550 |
refs/heads/master | <file_sep>package ondoc.lkp.tests.delete;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class DeleteConsultation extends TestBase {
@Test
public void testDeleteConsultation() {
app.getNavigationHelper().gotoMedcard();
app.getConsultationHelper().deleteConsultation();
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DeleteAnalysis extends TestBase {
@Test
public void testDeleteAnalysis() {
app.getNavigationHelper().gotoMedcard();
app.getAnalysisHelper().goToInsertAnalysis();
if (! app.getAnalysisHelper().isThereAnalysis()) {
app.getAnalysisHelper().createFullAnalysis();
app.getNavigationHelper().backToList();
}
//int before = app.getAnalysisHelper().getAnalysisCount();
app.getAnalysisHelper().deleteAnalysis();
app.getAnalysisHelper().goToInsertAnalysis();
app.getNavigationHelper().refreshPage();
//int after = app.getAnalysisHelper().getAnalysisCount();
//Assert.assertEquals(after, before - 1);
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DeleteVaccination extends TestBase {
@Test
public void testDeleteVaccination() {
app.getNavigationHelper().gotoMedcard();
app.getVaccinationHelper().goToInsertVaccination();
if (! app.getVaccinationHelper().isThereVaccination()) {
app.getVaccinationHelper().createFullVaccination();
app.getNavigationHelper().backToList();
}
int before = app.getVaccinationHelper().getVaccinationCount();
app.getVaccinationHelper().deleteVaccination();
app.getVaccinationHelper().goToInsertVaccination();
app.getNavigationHelper().refreshPage();
int after = app.getVaccinationHelper().getVaccinationCount();
Assert.assertEquals(after, before - 1);
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class NavigationHelper extends HelperBase {
public NavigationHelper(WebDriver wd) {
super(wd);
}
public class Elements {
private static final String MEDCARD = "//div[2]/user-layout/div/div/div/aside/div[1]/div[4]/ul/li[2]/a";
private static final String CHOSE_TYPE = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[1]/div/div/div[2]/a";
}
public void save() {
click(By.xpath("//div[@class='widget']//button[.='Сохранить']"));
}
public void choseType() {
findAndClick(Elements.CHOSE_TYPE);
}
public void gotoMedcard() {
findAndClick(Elements.MEDCARD);
}
public void add() {
click(By.linkText("Добавить"));
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class AllergiesHelper extends HelperBase {
public AllergiesHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_ALLERG = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div";
private static final String EDIT = "/html/body/div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/allergy-details/div/section/div/div[1]/div/div[3]/patient-medcard-edit-button";
private static final String DELETE_BUTTON = "/html/body/div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/allergy-create/div/div[3]/div/div[1]/patient-medcard-allergy-delete-button/button";
}
public int getAllergiesCount() {
return wd.findElements(By.cssSelector("strong.font-medium")).size();
}
public void reactionAllergies(String reaction) {
type(By.xpath("(//input[@type='text'])[2]"), reaction);
}
public void createFullAllergies() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[1]/div/div/div[2]/a"));
createAllergies();
nameAllergies("Аллергия на лактозу");
reactionAllergies("Сыпь на коже в виде крапивницы, дерматита, экземы. Одышка, насморк, чихание, бронхиальная астма, отек Квинке.");
click(By.xpath("//div[@class='widget']//button[.='Сохранить']"));
commentInAllergies();
}
public boolean isThereAllergies() {
return isElementPresent(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div"));
}
public void nameAllergies(String name) {
type(By.xpath("//input[@type='text']"), name);
}
public void createAllergies() {
click(By.xpath("//*[@data-testid=\"medcard-type-allergy\"]"));
}
public void commentInAllergies() {
waiting(1, TimeUnit.MINUTES);
click(By.xpath("//div[@class='margin-bottom-large']/div[2]/button"));
click(By.cssSelector("strong"));
}
public void modificationAllergies() {
findAndClick(Elements.REC_ALLERG);
findAndClick(Elements.EDIT);
type(By.xpath("//div[@class='col-xs-17']/input"), "Аллергия на шоколад");
type(By.xpath("//div[@class='widget']/div[2]/div[1]/div[2]/div[3]/input"), "Красные пятна на коже");
}
public void deleteAllergies() {
goToInsertAllergies();
findAndClick(Elements.REC_ALLERG);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("/html/body/div[4]/div/div/div[2]/div/div[2]/button"));
}
public void attachDocument() {
click(By.xpath("//div[@class='widget']/div[2]/div[2]/files-attachment/div/label/span"));
}
public void goToInsertAllergies() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[7]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[7]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[7]/input"));
}
waiting(8, TimeUnit.SECONDS);
}
private File pdf;
public File getPdf() {
return pdf;
}
public void setPdf(File pdf) {
this.pdf = pdf;
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class AnalysisHelper extends HelperBase {
public AnalysisHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_ANALYSIS = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/strong";
private static final String EDIT = "/html/body/div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-details/div/section/div/div[1]/div/div[3]/patient-medcard-edit-button";
private static final String DELETE_BUTTON = "/html/body/div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-create/div/div[3]/div/div[1]/patient-medcard-analyze-delete-button/button";
}
public void createFullAnalysis() {
click(By.xpath("//*[@data-testid=\"medcard-type-analyze\"]"));
//click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[1]/div/div/div[2]/a"));
createAnalysis();
analysisName("Коагулограмма");
firstIndicator("Протромбиновое время", "13.5", "9.0 - 15.0", "cек", "good");
conclusionOfResults("Количество тромбоцитов в норме. Сосудисто-тромбоцитарный гемостаз в норме. Нормокоагуляция по внешнему и внутреннему пути активации плазменного гемостаза. Конечные этапы свертывания в норме. Активность антикоагулянтов и состояние фибринолитической системы в норме. Показатели коагулограммы в пределах физиологической нормы.");
click(By.xpath("//div[@class='widget']//button[.='Сохранить']"));
commentInAnalysis();
}
public boolean isThereAnalysis() {
return isElementPresent(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]"));
}
public void modificationAnalysis() {
findAndClick(Elements.REC_ANALYSIS);
findAndClick(Elements.EDIT);
analysisName("Щитовидная железа: расширенное обследование");
firstIndicator("Гемоглобин", "13.1", "11.7 - 15.5", "г/дл", "");
secondIndicator("MCH (ср. содер. Hb в эр.)", "29.8", "27.0 - 34.0", "пг", "");
conclusionOfResults("Необходимо включить в свой рацион продукты, содержащие йод: йодированная соль, морские сорта рыб, моллюски, ламинария, помидоры, капуста, фейхоа, клубника, клюква, лимон.");
}
public void conclusionOfResults(String conclusions) {
type(By.xpath("//div[@class='widget']/div[2]/div[4]/textarea"), conclusions);
}
public void secondIndicator(String index, String result, String normValue, String units, String comment) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[3]/input"), index);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[5]/input"), result);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[7]/input"), normValue);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[9]/input"), units);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[11]/input"), comment);
}
public void firstIndicator(String index, String result, String normValue, String units, String comment) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"), index);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[5]/input"), result);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[7]/input"), normValue);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[9]/input"), units);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[11]/input"), comment);
}
public void commentInAnalysis () {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-details/div/section/div/div[2]/medcard-comments-list/div/div[2]/button"));
click(By.cssSelector("buttton.r-button.r-button--blue-border"));
}
public void analysisName(String name) {
//type(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"), name);
type(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-create/div/div[2]/div[2]/div[2]/input"), name);
click(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"));
clear(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"));
}
public void createAnalysis() {
click(By.xpath("//*[@data-testid=\"medcard-type-analyze\"]"));
click(By.xpath("//div[@class='widget']//strong[.='Выберите клинику ']"));
click(By.cssSelector("div.font-small.gray-text"));
waiting(1, TimeUnit.MINUTES);
click(By.xpath("//div[@class='widget']//strong[.='Выберите врача ']"));
click(By.xpath("//div[@class='medcard-doctor__doc-find-wrapper']/div[1]/div/div[2]"));
//click(By.xpath("//div[1]/div/div[2]/div[2]/div[1]/div[1]/div/div[2]"));
click(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"));
clear(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"));
}
public void deleteAnalysis() {
goToInsertAnalysis();
findAndClick(Elements.REC_ANALYSIS);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("/html/body/div[4]/div/div/div[2]/div/div[2]/button"));
}
public void goToInsertAnalysis() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/input"));
}
waiting(8, TimeUnit.SECONDS);
}
public int getAnalysisCount() {
return wd.findElements(By.cssSelector("div.text-overflow.ng-binding")).size();
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DeleteNote extends TestBase {
@Test
public void testDeleteNote() {
app.getNavigationHelper().gotoMedcard();
app.getNoteHelper().goToInsertNote();
if (! app.getNoteHelper().isThereNote()) {
app.getNoteHelper().createFullNote();
app.getNavigationHelper().backToList();
}
int before = app.getNoteHelper().getNoteCount();
app.getNoteHelper().deleteNote();
app.getNoteHelper().goToInsertNote();
app.getNavigationHelper().refreshPage();
int after = app.getNoteHelper().getNoteCount();
Assert.assertEquals(after, before - 1);
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class NoteHelper extends HelperBase {
public NoteHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_NOTE = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/div";
private static final String EDIT = "//div[@class='widget']/div[1]/div/div[3]/a/span";
private static final String DELETE_BUTTON = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/note-create/notes-create-page/div/div[3]/div/div[1]/button";
}
public void descriptionNote(String descr) {
type(By.xpath("//div[@class='widget__textarea-wrapper']/textarea"), descr);
}
public void nameNote(String name) {
type(By.cssSelector("input.sc-dxgOiQ.jYQKwt"), name);
}
public void createNote() {
click(By.xpath("//div[1]/div/div[2]/medcard-type-modal/div[2]/div[3]/div[1]/div"));
}
public void deleteNote() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/input"));
}
findAndClick(Elements.REC_NOTE);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("//div[@class='custom-modal__modal']//strong[.='Удалить']"));
}
}
<file_sep>package ondoc.lkp.tests.creation;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class CreationAllergies extends TestBase {
@Test
public void testCreationAllergies() {
app.getNavigationHelper().gotoMedcard();
app.getNavigationHelper().choseType();
app.getAllergiesHelper().createAllergies();
app.getAllergiesHelper().nameAllergies("Аллергия на лактозу");
app.getAllergiesHelper().reactionAllergies("Сыпь на коже в виде крапивницы, дерматита, экземы. Одышка, насморк, чихание, бронхиальная астма, отек Квинке.");
app.getNavigationHelper().save();
app.getAllergiesHelper().commentInAllergies();
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ModificationCheckup extends TestBase {
@Test
public void testModificationCheckup() {
app.getNavigationHelper().gotoMedcard();
app.getCheckupHelper().goToInsertCheckup();
if (! app.getCheckupHelper().isThereCheckup()) {
app.getCheckupHelper().createFullCheckup();
app.getNavigationHelper().backToList();
}
int before = app.getCheckupHelper().getCheckupCount();
app.getCheckupHelper().modificationCheckup();
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
int after = app.getCheckupHelper().getCheckupCount();
Assert.assertEquals(after, before);
}
}
<file_sep>package ondoc.lkp.tests.delete;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class DeleteDentistry extends TestBase {
@Test
public void testDeleteDentistry() {
app.getNavigationHelper().gotoMedcard();
app.getDentistryHelper().deleteDentistry();
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class NavigationHelper extends HelperBase {
public NavigationHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String MEDCARD = "//a[contains(@href, '/medcard')]";
private static final String CHOSE_TYPE = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[1]/div/div/div[2]/a";
}
public void save() {
click(By.xpath("//button[@type='submit']"));
}
public void saveNote() {
click(By.xpath("/html/body/div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/note-create/notes-create-page/div/div[3]/div/div[2]/div/div[2]/button"));
}
public void choseType() {
waiting(10, TimeUnit.SECONDS);
findAndClick(Elements.CHOSE_TYPE);
}
public void gotoMedcard() {
waiting(1, TimeUnit.MINUTES);
findAndClick(Elements.MEDCARD);
}
public void backToList() {
click(By.linkText("Назад к списку"));
refreshPage();
waiting(20, TimeUnit.SECONDS);
}
public void refreshPage() {
wd.navigate().refresh();
}
public void add() {
click(By.linkText("Добавить"));
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ModificationAnalysis extends TestBase {
@Test
public void testModificationAnalysis() {
app.getNavigationHelper().gotoMedcard();
app.getAnalysisHelper().goToInsertAnalysis();
if (! app.getAnalysisHelper().isThereAnalysis()) {
app.getAnalysisHelper().createFullAnalysis();
app.getNavigationHelper().backToList();
}
int before = app.getAnalysisHelper().getAnalysisCount();
app.getAnalysisHelper().modificationAnalysis();
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
int after = app.getAnalysisHelper().getAnalysisCount();
Assert.assertEquals(after, before);
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ModificationConsultation extends TestBase{
@Test
public void testModificationConsultation() throws InterruptedException {
app.getNavigationHelper().gotoMedcard();
app.getConsultationHelper().goToInsertConsultation();
if (! app.getConsultationHelper().isThereConsultation()) {
app.getConsultationHelper().createFullConsultation();
app.getNavigationHelper().backToList();
}
int before = app.getConsultationHelper().getConsultationCount();
app.getConsultationHelper().modificationConsultation();
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
int after = app.getConsultationHelper().getConsultationCount();
Assert.assertEquals(after, before);
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CreationAllergies extends TestBase {
@Test
public void testCreationAllergies() {
app.getNavigationHelper().gotoMedcard();
app.getAllergiesHelper().goToInsertAllergies();
int before = app.getAllergiesHelper().getAllergiesCount();
app.getNavigationHelper().choseType();
app.getAllergiesHelper().createAllergies();
app.getAllergiesHelper().nameAllergies("Аллергия на лактозу");
app.getAllergiesHelper().reactionAllergies("Сыпь на коже в виде крапивницы, дерматита, экземы. Одышка, насморк, чихание, бронхиальная астма, отек Квинке.");
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
int after = app.getAllergiesHelper().getAllergiesCount();
Assert.assertEquals(after, before + 1);
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CreationVaccination extends TestBase {
@Test
public void testCreationVaccination () {
app.getNavigationHelper().gotoMedcard();
app.getVaccinationHelper().goToInsertVaccination();
//int before = app.getVaccinationHelper().getVaccinationCount();
app.getNavigationHelper().choseType();
app.getVaccinationHelper().createVaccination();
app.getVaccinationHelper().nameVaccination("Прививка от гриппа");
app.getVaccinationHelper().nameVaccine("Инфлювак");
app.getNavigationHelper().add();
//app.getVaccinationHelper().newDataVaccine2();
app.getVaccinationHelper().nameVaccine2("Гриппол");
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
//int after = app.getVaccinationHelper().getVaccinationCount();
//Assert.assertEquals(after, before + 1);
}
}<file_sep>package ondoc.lkp.tests.creation;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class CreationVaccination extends TestBase {
@Test
public void testCreationVaccination () {
app.getNavigationHelper().gotoMedcard();
app.getNavigationHelper().choseType();
app.getVaccinationHelper().createVaccination();
app.getVaccinationHelper().nameVaccination("Прививка от гриппа");
app.getVaccinationHelper().nameVaccine("Инфлювак");
app.getNavigationHelper().add();
app.getVaccinationHelper().newDataVaccine2();
app.getVaccinationHelper().nameVaccine2("Гриппол");
app.getNavigationHelper().save();
app.getVaccinationHelper().commentInVaccination();
}
}<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class ConsultationHelper extends HelperBase {
public ConsultationHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_CONSULTATION = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/div";
private static final String EDIT = "//div[@class='widget']/div[1]/div/div[3]/a/span";
private static final String DELETE_BUTTON = "//div[@class='widget']/div[3]/div/div[1]/medcard-delete-button/input";
private static final String COMMENT = "//div[@class='widget']/div[2]/medcard-comments-list/div/div[2]/button";
private static final String MKB = "//div[@id='icd-form-select_dropdown']/div[3]/div/div[2]";
private static final String CLINIC = "//div[1]/div/div[2]/div[3]/div[1]/div[1]/div/div[2]/strong";
private static final String DOCTOR = "//div[1]/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/a";
}
public void recommendations(String recomendadions) {
type(By.xpath("//div[@class='widget']/div[2]/div/div[1]/div[6]/div[2]/textarea"), recomendadions);
}
public void objectively(String objectivno) {
type(By.xpath("//div[@class='widget']/div[2]/div/div[1]/div[5]/div[2]/textarea"), objectivno);
}
public void anamnesis(String anam) {
type(By.xpath("//div[@class='widget']/div[2]/div/div[1]/div[4]/div[2]/textarea"), anam);
}
public void complaints(String zhalob) {
type(By.xpath("//div[@class='widget']/div[2]/div/div[1]/div[3]/div[2]/textarea"), zhalob);
}
public void diagnosis(String diag) {
type(By.xpath("//div[@class='widget']/div[2]/div/div[1]/div[2]/div[3]/input"), diag);
}
public void MKB() {
type(By.id("icd-form-select_value"), "it");
findAndClick(Elements.MKB);
}
public void createConsultation() throws InterruptedException {
click(By.xpath("//div[1]/div/div[2]/medcard-type-modal/div[2]/div[1]/div[1]/div"));
click(By.xpath("//div[@class='widget']//strong[normalize-space(.)='Выберите клинику']"));
findAndClick(Elements.CLINIC);
click(By.xpath("//div[@class='widget']//strong[normalize-space(.)='Выберите врача']"));
findAndClick(Elements.DOCTOR);
}
public void commentInConsultation() {
findAndClick(Elements.COMMENT);
click(By.cssSelector("strong"));
}
public void deleteConsultation() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[2]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[2]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[2]/input"));
}
findAndClick(Elements.REC_CONSULTATION);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("//div[@class='custom-modal__modal']//strong[.='Удалить']"));
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class VaccinationHelper extends HelperBase {
public VaccinationHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_VACCINATION = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/div";
private static final String EDIT = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/vaccination-details/div/section/div/div[1]/div/div[3]/a/span";
private static final String DELETE_BUTTON = "//div[@class='widget']/div[3]/div/div[1]/medcard-delete-button/input";
}
public void nameVaccine2(String name) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[3]/input"), name);
}
public void newDataVaccine2() {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[3]/div/calendar/div[2]/input"), "18.12.2019" );
}
public void nameVaccine(String name) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[2]/input"), name);
}
public void nameVaccination(String name) {
type(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"), name);
}
public void createVaccination() {
click(By.xpath("//div[1]/div/div[2]/medcard-type-modal/div[2]/div[4]/div/div"));
click(By.xpath("//div[@class='widget']//strong[normalize-space(.)='Выберите клинику']"));
waiting(2, TimeUnit.MINUTES);
click(By.xpath("//div[1]/div/div[2]/div[3]/div[1]/div[1]/div/div[2]"));
click(By.xpath("//div[@class='widget']//strong[normalize-space(.)='Выберите врача']"));
click(By.xpath("//div[1]/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/p"));
}
public void commentInVaccination() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/vaccination-details/div/section/div/div[2]/medcard-comments-list/div/div[2]/button"));
click(By.cssSelector("buttton.r-button.r-button--blue-border"));
}
public void deleteVaccination() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[8]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[8]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[8]/input"));
}
findAndClick(Elements.REC_VACCINATION);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("//div[@class='custom-modal__modal']//strong[.='Удалить']"));
}
}
<file_sep>package ondoc.lkp.tests.delete;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class DeleteCheckup extends TestBase {
@Test
public void testDeleteCheckup() {
app.getNavigationHelper().gotoMedcard();
app.getCheckupHelper().deleteCheckup();
}
}
<file_sep>package ondoc.lkp.tests.medcard;
import ondoc.lkp.tests.TestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ModificationNote extends TestBase {
@Test
public void testModificationNote() {
app.getNavigationHelper().gotoMedcard();
app.getNoteHelper().goToInsertNote();
if (! app.getNoteHelper().isThereNote()) {
app.getNoteHelper().createFullNote();
app.getNavigationHelper().backToList();
}
int before = app.getNoteHelper().getNoteCount();
app.getNoteHelper().modificationNote();
app.getNavigationHelper().save();
app.getNavigationHelper().backToList();
int after = app.getNoteHelper().getNoteCount();
Assert.assertEquals(after, before);
}
}
<file_sep>package ondoc.lkp.tests.modification;
public class ModificationAllergies {
}
<file_sep>package ondoc.lkp.tests.creation;
import ondoc.lkp.tests.TestBase;
import org.testng.annotations.Test;
public class CreationAnalysis extends TestBase {
@Test
public void testCreateAnalysis() {
app.getNavigationHelper().gotoMedcard();
app.getNavigationHelper().choseType();
app.getAnalysisHelper().createAnalysis();
app.getAnalysisHelper().analysisName("Гемостазиограмма (коагулограмма) расширенная");
app.getAnalysisHelper().firstIndicator("Протромбиновое время", "13.5", "9.0 - 15.0", "cек", "");
app.getNavigationHelper().add();
app.getAnalysisHelper().secondIndicator("Фибриноген", "2.6", "г/л", "2.0 - 4.0", "Во втором и третьем триместрах беременности возможно физиологическое повышение уровня фибриногена до 5,6 г/л");
app.getAnalysisHelper().conclusionOfResults("Количество тромбоцитов в норме. Сосудисто-тромбоцитарный гемостаз в норме. Нормокоагуляция по внешнему и внутреннему пути активации плазменного гемостаза. Конечные этапы свертывания в норме. Активность антикоагулянтов и состояние фибринолитической системы в норме. Показатели коагулограммы в пределах физиологической нормы.");
app.getNavigationHelper().save();
app.getAnalysisHelper().commentInAnalysis();
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class AnalysisHelper extends HelperBase {
public AnalysisHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_ANALYSIS = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/strong";
private static final String EDIT = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-details/div/section/div/div[1]/div/div[3]/a/span";
private static final String DELETE_BUTTON = "//div[@class='widget']/div[3]/div/div[1]/medcard-delete-button/input";
}
public void conclusionOfResults(String conclusions) {
type(By.xpath("//div[@class='widget']/div[2]/div[4]/textarea"), conclusions);
}
public void secondIndicator(String index, String result, String normValue, String units, String comment) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[3]/input"), index);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[5]/input"), result);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[7]/input"), normValue);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[9]/input"), units);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div[2]/div/div[11]/input"), comment);
}
public void firstIndicator(String index, String result, String normValue, String units, String comment) {
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"), index);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[5]/input"), result);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[7]/input"), normValue);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[9]/input"), units);
type(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[11]/input"), comment);
}
public void commentInAnalysis () {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/analyze-details/div/section/div/div[2]/medcard-comments-list/div/div[2]/button"));
click(By.cssSelector("buttton.r-button.r-button--blue-border"));
}
public void analysisName(String name) {
type(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"), name);
click(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"));
clear(By.xpath("//div[@class='widget']/div[2]/div[3]/div[4]/div/div/div[3]/input"));
}
public void createAnalysis() {
click(By.xpath("//div[1]/div/div[2]/medcard-type-modal/div[2]/div[1]/div[2]/div"));
click(By.cssSelector("strong.ng-scope"));
waiting(2, TimeUnit.MINUTES);
click(By.xpath("//div[1]/div/div[2]/div[3]/div[1]/div[1]/div/div[2]"));
click(By.cssSelector("strong.ng-scope"));
click(By.xpath("//div[1]/div/div[2]/div[2]/div[1]/div[1]/div/div[2]"));
click(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"));
clear(By.xpath("//div[@class='widget']/div[2]/div[2]/div[2]/input"));
}
public void deleteAnalysis() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[3]/input"));
}
findAndClick(Elements.REC_ANALYSIS);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("//div[@class='custom-modal__modal']//strong[.='Удалить']"));
}
}
<file_sep>package ondoc.lkp.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class NoteHelper extends HelperBase {
public NoteHelper(WebDriver wd) {
super(wd);
}
private class Elements {
private static final String REC_NOTE = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/div";
private static final String EDIT = "//div[@class='widget']/div[1]/div/div[3]/a/span";
private static final String DELETE_BUTTON = "//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/note-create/notes-create-page/div/div[3]/div/div[1]/button";
}
public boolean isThereNote() {
return isElementPresent(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[2]/div/div/medcard-list-item/div/div/div[1]/div[2]/div"));
}
public void createFullNote() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[1]/div/div/div[2]/a"));
createNote();
nameNote("Для удаления");
descriptionNote("Тест по удалению");
click(By.xpath("//div[@class='widget']//button[.='Сохранить']"));
}
public void modificationNote() {
findAndClick(Elements.REC_NOTE);
findAndClick(Elements.EDIT);
clear(By.xpath("//div[@class='widget']/div[2]/div[1]/div[1]/div[2]/input"));
nameNote("Редактирование заметки");
descriptionNote("Тест по редактированию");
}
public void descriptionNote(String descr) {
type(By.xpath("//div[@class='widget__textarea-wrapper']/textarea"), descr);
}
public void nameNote(String name) {
type(By.xpath("//div[@class='widget']/div[2]/div[1]/div[1]/div[2]/input"), name);
}
public void createNote() {
click(By.xpath("//*[@data-testid=\"medcard-type-note\"]"));
//click(By.xpath("//div[1]/div/div[2]/medcard-type-modal/div[2]/div[3]/div[1]/div"));
}
public void deleteNote() {
goToInsertNote();
findAndClick(Elements.REC_NOTE);
findAndClick(Elements.EDIT);
findAndClick(Elements.DELETE_BUTTON);
click(By.xpath("//div[@class='custom-modal__modal']//strong[.='Удалить']"));
}
public void goToInsertNote() {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/span"));
if (!wd.findElement(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/input")).isSelected()) {
click(By.xpath("//div[2]/user-layout/div/div/div/section/medcard-layout/ui-view/medcard-list/div/div[1]/div[3]/label[6]/input"));
}
waiting(8, TimeUnit.SECONDS);
}
public int getNoteCount() {
return wd.findElements(By.cssSelector("div.text-overflow")).size();
}
}
| 5ab3b81d8bc51ee88894b1c867dda34e99db9e24 | [
"Java"
] | 25 | Java | vi-babaeva/ondoc | 501cfdc265f401172ef9d29bc843cf15389338c4 | f209a2594512a8e40fe2235d6cb9a0b915cabace |
refs/heads/master | <file_sep>#Require shiny
library(shiny)
library(plotly)
# Generate list of major categories
data <- read.csv("data/all-ages.csv", stringsAsFactors = FALSE)
categories <- sort(data$Major_category)
# Page on most popular majors
popularity <- tabPanel('Popularity',
titlePanel('Most Popular Majors'),
p("This plot displays the most popular college majors."),
sidebarLayout(
sidebarPanel(
#radioButtons('sex', label = 'Sex', choices = list("Female" = "Women", "Male" = "Men", "Both" = "Total"), selected = "Total"),
selectInput('category', label = 'Category', choices = c("Overall", categories), selected = "Overall"),
sliderInput('num.majors', label = 'Number to Display', min = 1, max = 10, value = c(1, 10))
),
mainPanel(
plotlyOutput('popularity')
)
)
)
# Page on major salaries
salaries <- tabPanel('Salaries',
titlePanel('Majors by Median Salary'),
p("Under construction!"),
sidebarLayout(
sidebarPanel(
selectInput('category', label = 'Category', choices = c("Overall", categories), selected = "Overall"),
sliderInput('num.majors', label = 'Number to Display', min = 1, max = 10, value = c(1, 10))
),
mainPanel(
#plotlyOutput('popularity')
)
)
)
shinyUI(navbarPage('College Majors',
popularity,
salaries
))
<file_sep># college-majors
This app visualizes data on college majors. [Here is a link to the app.](https://jchou.shinyapps.io/college-majors/)
Cleaned data taken from [FiveThirtyEight's GitHub](https://github.com/fivethirtyeight/data/tree/master/college-majors).
<file_sep># Include libraries
require(shiny)
require(dplyr)
require(ggplot2)
# Read in data
all.grads <- read.csv("data/all-ages.csv", stringsAsFactors = FALSE)
recent.grads <- read.csv("data/recent-grads.csv", stringsAsFactors = FALSE)
shinyServer(function(input, output, session) {
popularity.data <- reactive({
# Data by sex is flawed and seems to be inaccurate
# filtered.data <- recent.grads %>% select(Major, Major_category, Men, Women) %>%
# mutate(Total = Men + Women) %>%
# filter(Major_category == input$category | input$category == "Overall")
#
# filtered.data <- filtered.data %>% arrange_(paste0("desc(", input$sex, ")"))
filtered.data <- all.grads %>% select(Major, Major_category, Total) %>%
filter(Major_category == input$category | input$category == "Overall") %>%
arrange(desc(Total))
updateSliderInput(session, "num.majors", max = nrow(filtered.data))
return(filtered.data)
})
popularity.data.limited <- reactive({
limited.data <- popularity.data() %>% top_n(input$num.majors[2]) %>% top_n(-(input$num.majors[2] - input$num.majors[1] + 1))
return(limited.data)
})
output$popularity <- renderPlotly({
# plot <- plot_ly(popularity.data.limited(), type = "bar")
#
# if (input$sex == "Men" | input$sex == "Total") {
# plot <- plot %>% add_trace(y = ~Men, x = ~Major, name = "Male",
# marker = list(color = "rgb(31, 119, 180)"),
# hoverinfo = "text",
# text = ~paste("Major: ", Major,
# "</br>Men: ", Men,
# "</br>Total: ", Total))
# }
#
# if (input$sex == "Women" | input$sex == "Total") {
# plot <- plot %>% add_trace(y = ~Women, x = ~Major, name = "Female",
# marker = list(color = "rgb(255, 127, 14)"),
# hoverinfo = "text",
# text = ~paste("Major: ", Major,
# "</br>Women: ", Women,
# "</br>Total: ", Total))
# }
#
plot <- plot_ly(popularity.data.limited(), type = "bar", x = ~Major, y = ~Total,
hoverinfo = "text",
text = ~paste("Major: ", Major,
"</br>Number of graduates: ", Total))
plot <- plot %>% layout(xaxis = list(title = "Major",
categoryorder = "array", categoryarray = popularity.data.limited()$Total),
yaxis = list(title = "Count"),
barmode = 'stack',
margin = list(b = 80, r = 50))
return (plot)
})
output$popularity.table <- renderTable({
return (popularity.data())
})
}) | ee9d16312802ee814a888ace74c00b08cf9966d1 | [
"Markdown",
"R"
] | 3 | R | jchou8/college-majors | afebb42a99303aef814fa346861b757551a1810c | a42c988fa220cd854fa430dc72c869f0341b7356 |
refs/heads/master | <file_sep>
ARMGNU ?= arm-none-eabi
COPS = -Wall -O2 -nostdlib -nostartfiles -ffreestanding
gcc : kernel7.img
all : gcc clang
clean :
rm -f *.o
rm -f *.bin
rm -f *.hex
rm -f *.elf
rm -f *.list
rm -f *.img
rm -f *.bc
rm -f *.clang.s
vectors.o : vectors.s
$(ARMGNU)-as vectors.s -o vectors.o
bootloader07.o : bootloader07.c
$(ARMGNU)-gcc $(COPS) -c bootloader07.c -o bootloader07.o
periph.o : periph.c
$(ARMGNU)-gcc $(COPS) -c periph.c -o periph.o
kernel7.img : loader vectors.o periph.o bootloader07.o
$(ARMGNU)-ld vectors.o periph.o bootloader07.o -T loader -o bootloader07_rpi1.elf
$(ARMGNU)-objdump -D bootloader07_rpi1.elf > bootloader07_rpi1.list
$(ARMGNU)-objcopy bootloader07_rpi1.elf -O ihex bootloader07_rpi1.hex
$(ARMGNU)-objcopy bootloader07_rpi1.elf -O binary kernel7.img
LOPS = -Wall -m32 -emit-llvm
LLCOPS0 = -march=arm
LLCOPS1 = -march=arm -mcpu=arm1176jzf-s
LLCOPS = $(LLCOPS1)
COPS = -Wall -O2 -nostdlib -nostartfiles -ffreestanding
OOPSx = -std-compile-opts
OOPS = -std-link-opts
clang : bootloader07.clang.bin
bootloader07.bc : bootloader07.c
clang $(LOPS) -c bootloader07.c -o bootloader07.bc
periph.bc : periph.c
clang $(LOPS) -c periph.c -o periph.bc
bootloader07.clang.elf : loader vectors.o bootloader07.bc periph.bc
llvm-link periph.bc bootloader07.bc -o bootloader07.nopt.bc
opt $(OOPS) bootloader07.nopt.bc -o bootloader07.opt.bc
llc $(LLCOPS) bootloader07.opt.bc -o bootloader07.clang.s
$(ARMGNU)-as bootloader07.clang.s -o bootloader07.clang.o
$(ARMGNU)-ld -o bootloader07.clang.elf -T loader vectors.o bootloader07.clang.o
$(ARMGNU)-objdump -D bootloader07.clang.elf > bootloader07.clang.list
bootloader07.clang.bin : bootloader07.clang.elf
$(ARMGNU)-objcopy bootloader07.clang.elf bootloader07.clang.bin -O binary
<file_sep>
ARMGNU ?= aarch64-none-elf
COPS = -Wall -O2 -nostdlib -nostartfiles -ffreestanding
gcc : kernel7.img
all : gcc
clean :
rm -f *.o
rm -f *.bin
rm -f *.hex
rm -f *.elf
rm -f *.list
rm -f *.img
rm -f *.bc
rm -f *.clang.s
vectors.o : vectors.s
$(ARMGNU)-as vectors.s -o vectors.o
bootloader07.o : bootloader07.c
$(ARMGNU)-gcc $(COPS) -c bootloader07.c -o bootloader07.o
periph7.o : periph.c
$(ARMGNU)-gcc $(COPS) -c periph.c -o periph7.o
kernel7.img : loader vectors.o periph7.o bootloader07.o
$(ARMGNU)-ld vectors.o periph7.o bootloader07.o -T loader -o bootloader07_rpi2.elf
$(ARMGNU)-objdump -D bootloader07_rpi2.elf > bootloader07_rpi2.list
$(ARMGNU)-objcopy bootloader07_rpi2.elf -O ihex bootloader07_rpi2.hex
$(ARMGNU)-objcopy bootloader07_rpi2.elf -O binary kernel7.img
<file_sep>
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
#include "fontdata.h"
extern void PUT32 ( unsigned int, unsigned int );
extern unsigned int GET32 ( unsigned int );
extern void dummy ( unsigned int );
#define GPFSEL0 0x20200000
#define GPFSEL1 0x20200004
#define GPFSEL2 0x20200008
#define GPSET0 0x2020001C
#define GPCLR0 0x20200028
#define GPPUD 0x20200094
#define GPPUDCLK0 0x20200098
#define AUX_ENABLES 0x20215004
#define AUX_MU_IO_REG 0x20215040
#define AUX_MU_IER_REG 0x20215044
#define AUX_MU_IIR_REG 0x20215048
#define AUX_MU_LCR_REG 0x2021504C
#define AUX_MU_MCR_REG 0x20215050
#define AUX_MU_LSR_REG 0x20215054
#define AUX_MU_MSR_REG 0x20215058
#define AUX_MU_SCRATCH 0x2021505C
#define AUX_MU_CNTL_REG 0x20215060
#define AUX_MU_STAT_REG 0x20215064
#define AUX_MU_BAUD_REG 0x20215068
#define AUX_SPI0_CS 0x20204000
#define AUX_SPI0_FIFO 0x20204004
#define AUX_SPI0_CLK 0x20204008
#define AUX_SPI0_DLEN 0x2020400C
#define AUX_SPI0_LTOH 0x20204010
#define AUX_SPI0_DC 0x20204014
#define SETCONTRAST 0x81
#define DISPLAYALLONRESUME 0xA4
#define DISPLAYALLON 0xA5
#define NORMALDISPLAY 0xA6
#define INVERTDISPLAY 0xA7
#define DISPLAYOFF 0xAE
#define DISPLAYON 0xAF
#define SETDISPLAYOFFSET 0xD3
#define SETCOMPINS 0xDA
#define SETVCOMDESELECT 0xDB
#define SETDISPLAYCLOCKDIV 0xD5
#define SETPRECHARGE 0xD9
#define SETMULTIPLEX 0xA8
#define SETLOWCOLUMN 0x00
#define SETHIGHCOLUMN 0x10
#define SETSTARTLINE 0x40
#define MEMORYMODE 0x20
#define COMSCANINC 0xC0
#define COMSCANDEC 0xC8
#define SEGREMAP 0xA0
#define CHARGEPUMP 0x8D
#define EXTERNALVCC 0x01
#define SWITCHCAPVCC 0x02
unsigned int hex_screen_history[6];
unsigned char xstring[32];
unsigned int tim[4];
//GPIO14 TXD0 and TXD1
//GPIO15 RXD0 and RXD1
//alt function 5 for uart1
//alt function 0 for uart0
//((250,000,000/115200)/8)-1 = 270
//------------------------------------------------------------------------
void uart_init ( void )
{
unsigned int ra;
ra=GET32(AUX_ENABLES);
ra|=1; //enable mini uart
PUT32(AUX_ENABLES,ra);
PUT32(AUX_MU_IER_REG,0);
PUT32(AUX_MU_CNTL_REG,0);
PUT32(AUX_MU_LCR_REG,3);
PUT32(AUX_MU_MCR_REG,0);
PUT32(AUX_MU_IER_REG,0);
PUT32(AUX_MU_IIR_REG,0xC6);
// PUT32(AUX_MU_BAUD_REG,270); //115200
PUT32(AUX_MU_BAUD_REG,3254); //9600?
//setup gpio before enabling uart
ra=GET32(GPFSEL1);
ra&=~(7<<12); //gpio14
ra|=2<<12; //alt5
ra&=~(7<<15); //gpio15
ra|=2<<15; //alt5
PUT32(GPFSEL1,ra);
PUT32(GPPUD,0);
for(ra=0;ra<150;ra++) dummy(ra);
PUT32(GPPUDCLK0,(1<<14)|(1<<15));
for(ra=0;ra<150;ra++) dummy(ra);
PUT32(GPPUDCLK0,0);
//enable uart
PUT32(AUX_MU_CNTL_REG,3);
}
//------------------------------------------------------------------------
void uart_putc ( unsigned int c )
{
while(1)
{
if(GET32(AUX_MU_LSR_REG)&0x20) break;
}
PUT32(AUX_MU_IO_REG,c);
}
//------------------------------------------------------------------------
unsigned int uart_recv ( void )
{
while(1)
{
if(GET32(AUX_MU_LSR_REG)&0x01) break;
}
return(GET32(AUX_MU_IO_REG)&0xFF);
}
//------------------------------------------------------------------------
void hexstrings ( unsigned int d )
{
//unsigned int ra;
unsigned int rb;
unsigned int rc;
rb=32;
while(1)
{
rb-=4;
rc=(d>>rb)&0xF;
if(rc>9) rc+=0x37; else rc+=0x30;
uart_putc(rc);
if(rb==0) break;
}
uart_putc(0x20);
}
//------------------------------------------------------------------------
void hexstring ( unsigned int d )
{
hexstrings(d);
uart_putc(0x0D);
uart_putc(0x0A);
}
//GPIO7 SPI0_CE1_N P1-26 (use for reset)
//GPIO8 SPI0_CE0_N P1-24
//GPIO9 SPI0_MISO P1-21
//GPIO10 SPI0_MOSI P1-19
//GPIO11 SPI0_SCLK P1-23
//alt function 0 for all of the above
//P1 1 +3V3
//P1 25 GND
//P1 22 GPIO25 use as D/C
//------------------------------------------------------------------------
void spi_init ( void )
{
unsigned int ra;
ra=GET32(AUX_ENABLES);
ra|=2; //enable spi0
PUT32(AUX_ENABLES,ra);
ra=GET32(GPFSEL0);
//ra&=~(7<<27); //gpio9
//ra|=4<<27; //alt0
//ra|=1<<27; //output
ra&=~(7<<24); //gpio8
ra|=4<<24; //alt0
ra&=~(7<<21); //gpio7
//ra|=4<<21; //alt0
ra|=1<<21; //output
PUT32(GPFSEL0,ra);
ra=GET32(GPFSEL1);
ra&=~(7<<0); //gpio10/
ra|=4<<0; //alt0
ra&=~(7<<3); //gpio11/
ra|=4<<3; //alt0
PUT32(GPFSEL1,ra);
ra=GET32(GPFSEL2);
ra&=~(7<<15); //gpio25/
ra|=1<<15; //output
PUT32(GPFSEL2,ra);
PUT32(AUX_SPI0_CS,0x0000030);
// PUT32(AUX_SPI0_CLK,0x0000); //slowest possible, could probably go faster here
PUT32(AUX_SPI0_CLK,26);
}
//------------------------------------------------------------------------
void spi_one_byte ( unsigned int x )
{
PUT32(AUX_SPI0_CS,0x000000B0); //TA=1 cs asserted
while(1)
{
if(GET32(AUX_SPI0_CS)&(1<<18)) break; //TXD
}
PUT32(AUX_SPI0_FIFO,x&0xFF);
while(1) if(GET32(AUX_SPI0_CS)&(1<<16)) break;
//while(1) if(GET32(AUX_SPI0_CS)&(1<<17)) break; //should I wait for this?
PUT32(AUX_SPI0_CS,0x00000000); //cs0 comes back up
}
//------------------------------------------------------------------------
void spi_command ( unsigned int cmd )
{
PUT32(GPCLR0,1<<25); //D/C = 0 for command
spi_one_byte(cmd);
}
//------------------------------------------------------------------------
void spi_data ( unsigned int data )
{
PUT32(GPSET0,1<<25); //D/C = 1 for data
spi_one_byte(data);
}
//------------------------------------------------------------------------
//void show_string ( unsigned int row, const char *s )
//{
//unsigned int ra;
//unsigned int rb;
//unsigned int rc;
//unsigned int rd;
//row&=7;
//spi_command(0x80); //column
//spi_command(0x40|row); //row
//rc=0;
//for(ra=0;ra<11;ra++)
//{
//if(s[ra]==0) break;
//for(rb=0;rb<8;rb++)
//{
//rd=s[ra];
//spi_data(fontdata[rd][rb]);
//rc++;
//}
//}
//for(;rc<84;rc++) spi_data(0);
//}
//------------------------------------------------------------------------
void show_time ( void )
{
unsigned int ra;
unsigned int rb;
unsigned int rc;
unsigned int rd;
unsigned int re;
unsigned int rf;
uart_putc(0x30+(tim[0]&0xF));
uart_putc(0x30+(tim[1]&0xF));
uart_putc(0x30+(tim[2]&0xF));
uart_putc(0x30+(tim[3]&0xF));
uart_putc(0x0D);
uart_putc(0x0A);
for(rb=0;rb<5;rb++)
{
spi_command(0x80); //column
spi_command(0x40|rb); //row
if(tim[0]==0) re=0x00;
else re=0xFF;
for(rf=0;rf<6;rf++) spi_data(re);
for(rf=0;rf<6;rf++) spi_data(0x00);
for(ra=1;ra<4;ra++)
{
rc=clockdata[tim[ra]][rb];
for(rd=0x8;rd;rd>>=1)
{
if(rc&rd) re=0xFF;
else re=0x00;
for(rf=0;rf<6;rf++) spi_data(re);
}
}
//for(rf=0;rf<0x1000;rf++) dummy(rf);
}
}
//------------------------------------------------------------------------
int do_nmea ( void )
{
unsigned int ra;
unsigned int rb;
unsigned int rc;
unsigned int state;
unsigned int off;
//unsigned char toggle_seconds;
//toggle_seconds=0;
state=0;
off=0;
//$GPRMC,054033.00,V,
while(1)
{
ra=uart_recv();
//**/ uart_putc(ra);
//uart_putc(0x30+state);
switch(state)
{
case 0:
{
if(ra=='$') state++;
else state=0;
break;
}
case 1:
{
if(ra=='G') state++;
else state=0;
break;
}
case 2:
{
if(ra=='P') state++;
else state=0;
break;
}
case 3:
{
if(ra=='R') state++;
else state=0;
break;
}
case 4:
{
if(ra=='M') state++;
else state=0;
break;
}
case 5:
{
if(ra=='C') state++;
else state=0;
break;
}
case 6:
{
off=0;
if(ra==',') state++;
else state=0;
break;
}
case 7:
{
if(ra==',')
{
if(off>7)
{
rb=xstring[0]&0xF;
rc=xstring[1]&0xF;
//1010
rb=/*rb*10*/(rb<<3)+(rb<<1); //times 10
rb+=rc;
if(rb>12) rb-=12;
ra=5; //time zone adjustment
if(rb<=ra) rb+=12;
rb-=ra;
if(rb>9)
{
xstring[0]='1';
rb-=10;
}
else
{
xstring[0]='0';
}
rb&=0xF;
xstring[1]=0x30+rb;
rb=0;
//zstring[rb++]=0x77;
//toggle_seconds^=0x10;
//zstring[rb++]=toggle_seconds;
//zstring[rb++]=xstring[0];
//zstring[rb++]=xstring[1];
//zstring[rb++]=xstring[2];
//zstring[rb++]=xstring[3];
//xstring[rb++]=0x0D;
//zstring[rb++]=0;
tim[0]=xstring[0]&0xF;
tim[1]=xstring[1]&0xF;
tim[2]=xstring[2]&0xF;
tim[3]=xstring[3]&0xF;
}
else
{
//zstring[0]=0x33;
//zstring[1]=0x33;
//zstring[2]=0x33;
//zstring[3]=0x33;
//xstring[4]=0x0D;
//zstring[5]=0;
tim[0]=0;
tim[1]=0;
tim[2]=0;
tim[3]=0;
}
off=0;
state++;
}
else
{
if(off<16)
{
xstring[off++]=ra;
}
}
break;
}
case 8:
{
//if(zstring[off]==0)
//{
//state=0;
//}
//else
//{
//uart_send(zstring[off++]);
//}
show_time();
state=0;
break;
}
}
}
return(0);
}
//------------------------------------------------------------------------
int notmain ( void )
{
unsigned int ra;
unsigned int rf;
uart_init();
hexstring(0x12345678);
for(ra=0;ra<10;ra++)
{
hexstring(ra);
}
spi_init();
PUT32(GPSET0,1<<7); //reset high
for(ra=0;ra<0x10000;ra++) dummy(ra);
PUT32(GPCLR0,1<<7); //reset low
for(ra=0;ra<0x10000;ra++) dummy(ra);
PUT32(GPSET0,1<<7); //reset high
spi_command(0x21); //extended commands
// spi_command(0xB0); //vop less contrast
spi_command(0xBF); //vop more contrast
spi_command(0x04); //temp coef
spi_command(0x14); //bias mode 1:48
spi_command(0x20); //extended off
spi_command(0x0C); //display on
spi_command(0x80); //column
spi_command(0x40|5); //row
for(rf=0;rf<84;rf++) spi_data(0x00);
tim[0]=0;
tim[1]=0;
tim[2]=0;
tim[3]=0;
show_time();
do_nmea();
hexstring(0x12345678);
return(0);
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//
// Copyright (c) 2015 <NAME> <EMAIL>
//
// 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.
//
//-------------------------------------------------------------------------
| eb09a7e52e3c607b434a4b2d0b7e148e67aff402 | [
"C",
"Makefile"
] | 3 | Makefile | ccccjason/raspberrypi-1 | 0e81e9f7ea19854c98ea3ffdb522d1e39fac0438 | 05d72d1fb143d691c3b67220c93503c4daf4c540 |
refs/heads/master | <repo_name>jamesXG/weChat_applets<file_sep>/pages/campus/campus.js
import { Campus } from 'campus-model';
const CampusData = new Campus();
let detailStorage;
Page({
data: {
navigationIcon: "../../image/icon/navigation.png",
},
onLoad: function (options) {
CampusData.showLoading();
this._onload();
},
_onload: function () {
let banner_id = 1;
CampusData.getBannerId(banner_id, (res) => {
this.setData({
banner: res.item
})
});
this._loadDetail();
wx.hideLoading();
},
_loadDetail: function () {
let detail_id = 2;
CampusData.getDetailById(detail_id, (res) => {
this.setData({
detailInfo: res
});
});
},
toMapTap: function () {
wx.navigateTo({
url: '../index/index',
})
}
})<file_sep>/pages/search/search-model.js
import { Base } from '../../utils/base.js'
class Search extends Base {
constructor() {
super();
}
// 搜索内容
searchLocationByName(name, page, callback) {
let params = {
url: `/search/${name}/${page}`,
sCallback: function (res) {
callback && callback(res);
}
};
this.request(params);
}
}
export { Search };<file_sep>/README.md
# weChat_applets
校内导航微信小程序
## 接口规范
* RestFul API规则
<file_sep>/pages/bus/detail/detail-model.js
import {
Base
} from '../../../utils/base';
class busDetail extends Base {
constructor() {
super();
}
}
export {
busDetail
}<file_sep>/utils/base.js
import {
Config
} from 'config'; //配置文件
class Base {
constructor() {
this.baseRequestUrl = Config.baseUrl;
}
// 请求API方法
request(params) {
var url = this.baseRequestUrl + params.url;
if (!params.type) {
params.type = 'GET';
}
wx.request({
url: url,
data: params.data,
method: params.type,
header: {
'content-type': 'application/json',
// 'token': wx.getStorageInfoSync('token')
},
success: function (res) {
params.sCallback && params.sCallback(res.data);
},
fail: function (err) {
params.sCallback && params.sCallback(res);
}
})
}
// 获取元素绑定的值
getDataSet(event, key) {
return event.currentTarget.dataset[key];
}
showLoading(title = '加载中……') {
wx.showLoading({
title: title
})
}
/**
* @successRunClass 需要执行的方法
*/
showModal(content, isReturn = true, isShowCancel = false, callback) {
wx.showModal({
title: '提示',
content: content,
showCancel: isShowCancel,
success: function (res) {
if (isReturn) {
wx.navigateBack({
data: 1
})
} else if (res.cancel) {
wx.navigateBack({
data: 1
})
} else if (res.confirm) {
callback('ok')
}
}
})
}
// 设置缓存
setLocationStorage(key, data, callback) {
// let isExist = this.isExistCached(key, (res) => {
let res = wx.getStorageSync(key);
// console.log(res)
if (!res.hasOwnProperty('data')) {
wx.setStorage({
key: key,
data: this.setCacheData(data)
});
callback('success');
} else {
callback(key + ' is existed');
}
// });
}
// 设置给定缓存的有效期(已废弃,请采用setCacheData())
getCacheExpired(cacheName) {
let expired = new Date().getTime() + Config.expired;
if (cacheName instanceof Array) {
cacheName[cacheName.length] = expired;
} else {
cacheName.expired = expired;
}
}
// 设置需要缓存的数据并给加上缓存时间
setCacheData(data) {
let expired = new Date().getTime() + Config.expired;
function oResult(data) {
this.result = data;
this.expired = expired;
}
return new oResult(data);
}
/**
* 判断缓存是否过期
* @param cacheName 缓存的key值
* @param data 传入的缓存数据
* @return true:过期了;false:没有过期
*/
isExpired(cacheName, data) {
let nowTime = new Date().getTime();
if (data instanceof Array) {
let len = data.length;
return nowTime > data[len - 1] ? true : false;
} else {
return nowTime > data.expired ? true : false;
}
}
/**
* 最佳路径路径导航 driving: 驾车 walking: 步行 transit: 公交
*/
mapNavigation(froms, to, pathType, callback) {
wx.request({
url: Config.mapApi + pathType + '/',
data: {
from: froms,
to: to,
key: Config.key
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
callback(res)
},
fail: function (err) {
callback(err)
}
})
}
// 获取当前位置经纬度
getCurrentLocation(callback) {
wx.getLocation({
type: 'gcj02',
success: function (res) {
callback(res)
},
fail: function (err) {
callback(err)
// wx.showModal({
// title: '提示',
// content: '你点击了拒绝授权,将无法进行下一步操作,请先同意授权',
// success: function (res) {
// if (res.confirm) {
// wx.getSetting({
// success: function (res) {
// res.authSetting = {
// "scope.userLocation": true
// }
// wx.getLocation({
// success: function(res) {
// callback(res)
// },
// })
// }
// })
// }
// }
// })
}
})
}
// 依据分钟计算时分
setRuleTime(time) {
let duration = parseInt(time); //分钟
if (duration <= 60) {
return duration + '分钟';
}
let hour = parseInt(duration / 60),
min = parseInt(duration % 60);
return hour + '小时' + min + '分钟';
}
setRuleDistance(distance) {
return distance / 1000 + '公里';
}
// 检查对象中是否含有某key
isContainKey(arr, key) {
let len = arr.length;
if (len == 1) {
if (key in arr[0]) {
return true;
}
return false;
} else {
for (let i = 0; i < len; i++) {
if (key in arr[i]) {
return true;
} else {
return false;
}
}
}
}
}
export {
Base
};<file_sep>/pages/index/index.js
//index.js #F54336
import { Home } from 'index-model';
let HomeData = new Home();
Page({
data: {
currentLon: 113.266811,
currentLat: 35.189522,
positonIcon: 35,
locationIcon: 40,
mapScale: 16,
iconAlpha: .8,
positionIconPath: '../../image/icon/position.png',
searchIconPath: '../../image/icon/search.png',
locationIconPath: '../../image/icon/location.png',
isClickMarker: false,
// 是否显示map组件
showIndexMap: false,
showList: true,
sortId: 1,
listHeight: 500, //500是伸开的高度 80是折叠的高度
maxlistHeight: 500,
minlistHeight: 100
},
onLoad: function (options) {
this._onLoad();
},
_onLoad: function () {
// 加载控件
this._controls();
this._mapSort();
this._loadLocation();
},
_mapSort: function () {
HomeData.getSortList(res => {
this.setData({
'SortList': res
})
})
},
setListHeight: function (listheight) {
return this.data.windowHeight * (750 / this.data.screenWidth) - 70 - listheight;
},
// 地图相关控件
_controls: function () {
var that = this;
wx.getSystemInfo({
success: function (res) {
that.data.windowHeight = res.windowHeight;
that.data.windowWidth = res.windowWidth;
that.data.screenWidth = res.screenWidth;
that.data.control_space = (that.data.listHeight / 2) + 25;
that.setControls(that.data.windowWidth, that.data.windowHeight, that.data.control_space, that.setListHeight(that.data.listHeight));
},
})
},
// 设置地图控件
setControls: function (width, height, control_space, viewHeight) {
this.setData({
controls: [{
id: 1,
iconPath: this.data.positionIconPath,
position: {
left: width - 60,
top: height - 90 - control_space,
width: this.data.locationIcon,
height: this.data.locationIcon
},
clickable: true
}, {
id: 2,
iconPath: this.data.searchIconPath,
position: {
left: width - 60,
top: height - 140 - control_space,
width: this.data.locationIcon,
height: this.data.locationIcon
},
clickable: true
}],
showIndexMap: true,
second_height: viewHeight
})
},
// 加载首页点位、分类数据
_loadLocation: function (id = 1) {
HomeData.showLoading()
this._loadLocationList(id);
HomeData.getLocationListById(id, (res) => {
this.data.LocationListArr = [];
this.setData({
locationArr: res.map((item, index) => {
let point =
{
iconPath: this.data.locationIconPath,
id: item.items[0].id,
latitude: item.lat,
longitude: item.lon,
width: this.data.locationIcon,
height: this.data.locationIcon,
alpha: this.data.iconAlpha
};
this.setPointsList(this.data.LocationListArr, item, index);
return point;
}),
loadingHidden: true
});
this.includePoints();
});
},
_loadLocationList: function (id = 1) {
HomeData.getPointListById(id, (res) => {
this.data.LocationList = res;
this.setData({
'listArr': res
})
wx.hideLoading();
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.mapCtx = wx.createMapContext('map-container');
},
// 移动到定位点
moveToLocation: function () {
this.mapCtx.moveToLocation();
this.setData({
'mapScale': this.data.mapScale
})
},
// 跳转到搜索页
onControlSearch() {
wx.navigateTo({
url: '../search/search',
})
},
/**
* 控件点击事件
* 1:移动到当前定位的点
* 2:跳转到搜索页
*/
onControlsTap(event) {
if (event.controlId == 1) {
this.moveToLocation();
} else if (event.controlId == 2) {
this.onControlSearch();
}
},
// 跳转到地点详情页
onMarkerDetail(event) {
let id = HomeData.getDataSet(event, 'listid');
wx.navigateTo({
url: '../detail/detail?id=' + id
})
},
// 点击标记点移动到对应的列
onMarkerTap(event) {
let markerId = event.markerId,
order = this.data.LocationList;
for (var i = 0; i < order.length; ++i) {
if (order[i].id == markerId) {
this.setData({
toView: order[i].id
})
break
}
}
},
// 点击地图随机处关闭弹框
closeList(event) {
if (this.data.isClickMarker) {
this.setData({
'isClickMarker': false
})
}
},
// 设置经纬度数组对象
setPointsList(arr, item, index) {
arr[index] = {};
arr[index].latitude = item.lat;
arr[index].longitude = item.lon;
return arr;
},
onHide: function () {
this.setData({
'showIndexMap': false
})
},
onShow: function () {
this.setData({
'showIndexMap': true,
'isClickMarker': false
})
},
// 点击类别时触发
onSortTap(event) {
let sortId = HomeData.getDataSet(event, 'id'); //指定类别的ID号
this._loadLocation(sortId);
this.setData({
"sortId": sortId
})
},
includePoints: function () {
this.mapCtx.includePoints({
padding: [50],
points: this.data.LocationListArr
})
},
// 点击列表伸缩框,展开/收缩
onCloseList: function () {
if (this.data.listHeight == this.data.maxlistHeight) {
this.setCloseData(this.data.minlistHeight);
} else if (this.data.listHeight == this.data.minlistHeight) {
this.setCloseData(this.data.maxlistHeight);
}
},
// 设置onCloseList函数内的传递值
setCloseData: function (height) {
this.setData({
listHeight: height,
second_height: this.data.windowHeight * (750 / this.data.screenWidth) - 70 - height,
showList: !this.data.showList
})
this.setControls(this.data.windowWidth, this.data.windowHeight, (height / 2) + 25, this.setListHeight(height));
},
startPosition: function (event) {
let coordinateItem = HomeData.getDataSet(event, 'info');
wx.navigateTo({
url: `../path/path?marker_Id=${coordinateItem.id}&lat=${coordinateItem.lat}&lon=${coordinateItem.lon}`,
})
}
})
<file_sep>/pages/bus/detail/detail.js
import {
busDetail
} from 'detail-model';
let BusDetail = new busDetail();
Page({
data: {
},
onLoad: function (options) {
let key = options.key;
this.data.bounds = options.bounds;
this._loadData(key);
},
_loadData: function (cacheName) {
var that = this;
wx.getStorage({
key: cacheName,
success: function (res) {
that.extractData(res.data.result.result.routes);
},
fail: function (err) {
BusDetail.showModal('路径规划失败');
}
});
},
// 根据上一级传递的参数选出需要渲染的数据
extractData: function (data) {
for (let i = 0, len = data.length; i < len; i++) {
let item = data[i];
if (item.bounds === this.data.bounds) {
this.setPathData(item);
break;
}
}
},
// 准备要加载的公交线路数据
setPathData: function (data) {
// console.log(data.steps)
let list = [];
for (let i = 0, len = data.steps.length; i < len; i++) {
let item = data.steps[i];
if (item.mode == 'WALKING') {
if ('steps' in item) {
for (let j = 0, j_len = item.steps.length; j < j_len; j++) {
let items = {
id: i,
mode: item.mode,
distance: item.distance,
instruction: item.steps[j].instruction,
road_name: item.steps[j].road_name,
direction: item.steps[j].dir_desc
};
list.push(items);
}
}
} else {
let items = {
id: i,
mode: item.mode,
distance: item.lines[0].distance,
getOn: item.lines[0].geton.title,
getOff: item.lines[0].getoff.title,
station_count: item.lines[0].station_count
};
list.push(items);
}
}
list.push([]);
// console.log(list);
this.setData({
busPath: list
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
}
})<file_sep>/pages/index/index-model.js
import { Base } from '../../utils/base.js';
class Home extends Base {
constructor() {
super();
}
// 首页位置点,通过分类获取
getLocationListById(id, callback) {
let params = {
url: `/list/${id}`,
sCallback: function (res) {
callback && callback(res);
}
};
this.request(params);
}
getPointListById(id, callback) {
let params = {
url: `/location/list/${id}`,
sCallback: function (res) {
callback && callback(res);
}
};
this.request(params);
}
getSortList(callback) {
let params = {
url: `/sort`,
sCallback: function (res) {
callback && callback(res);
}
};
this.request(params);
}
}
export { Home };
<file_sep>/pages/path/detail/detail.js
import {
pathDetail
} from 'detail-model';
let PathDetail = new pathDetail();
Page({
data: {
key: ''
},
onLoad: function (options) {
let key = options.key;
this._loadData(key);
},
_loadData: function (cacheName) {
var that = this;
wx.getStorage({
key: cacheName,
success: function (res) {
res.data.result.push([]);
that.setData({
pathList: res.data.result
});
},
fail: function (err) {
PathDetail.showModal('路径规划失败');
}
});
},
// 打开App
openApp(){
wx.getLocation({
type: 'gcj02', //返回可以用于wx.openLocation的经纬度
success: function (res) {
var latitude = res.latitude
var longitude = res.longitude
wx.openLocation({
latitude: latitude,
longitude: longitude,
scale: 25
})
}
})
}
}) | 6ac51ff027e8a68c272ab18fec070fca4c4279c7 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | jamesXG/weChat_applets | fcfcda1a533859e7a0d0a5957301bf411d1f56d0 | 68a8236058f4c98d56f02341c0f5e508a66e48fc |
refs/heads/master | <repo_name>akshaaatt/artwork-redirect<file_sep>/docker/push.sh
#!/bin/bash
#
# Build image from the currently checked out version of the CAA redirect service
# and push it to the Docker Hub, with an optional tag (by default "latest").
#
# Usage:
# $ ./push.sh [tag]
cd "$(dirname "${BASH_SOURCE[0]}")/../"
TAG_PART=${1:-latest}
docker build -t metabrainz/artwork-redirect:$TAG_PART .
docker push metabrainz/artwork-redirect:$TAG_PART
<file_sep>/artwork_redirect_server.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# Copyright (C) 2011, 2012 MetaBrainz Foundation
#
# 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.
import os
import sys
from artwork_redirect.server import Server
from artwork_redirect.config import load_config
def development():
from werkzeug import run_simple
config = load_config()
application = Server(config)
addr = config.listen.addr
port = int(config.listen.port)
run_simple(addr, port, application, use_reloader=True,
extra_files=None, reloader_interval=1, threaded=False,
processes=1, request_handler=None)
def print_help():
print("""
syntax: python artwork_redirect_server.py [options]
options:
--help This message
""")
sys.exit(0)
if __name__ == '__main__':
option = None
if len(sys.argv) > 1:
option = sys.argv.pop()
if option == '--help':
print_help()
else:
development()
<file_sep>/README.md
Cover Art Archive URL redirect service
======================================
This service will redirect from `coverartarchive.org` URLs to `archive.org` URLs, taking into account MBID redirects
caused by release merges.
For example, this URL:
https://coverartarchive.org/release/5b07fe49-39a9-47a6-97b3-e5005992fb2a/front.jpg
should redirect to:
https://archive.org/download/mbid-5b07fe49-39a9-47a6-97b3-e5005992fb2a/mbid-5b07fe49-39a9-47a6-97b3-e5005992fb2a-2270157148.jpg
## Development setup
There are two ways of setting up the server: with and without Docker. First option might be easier if you are just
getting started. Second requires having a MusicBrainz database set up on your machine.
### Option 1: Docker-based
Make sure that you have [Docker](https://www.docker.com/) and [Compose](https://github.com/docker/compose) installed.
To start the development server and its dependencies run:
$ docker-compose -f docker/docker-compose.dev.yml up --build
After all Docker images start you should be able to access the web server at `localhost:8080`.
**Note:** Keep in mind that any changes that you make won't show up until the server container is recreated. To do that
you can simply stop the server (Ctrl + C) and run the command above again.
### Option 2: Manual
CAA redirect server works with *Python 3*, so make sure that you have it installed. Create a
[virtual environment](https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments),
if necessary.
Install all required packages using [pip](https://pip.pypa.io):
$ pip install -r requirements.txt
Copy *config.default.ini* to *config.ini* and adjust configuration values. You'd want to set up
a connection to the instance of PostgreSQL with a MusicBrainz database that you should already have running.
Finally, run the *artwork_redirect_server.py* script to start the server.
All logging goes to stdout, including stacktraces, so its suitable for running inside of daemontools.
## Testing
*Currently some tests depend on an actual MusicBrainz database running in the background, so make sure to follow the
setup process first.* We use [Pytest](https://pytest.org) as a test runner. All tests can be run with the following
command:
$ pytest
There are more ways to use Pytest (for example, to run only tests for a specific module). Check their documentation to
see what kinds of additional options you have.
With **Docker** you can run all the tests like this:
$ docker-compose -f docker/docker-compose.test.yml up --build
You should see test results in the output.
<file_sep>/pytest.ini
[pytest]
testpaths = artwork_redirect test
addopts = --cov=artwork_redirect
<file_sep>/docker/prod/redirect.service
#!/bin/bash
exec run-consul-template -config /etc/consul-template-redirect.conf
<file_sep>/requirements.txt
coverage==5.3
pytest==6.1.2
pytest-cov==2.10.1
psycopg2==2.8.6
raven==6.10.0
requests==2.20.0
sqlalchemy==1.3.0
werkzeug==0.15.3
uWSGI==2.0.15
<file_sep>/config.default.ini
[database]
user=musicbrainz
name=musicbrainz_test
host=mbs_db_test
port=5432
[testdatabase]
user=musicbrainz
name=musicbrainz_test
host=mbs_db_test
port=5432
[listen]
address=0.0.0.0
port=8081
[sentry]
dsn=
[s3]
prefix=//archive.org/download
<file_sep>/Dockerfile
FROM metabrainz/python:3.8-20201201
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
git \
libpq-dev \
libffi-dev \
libssl-dev \
sudo \
&& rm -rf /var/lib/apt/lists/*
RUN useradd --create-home --shell /bin/bash art
WORKDIR /home/art/artwork-redirect
RUN chown art:art /home/art/artwork-redirect
# Python dependencies
RUN sudo -E -H -u art pip install --user -U cffi
COPY requirements.txt ./
RUN sudo -E -H -u art pip install --user -r requirements.txt
# Node dependencies
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
COPY package.json package-lock.json ./
RUN sudo -E -H -u art npm install
COPY . ./
RUN sudo -E -H -u art ./node_modules/.bin/lessc \
static/css/main.less > static/css/main.css
RUN chown -R art:art ./
############
# Services #
############
COPY ./docker/prod/redirect.service /etc/service/redirect/run
COPY ./docker/prod/uwsgi.ini /etc/uwsgi/
RUN chmod 755 /etc/service/redirect/run
# Configuration
COPY ./docker/prod/consul-template-redirect.conf /etc/
EXPOSE 8080
<file_sep>/compile_resources.sh
#!/bin/sh
cd "$(dirname $0)"
node_modules/.bin/lessc --clean-css ./static/css/main.less > ./static/css/main.css
<file_sep>/docker/prod/uwsgi.ini
[uwsgi]
master = true
http = 0.0.0.0:8080
module = artwork_redirect.wsgi
callable = application
chdir = /home/art/artwork-redirect/
enable-threads = true
processes = 10
die-on-term = true
worker-reload-mercy = 10
reload-mercy = 25
<file_sep>/artwork_redirect/wsgi.py
# Copyright (C) 2017 MetaBrainz Foundation
# Distributed under the MIT license, see the LICENSE file for details.
# Simple WSGI module intended to be used by uWSGI.
from artwork_redirect.server import Server
from artwork_redirect.config import load_config
from artwork_redirect.loggers import init_raven_client
config = load_config()
sentry_dsn = config.sentry.dsn
if sentry_dsn:
init_raven_client(sentry_dsn)
application = Server(config)
| fa1e5c917cbe4354fc3645df3299568793b93b22 | [
"Markdown",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 11 | Shell | akshaaatt/artwork-redirect | 90ff5c7b57df4c37a6c03fd01dd9f04e76ed5bb8 | 7a64ec5a2c6f4040b4bcb254ea953d403745dae2 |
refs/heads/master | <repo_name>alex4321/deadbeef-azlyrics<file_sep>/deadbeef-azlyrics.sh
#!/bin/bash
ARTIST=$1
TITLE=$2
ALBUM=$3
ARTIST_CONVERTED=`echo $ARTIST | sed 's/[_ ()]//g' | awk '{print tolower($0)}'`
TITLE_CONVERTED=`echo $TITLE | sed 's/[_ ()]//g' | awk '{print tolower($0)}'`
ALBUM_CONVERTED=`echo $ALBUM | sed 's/[_ ()]//g' | awk '{print tolower($0)}'`
URL="http://www.azlyrics.com/lyrics/$ARTIST_CONVERTED/$TITLE_CONVERTED.html"
USER_AGENT="User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1535.3 Safari/537.36"
ANSWER=`curl -s $URL -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Host: www.azlyrics.com' -H "$USER_AGENT"`
if [ "$?" -ne "0" ]
then
exit 1
fi
ANSWER_SEDABLE=`echo $ANSWER | tr -s '\r\n' ' '`
SUBTEXT=`echo "$ANSWER_SEDABLE" | sed "s/^.*<!-- Usage of azlyrics.com content by any third-party lyrics provider is prohibited by our licensing agreement. Sorry about that. -->//"`
TEXT_HTML=`echo "$SUBTEXT" | sed "s/<br><br> <form id=\"addsong\".*$//" | sed "s/<\/div>//"`
echo "$TEXT_HTML" | w3m -dump -T text/html
| ea6cd3f9524d01d1d3e43acb3c41bcf8444e9135 | [
"Shell"
] | 1 | Shell | alex4321/deadbeef-azlyrics | fcae9b14630a9682d90e3d9e522c69fc87d9d0d8 | 59c5f3ae381c43237e7bf65b5d6be9cd71df45be |
refs/heads/master | <repo_name>hugolardosa/DVD_DB<file_sep>/src/App/MovieTableModel.java
package App;
import DataSet.Movie;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.util.List;
public class MovieTableModel extends AbstractTableModel {
private final List<Movie> movies;
private final String[] columnNames = new String[]{
"Title", "Original Title", "Ordering Title", "Seen", "Original DVD", "Production Year", "Running Time", "Genre", "Cover"
};
private final Class[] columnClass = new Class[]{
String.class,String.class,String.class, Boolean.class,Boolean.class, Integer.class, Integer.class, String.class, String.class
};
public MovieTableModel(List<Movie> m) {
this.movies = m;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return movies.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Movie row = movies.get(rowIndex);
if (0 == columnIndex) {
return row.getTitle();
} else if (1 == columnIndex) {
return row.getOgtitle();
} else if (2 == columnIndex) {
return row.getOrdertitle();
} else if (3 == columnIndex) {
return row.isSeen();
}else if (4 == columnIndex) {
return row.isOriginalDVD();
}else if (5 == columnIndex) {
return row.getYear();
}else if (6 == columnIndex) {
return row.getTime();
}else if (7 == columnIndex) {
return row.getGenere();
}else if (8 == columnIndex) {
return row.getCoverpath();
}
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Movie row = movies.get(rowIndex);
if (0 == columnIndex) {
row.setTitle((String) aValue);
} else if (1 == columnIndex) {
row.setOgtitle((String) aValue);
} else if (2 == columnIndex) {
row.setOrdertitle((String) aValue);
} else if (3 == columnIndex) {
row.setSeen((Boolean) aValue);
}else if (4 == columnIndex) {
row.setOriginalDVD((Boolean) aValue);
}else if (5 == columnIndex) {
row.setYear((Integer) aValue);
}else if (6 == columnIndex) {
row.setTime((Integer) aValue);
}else if (7 == columnIndex) {
row.setGenere((String) aValue);
}else if (8 == columnIndex) {
row.setCoverpath((String) aValue);
}
}
}
<file_sep>/src/App/MovieTableCreator.java
package App;
import DataSet.Movie;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.List;
public class MovieTableCreator extends JFrame
{
public MovieTableCreator(List<Movie> movies)
{
//create the model
MovieTableModel model = new MovieTableModel(movies);
//create the table
JTable table = new JTable(model);
//add the table to the frame
this.add(new JScrollPane(table));
this.setTitle("Movie Editor");
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
<file_sep>/index.html
<!DOCTYPE html>
<html>
<head>
<title> DVD DB</title>
<style>
#movies {
border-collapse: collapse;
width: 100%;
}
#movies td, #movies th {
border: 1px solid #ddd;
padding: 8px;
}
#movies tr:nth-child(even){background-color: #f2f2f2;}
#movies tr:hover {background-color: #ddd;}
#movies th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color:white;
}
</style>
</head>
<body>
<h2>Movie Database</h2>
<table id= "movies">
<tr>
<th>Title</th>
<th> Original Title </th>
<th> Ordering Title </th>
<th> Seen </th>
<th> Original DVD </th>
<th> Production Year </th>
<th> Running Time </th>
<th> Genre </th>
<th> Cover </th>
</tr >
<tr>
<td>"O Resgate dos ""Soldados Fantasma"""</td>
<td>The Great Raid</td>
<td>"O Resgate dos ""Soldados Fantasma"""</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>132</td>
<td>Acção</td>
<td><img src=Images\5600304168656.15F.jpg alt=""o resgate dos ""soldados fantasma"""" height=110 width=95></td>
</tr>
<tr>
<td>007 Contra Goldfinger</td>
<td>Goldfinger</td>
<td>007 Contra Goldfinger</td>
<td>X</td>
<td>X</td>
<td>1964</td>
<td>110</td>
<td>Acção</td>
<td><img src=Images\IFB1D734B8918010C.15F.jpg alt="007 contra goldfinger" height=110 width=95></td>
</tr>
<tr>
<td>007 Risco Imediato</td>
<td>The Living Daylights</td>
<td>007 Risco Imediato</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>125</td>
<td>Acção</td>
<td><img src=Images\I85011E9AB638EC9E.15F.jpg alt="007 risco imediato" height=110 width=95></td>
</tr>
<tr>
<td>15 Minutos</td>
<td>15 Minutes</td>
<td>15 Minutos</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>116</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887429653.15F.jpg alt="15 minutos" height=110 width=95></td>
</tr>
<tr>
<td>2012</td>
<td>0</td>
<td>2012</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>151</td>
<td>Ficção Científica</td>
<td><img src=Images\8414533066310.15F.jpg alt="2012" height=110 width=95></td>
</tr>
<tr>
<td>21 Gramas</td>
<td>21 Grams</td>
<td>21 Gramas</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5608652023399.15F.jpg alt="21 gramas" height=110 width=95></td>
</tr>
<tr>
<td>24 Horas para Matar</td>
<td>The Watcher</td>
<td>24 Horas para Matar</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>97</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887428267.15F.jpg alt="24 horas para matar" height=110 width=95></td>
</tr>
<tr>
<td>8MM</td>
<td>0</td>
<td>8MM</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>119</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887404667.15F.jpg alt="8mm" height=110 width=95></td>
</tr>
<tr>
<td>A Armadilha</td>
<td>Entrapment</td>
<td>A Armadilha</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>108</td>
<td>Acção</td>
<td><img src=Images\5600304163491.15F.jpg alt="a armadilha" height=110 width=95></td>
</tr>
<tr>
<td>À beira do casamento</td>
<td>The Groomsmen</td>
<td>A beira do casamento</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\5601887493906.15F.jpg alt="a beira do casamento" height=110 width=95></td>
</tr>
<tr>
<td>A Bela Adormecida</td>
<td>Sleeping Beauty</td>
<td>A Bela Adormecida</td>
<td>X</td>
<td>X</td>
<td>1959</td>
<td>72</td>
<td>0</td>
<td><img src=Images\5601887430147.15F.jpg alt="a bela adormecida" height=110 width=95></td>
</tr>
<tr>
<td>A Bela e o Monstro</td>
<td>Beauty and the Beast</td>
<td>A Bela e o Monstro</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>87</td>
<td>0</td>
<td><img src=Images\5601887437238.15F.jpg alt="a bela e o monstro" height=110 width=95></td>
</tr>
<tr>
<td>A Borboleta Azul</td>
<td>The Blue Butterfly</td>
<td>A Borboleta Azul</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5608652022620.15F.jpg alt="a borboleta azul" height=110 width=95></td>
</tr>
<tr>
<td>A Canção de Lisboa</td>
<td>0</td>
<td>A Cancao de Lisboa</td>
<td>X</td>
<td>X</td>
<td>1933</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5601684043212.15F.jpg alt="a cancao de lisboa" height=110 width=95></td>
</tr>
<tr>
<td>A Casa da Felicidade</td>
<td>The House of Mirth</td>
<td>A Casa da Felicidade</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>134</td>
<td>Drama</td>
<td><img src=Images\5608652008600.15F.jpg alt="a casa da felicidade" height=110 width=95></td>
</tr>
<tr>
<td>A Casa da Lagoa</td>
<td>The Lake House</td>
<td>A Casa da Lagoa</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>115</td>
<td>Fantasia</td>
<td><img src=Images\7321976736728.15F.jpg alt="a casa da lagoa" height=110 width=95></td>
</tr>
<tr>
<td>A Casa da Russia</td>
<td>The Russia House</td>
<td>A Casa da Russia</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5608652039321.15F.jpg alt="a casa da russia" height=110 width=95></td>
</tr>
<tr>
<td>A Casa dos Espíritos</td>
<td>The House of the Spirits</td>
<td>A Casa dos Espiritos</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>146</td>
<td>Drama</td>
<td><img src=Images\5608652016940.15F.jpg alt="a casa dos espiritos" height=110 width=95></td>
</tr>
<tr>
<td>A Cela</td>
<td>The Cell</td>
<td>A Cela</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>105</td>
<td>0</td>
<td><img src=Images\5602193305556.15F.jpg alt="a cela" height=110 width=95></td>
</tr>
<tr>
<td>A Chave</td>
<td>The Skeleton Key</td>
<td>A Chave</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>99</td>
<td>0</td>
<td><img src=Images\5050582384826.15F.jpg alt="a chave" height=110 width=95></td>
</tr>
<tr>
<td>A Cidade do Passado</td>
<td>City by the Sea</td>
<td>A Cidade do Passado</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>109</td>
<td>0</td>
<td><img src=Images\5601887450077.15F.jpg alt="a cidade do passado" height=110 width=95></td>
</tr>
<tr>
<td>A Cidade dos Anjos</td>
<td>City of Angels</td>
<td>A Cidade dos Anjos</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>110</td>
<td>0</td>
<td><img src=Images\5606376506181.15F.jpg alt="a cidade dos anjos" height=110 width=95></td>
</tr>
<tr>
<td>A Conspiração da Aranha</td>
<td>Along Came a Spider</td>
<td>A Conspiracao da Aranha</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887427437.15F.jpg alt="a conspiracao da aranha" height=110 width=95></td>
</tr>
<tr>
<td>A Dama de Ferro</td>
<td>0</td>
<td>A Dama de Ferro</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>104</td>
<td>Drama</td>
<td><img src=Images\5602193358385.15F.jpg alt="a dama de ferro" height=110 width=95></td>
</tr>
<tr>
<td>A Dama e o Vagabundo</td>
<td>Lady and the Tramp</td>
<td>A Dama e o Vagabundo</td>
<td>X</td>
<td></td>
<td>1955</td>
<td>74</td>
<td>Animação</td>
<td><img src=Images\5601887480302.15F.jpg alt="a dama e o vagabundo" height=110 width=95></td>
</tr>
<tr>
<td>A Dama e o Vagabundo II: As Aventuras de Banzé</td>
<td>Lady and the Tramp II: Scamp's Adventure</td>
<td>A Dama e o Vagabundo II: As Aventuras de Banze</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>66</td>
<td>Animação</td>
<td><img src=Images\5601887417117.15F.jpg alt="a dama e o vagabundo ii: as aventuras de banze" height=110 width=95></td>
</tr>
<tr>
<td>A Desaparecida</td>
<td>The Vanishing</td>
<td>A Desaparecida</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>105</td>
<td>Drama</td>
<td><img src=Images\5600304166164.15F.jpg alt="a desaparecida" height=110 width=95></td>
</tr>
<tr>
<td>A Domadora de Baleias</td>
<td>Whale Rider</td>
<td>A Domadora de Baleias</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5606118002100.15F.jpg alt="a domadora de baleias" height=110 width=95></td>
</tr>
<tr>
<td>A duquesa</td>
<td>The Duchess</td>
<td>A duquesa</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>110</td>
<td>Drama</td>
<td><img src=Images\5601887535842.15F.jpg alt="a duquesa" height=110 width=95></td>
</tr>
<tr>
<td>À Dúzia é Mais Barato</td>
<td>Cheaper by the Dozen</td>
<td>A Duzia e Mais Barato</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>95</td>
<td>Comédia</td>
<td><img src=Images\5608652022057.15F.jpg alt="a duzia e mais barato" height=110 width=95></td>
</tr>
<tr>
<td>A Educação de Charlie Banks</td>
<td>0</td>
<td>A Educacao de Charlie Banks</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>101</td>
<td>Drama</td>
<td><img src=Images\013131580990F.jpg alt="a educacao de charlie banks" height=110 width=95></td>
</tr>
<tr>
<td>A Espada Era a Lei</td>
<td>The Sword in the Stone</td>
<td>A Espada Era a Lei</td>
<td>X</td>
<td>X</td>
<td>1963</td>
<td>76</td>
<td>0</td>
<td><img src=Images\5601887435272.15F.jpg alt="a espada era a lei" height=110 width=95></td>
</tr>
<tr>
<td>À Espera de um Milagre</td>
<td>The Green Mile</td>
<td>A Espera de um Milagre</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>181</td>
<td>0</td>
<td><img src=Images\5601887409877.15F.jpg alt="a espera de um milagre" height=110 width=95></td>
</tr>
<tr>
<td>A Estação</td>
<td>The Station Agent</td>
<td>A Estacao</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>86</td>
<td>0</td>
<td><img src=Images\5608652023436.15F.jpg alt="a estacao" height=110 width=95></td>
</tr>
<tr>
<td>A Estranha em Mim</td>
<td>The Brave One</td>
<td>A Estranha em Mim</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>119</td>
<td>Acção</td>
<td><img src=Images\5600304192583.15F.jpg alt="a estranha em mim" height=110 width=95></td>
</tr>
<tr>
<td>A Face Oculta de MR. Brooks</td>
<td>Mr. Brooks</td>
<td>A Face Oculta de MR. Brooks</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>115</td>
<td>0</td>
<td><img src=Images\5602193339360.15F.jpg alt="a face oculta de mr. brooks" height=110 width=95></td>
</tr>
<tr>
<td>A Feira das Vaidades</td>
<td>Vanity Fair</td>
<td>A Feira das Vaidades</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>139</td>
<td>Comédia</td>
<td><img src=Images\5608652026789.15F.jpg alt="a feira das vaidades" height=110 width=95></td>
</tr>
<tr>
<td>A Festa</td>
<td>The Party</td>
<td>A Festa</td>
<td>X</td>
<td>X</td>
<td>1968</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5608652018388.15F.jpg alt="a festa" height=110 width=95></td>
</tr>
<tr>
<td>A Filha do Patrão</td>
<td>0</td>
<td>A Filha do Patrao</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>82</td>
<td>Comédia</td>
<td><img src=Images\5608652024280.15F.jpg alt="a filha do patrao" height=110 width=95></td>
</tr>
<tr>
<td>A Firma</td>
<td>The Firm</td>
<td>A Firma</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>148</td>
<td>Drama</td>
<td><img src=Images\5601887413935.15F.jpg alt="a firma" height=110 width=95></td>
</tr>
<tr>
<td>A Flor do Mal</td>
<td>White Oleander</td>
<td>A Flor do Mal</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>109</td>
<td>0</td>
<td><img src=Images\5050582222906.15F.jpg alt="a flor do mal" height=110 width=95></td>
</tr>
<tr>
<td>A Fuga das Galinhas</td>
<td>Chicken Run</td>
<td>A Fuga das Galinhas</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>81</td>
<td>Animação</td>
<td><img src=Images\0667068827323.15F.jpg alt="a fuga das galinhas" height=110 width=95></td>
</tr>
<tr>
<td>A Fúria Do Último Escuteiro</td>
<td>The Last Boy Scout</td>
<td>A Furia Do Ultimo Escuteiro</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5606376267518.15F.jpg alt="a furia do ultimo escuteiro" height=110 width=95></td>
</tr>
<tr>
<td>A Glória dos Campeões</td>
<td>Blades of Glory</td>
<td>A Gloria dos Campeoes</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\5601887497058.15F.jpg alt="a gloria dos campeoes" height=110 width=95></td>
</tr>
<tr>
<td>A Grande Aventura dos Gnomos</td>
<td>The Gnomes Great Adventure</td>
<td>A Grande Aventura dos Gnomos</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>75</td>
<td>0</td>
<td><img src=Images\5608652016667.15F.jpg alt="a grande aventura dos gnomos" height=110 width=95></td>
</tr>
<tr>
<td>A Guerra a Cores: A Segunda Guerra Mundial: Hitler</td>
<td>0</td>
<td>A Guerra a Cores: A Segunda Guerra Mundial: Hitler</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>71</td>
<td>0</td>
<td><img src=Images\5604779059280.15F.jpg alt="a guerra a cores: a segunda guerra mundial: hitler" height=110 width=95></td>
</tr>
<tr>
<td>A Guerra das Rosas</td>
<td>The War of the Roses</td>
<td>A Guerra das Rosas</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>116</td>
<td>Comédia</td>
<td><img src=Images\5600304166225.15F.jpg alt="a guerra das rosas" height=110 width=95></td>
</tr>
<tr>
<td>A Herança que veio do Frio</td>
<td>Kevin of the North</td>
<td>A Heranca que veio do Frio</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5608652008952.15F.jpg alt="a heranca que veio do frio" height=110 width=95></td>
</tr>
<tr>
<td>A História de uma Abelha</td>
<td>Bee Movie</td>
<td>A Historia de uma Abelha</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>0</td>
<td><img src=Images\5601887521494.15F.jpg alt="a historia de uma abelha" height=110 width=95></td>
</tr>
<tr>
<td>A Idade das Sombras</td>
<td>The Age of Shadows</td>
<td>A Idade das Sombras</td>
<td>X</td>
<td>X</td>
<td>2016</td>
<td>140</td>
<td>Acção</td>
<td><img src=Images\5600351704258.15F.jpg alt="a idade das sombras" height=110 width=95></td>
</tr>
<tr>
<td>A Idade do Gelo</td>
<td>Ice Age</td>
<td>A Idade do Gelo</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>78</td>
<td>Animação</td>
<td><img src=Images\5600304162470.15F.jpg alt="a idade do gelo" height=110 width=95></td>
</tr>
<tr>
<td>A Idade do Gelo 2 - Descongelados</td>
<td>Ice Age: The Meltdown</td>
<td>A Idade do Gelo 2 - Descongelados</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>87</td>
<td>Animação</td>
<td><img src=Images\5600304169936.15F.jpg alt="a idade do gelo 2 - descongelados" height=110 width=95></td>
</tr>
<tr>
<td>A Idade do Gelo 3 - Despertar dos dinossauros</td>
<td>Ice Age 3: Dawn of the Dinosaurs</td>
<td>A Idade do Gelo 3 - Despertar dos dinossauros</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>90</td>
<td>Animação</td>
<td><img src=Images\5600304210386.15F.jpg alt="a idade do gelo 3 - despertar dos dinossauros" height=110 width=95></td>
</tr>
<tr>
<td>A idade do gelo 4: Deriva continental</td>
<td>Ice Age 4: Continental Drift</td>
<td>A idade do gelo 4: Deriva continental</td>
<td>X</td>
<td></td>
<td>2012</td>
<td>88</td>
<td>Animação</td>
<td><img src=Images\5602193504652.15F.jpg alt="a idade do gelo 4: deriva continental" height=110 width=95></td>
</tr>
<tr>
<td>A Ilha</td>
<td>The Island</td>
<td>A Ilha</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>130</td>
<td>Acção</td>
<td><img src=Images\7321976717307.15F.jpg alt="a ilha" height=110 width=95></td>
</tr>
<tr>
<td>A Ilha do Tesouro</td>
<td>0</td>
<td>A Ilha do Tesouro</td>
<td>X</td>
<td>X</td>
<td>1950</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5601887447695.15F.jpg alt="a ilha do tesouro" height=110 width=95></td>
</tr>
<tr>
<td>A Importância de ser Ernesto</td>
<td>The Importance of Being Earnest</td>
<td>A Importancia de ser Ernesto</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\5608652016568.15F.jpg alt="a importancia de ser ernesto" height=110 width=95></td>
</tr>
<tr>
<td>A Intérprete</td>
<td>The Interpreter</td>
<td>A Interprete</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>123</td>
<td>Drama</td>
<td><img src=Images\5050582346718.15F.jpg alt="a interprete" height=110 width=95></td>
</tr>
<tr>
<td>A Invasão</td>
<td>The Invasion</td>
<td>A Invasao</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>95</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304192705.15F.jpg alt="a invasao" height=110 width=95></td>
</tr>
<tr>
<td>A Janela Secreta</td>
<td>Secret Window</td>
<td>A Janela Secreta</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>92</td>
<td>Drama</td>
<td><img src=Images\8414533025966.15F.jpg alt="a janela secreta" height=110 width=95></td>
</tr>
<tr>
<td>A Jóia do Nilo</td>
<td>The Jewel of the Nile</td>
<td>A Joia do Nilo</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>101</td>
<td>Acção</td>
<td><img src=Images\5600304162869.15F.jpg alt="a joia do nilo" height=110 width=95></td>
</tr>
<tr>
<td>A Lenda de Bagger Vance</td>
<td>The Legend of Bagger Vance</td>
<td>A Lenda de Bagger Vance</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>125</td>
<td>0</td>
<td><img src=Images\5601887434435.15F.jpg alt="a lenda de bagger vance" height=110 width=95></td>
</tr>
<tr>
<td>A Lenda de Despereaux</td>
<td>Tale of Despereaux</td>
<td>A Lenda de Despereaux</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>90</td>
<td>Animação</td>
<td><img src=Images\5050582706697.2F.jpg alt="a lenda de despereaux" height=110 width=95></td>
</tr>
<tr>
<td>A Lenda Do Rei David</td>
<td>0</td>
<td>A Lenda Do Rei David</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M4.15F.jpg alt="a lenda do rei david" height=110 width=95></td>
</tr>
<tr>
<td>A Máquina do Tempo</td>
<td>The Time Machine</td>
<td>A Maquina do Tempo</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\7321977221919.15F.jpg alt="a maquina do tempo" height=110 width=95></td>
</tr>
<tr>
<td>A Máscara</td>
<td>The Mask</td>
<td>A Mascara</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\IB2D1989D81922B77.15F.jpg alt="a mascara" height=110 width=95></td>
</tr>
<tr>
<td>A Menina da Rádio</td>
<td>0</td>
<td>A Menina da Radio</td>
<td>X</td>
<td>X</td>
<td>1944</td>
<td>107</td>
<td>0</td>
<td><img src=Images\5606699505489.15F.jpg alt="a menina da radio" height=110 width=95></td>
</tr>
<tr>
<td>A Minha Vida em Ruínas</td>
<td>My Life in Ruins</td>
<td>A Minha Vida em Ruinas</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5606320009263.15F.jpg alt="a minha vida em ruinas" height=110 width=95></td>
</tr>
<tr>
<td>A Missão</td>
<td>The Mission</td>
<td>A Missao</td>
<td>X</td>
<td>X</td>
<td>1986</td>
<td>120</td>
<td>Aventura</td>
<td><img src=Images\5601887458608.15F.jpg alt="a missao" height=110 width=95></td>
</tr>
<tr>
<td>A Mosca</td>
<td>The Fly</td>
<td>A Mosca</td>
<td>X</td>
<td>X</td>
<td>1986</td>
<td>94</td>
<td>Horror</td>
<td><img src=Images\5600304162784.15F.jpg alt="a mosca" height=110 width=95></td>
</tr>
<tr>
<td>A Mulher da Casa</td>
<td>Bringing Down the House</td>
<td>A Mulher da Casa</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5601887456871.15F.jpg alt="a mulher da casa" height=110 width=95></td>
</tr>
<tr>
<td>A Mulher do Astronauta</td>
<td>The Austronaut's Wife</td>
<td>A Mulher do Astronauta</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>104</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887426423.15F.jpg alt="a mulher do astronauta" height=110 width=95></td>
</tr>
<tr>
<td>A Múmia</td>
<td>The Mummy</td>
<td>A Mumia</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>120</td>
<td>0</td>
<td><img src=Images\5050582008951.15F.jpg alt="a mumia" height=110 width=95></td>
</tr>
<tr>
<td>A Múmia: O Túmulo do Imperador Dragão</td>
<td>The Mummy: Tomb of the Dragon Emperor</td>
<td>A Mumia: O Tumulo do Imperador Dragao</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>107</td>
<td>Acção</td>
<td><img src=Images\5050582593280.15F.jpg alt="a mumia: o tumulo do imperador dragao" height=110 width=95></td>
</tr>
<tr>
<td>A Musa</td>
<td>The Muse</td>
<td>A Musa</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5608652003155.15F.jpg alt="a musa" height=110 width=95></td>
</tr>
<tr>
<td>A Namorada do meu melhor amigo</td>
<td>My Best Friend's Girl</td>
<td>A Namorada do meu melhor amigo</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>112</td>
<td>Comédia</td>
<td><img src=Images\5608652035323.15F.jpg alt="a namorada do meu melhor amigo" height=110 width=95></td>
</tr>
<tr>
<td>À Noite, no Museu</td>
<td>Night at the Museum</td>
<td>A Noite, no Museu</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>108</td>
<td>Acção</td>
<td><img src=Images\5600304174572.15F.jpg alt="a noite, no museu" height=110 width=95></td>
</tr>
<tr>
<td>À Noite, no Museu 2</td>
<td>Night at the Museum: Battle of the Smithsonian</td>
<td>A Noite, no Museu 2</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5600304210041.15F.jpg alt="a noite, no museu 2" height=110 width=95></td>
</tr>
<tr>
<td>A Noiva Cadáver</td>
<td>Corpse Bride</td>
<td>A Noiva Cadaver</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>74</td>
<td>Animação</td>
<td><img src=Images\7321976593512.15F.jpg alt="a noiva cadaver" height=110 width=95></td>
</tr>
<tr>
<td>A Nona Porta</td>
<td>The Ninth Gate</td>
<td>A Nona Porta</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>128</td>
<td>Horror</td>
<td><img src=Images\5601887426508.15F.jpg alt="a nona porta" height=110 width=95></td>
</tr>
<tr>
<td>A organização</td>
<td>The Crew</td>
<td>A organizacao</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>118</td>
<td>Acção</td>
<td><img src=Images\5608652035897.15F.jpg alt="a organizacao" height=110 width=95></td>
</tr>
<tr>
<td>A Outra Face</td>
<td>Face/Off</td>
<td>A Outra Face</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>133</td>
<td>Acção</td>
<td><img src=Images\5601887419425.15F.jpg alt="a outra face" height=110 width=95></td>
</tr>
<tr>
<td>A Ovelha Choné: Futebaa!</td>
<td>Shaun the Sheep: Off the Baa</td>
<td>A Ovelha Chone: Futebaa!</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>56</td>
<td>Animação</td>
<td><img src=Images\5608652033381.15F.jpg alt="a ovelha chone: futebaa!" height=110 width=95></td>
</tr>
<tr>
<td>A Paixão de Cristo</td>
<td>The Passion of the Christ</td>
<td>A Paixao de Cristo</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>121</td>
<td>Drama</td>
<td><img src=Images\5601887462353.15F.jpg alt="a paixao de cristo" height=110 width=95></td>
</tr>
<tr>
<td>A Paixão de Shakespeare</td>
<td>Shakespeare In Love</td>
<td>A Paixao de Shakespeare</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>119</td>
<td>0</td>
<td><img src=Images\5601887404131.15F.jpg alt="a paixao de shakespeare" height=110 width=95></td>
</tr>
<tr>
<td>A Porta no Chão</td>
<td>The Door in the Floor</td>
<td>A Porta no Chao</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>106</td>
<td>0</td>
<td><img src=Images\5602193322768.15F.jpg alt="a porta no chao" height=110 width=95></td>
</tr>
<tr>
<td>A Pousada da Jamaica</td>
<td>Jamaica Inn</td>
<td>A Pousada da Jamaica</td>
<td>X</td>
<td>X</td>
<td>1939</td>
<td>98</td>
<td>Suspense/Thriller</td>
<td><img src=Images\IFB8362F58BC2FEFE.15F.jpg alt="a pousada da jamaica" height=110 width=95></td>
</tr>
<tr>
<td>A Praia</td>
<td>The Beach</td>
<td>A Praia</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\5600304163293.15F.jpg alt="a praia" height=110 width=95></td>
</tr>
<tr>
<td>À Procura da Terra do Nunca</td>
<td>Finding Neverland</td>
<td>A Procura da Terra do Nunca</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>97</td>
<td>Drama</td>
<td><img src=Images\5600304161817.15F.jpg alt="a procura da terra do nunca" height=110 width=95></td>
</tr>
<tr>
<td>À Procura de Nemo</td>
<td>Finding Nemo</td>
<td>A Procura de Nemo</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>97</td>
<td>0</td>
<td><img src=Images\5601887463923.15F.jpg alt="a procura de nemo" height=110 width=95></td>
</tr>
<tr>
<td>A Profecia das Sombras</td>
<td>The Mothman Prophecies</td>
<td>A Profecia das Sombras</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>114</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887440948.15F.jpg alt="a profecia das sombras" height=110 width=95></td>
</tr>
<tr>
<td>A Proposta</td>
<td>The Proposition</td>
<td>A Proposta</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>107</td>
<td>Drama</td>
<td><img src=Images\5601887432967.15F.jpg alt="a proposta" height=110 width=95></td>
</tr>
<tr>
<td>À Prova de Bala</td>
<td>Bulletproof Monk</td>
<td>A Prova de Bala</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\5602193317702.15F.jpg alt="a prova de bala" height=110 width=95></td>
</tr>
<tr>
<td>À Prova de Morte</td>
<td>Death Proof</td>
<td>A Prova de Morte</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>109</td>
<td>Acção</td>
<td><img src=Images\5602193339346.15F.jpg alt="a prova de morte" height=110 width=95></td>
</tr>
<tr>
<td>A Qualquer Preço</td>
<td>A Civil Action</td>
<td>A Qualquer Preco</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\7896012250136.23F.jpg alt="a qualquer preco" height=110 width=95></td>
</tr>
<tr>
<td>A Queda - Hitler e o Fim do Terceiro Reich</td>
<td><NAME></td>
<td>A Queda - Hitler e o Fim do Terceiro Reich</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>149</td>
<td>Drama</td>
<td><img src=Images\5608652026864.15F.jpg alt="a queda - hitler e o fim do terceiro reich" height=110 width=95></td>
</tr>
<tr>
<td>A Rainha</td>
<td>The Queen</td>
<td>A Rainha</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>98</td>
<td>Drama</td>
<td><img src=Images\5608652030595.15F.jpg alt="a rainha" height=110 width=95></td>
</tr>
<tr>
<td>A Rainha Margot</td>
<td>La Reine Margot</td>
<td>A Rainha Margot</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>137</td>
<td>0</td>
<td><img src=Images\5608652022217.15F.jpg alt="a rainha margot" height=110 width=95></td>
</tr>
<tr>
<td>A Rede</td>
<td>The Net</td>
<td>A Rede</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5606376278965.15F.jpg alt="a rede" height=110 width=95></td>
</tr>
<tr>
<td>A ressaca</td>
<td>The Hangover</td>
<td>A ressaca</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>103</td>
<td>Comédia</td>
<td><img src=Images\5601887551958.15F.jpg alt="a ressaca" height=110 width=95></td>
</tr>
<tr>
<td>A ressaca - Parte III</td>
<td>The Hangover: Part III</td>
<td>A ressaca - Parte III</td>
<td></td>
<td>X</td>
<td>2013</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5051892124348.4F.jpg alt="a ressaca - parte iii" height=110 width=95></td>
</tr>
<tr>
<td>A Ressaca Parte II</td>
<td>The Hangover Part II</td>
<td>A Ressaca Parte II</td>
<td></td>
<td>X</td>
<td>2011</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\5601887574926.15F.jpg alt="a ressaca parte ii" height=110 width=95></td>
</tr>
<tr>
<td>A Secretária</td>
<td>Secretary</td>
<td>A Secretaria</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>107</td>
<td>0</td>
<td><img src=Images\5608652021685.15F.jpg alt="a secretaria" height=110 width=95></td>
</tr>
<tr>
<td>A Soma de Todos os Medos</td>
<td>The Sum of All Fears</td>
<td>A Soma de Todos os Medos</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>119</td>
<td>Acção</td>
<td><img src=Images\5601887444991.15F.jpg alt="a soma de todos os medos" height=110 width=95></td>
</tr>
<tr>
<td>A Sombra da Forca</td>
<td>Hang 'em High</td>
<td>A Sombra da Forca</td>
<td>X</td>
<td>X</td>
<td>1968</td>
<td>110</td>
<td>Western</td>
<td><img src=Images\5600304195355.15F.jpg alt="a sombra da forca" height=110 width=95></td>
</tr>
<tr>
<td>A Toda a Prova</td>
<td>Foolproof</td>
<td>A Toda a Prova</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>90</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652022972.15F.jpg alt="a toda a prova" height=110 width=95></td>
</tr>
<tr>
<td>A Todos um Shrek Natal</td>
<td>Shrek The Halls</td>
<td>A Todos um Shrek Natal</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>27</td>
<td>Animação</td>
<td><img src=Images\5601887528639.15F.jpg alt="a todos um shrek natal" height=110 width=95></td>
</tr>
<tr>
<td>A Última Cartada</td>
<td>21</td>
<td>A Ultima Cartada</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>118</td>
<td>0</td>
<td><img src=Images\8414533052634.15F.jpg alt="a ultima cartada" height=110 width=95></td>
</tr>
<tr>
<td>A Última Legião</td>
<td>The Last Legion</td>
<td>A Ultima Legiao</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>97</td>
<td>0</td>
<td><img src=Images\5608652032124.15F.jpg alt="a ultima legiao" height=110 width=95></td>
</tr>
<tr>
<td>A Vedação</td>
<td>Rabbit-Proof Fence</td>
<td>A Vedacao</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>90</td>
<td>Aventura</td>
<td><img src=Images\5601887453511.15F.jpg alt="a vedacao" height=110 width=95></td>
</tr>
<tr>
<td>A Verdade da Mentira</td>
<td>True Lies</td>
<td>A Verdade da Mentira</td>
<td></td>
<td>X</td>
<td>1994</td>
<td>135</td>
<td>Acção</td>
<td><img src=Images\5601887422302.15F.jpg alt="a verdade da mentira" height=110 width=95></td>
</tr>
<tr>
<td>A Verdade Escondida</td>
<td>What Lies Beneath</td>
<td>A Verdade Escondida</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>125</td>
<td>0</td>
<td><img src=Images\5608652005821.15F.jpg alt="a verdade escondida" height=110 width=95></td>
</tr>
<tr>
<td>A Verdade Sobre Charlie</td>
<td>The Truth About Charlie</td>
<td>A Verdade Sobre Charlie</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5050582009231.15F.jpg alt="a verdade sobre charlie" height=110 width=95></td>
</tr>
<tr>
<td>A Verdadeira História de Jack, o Estripador</td>
<td>From Hell</td>
<td>A Verdadeira Historia de Jack, o Estripador</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>117</td>
<td>Horror</td>
<td><img src=Images\5608652012393.15F.jpg alt="a verdadeira historia de jack, o estripador" height=110 width=95></td>
</tr>
<tr>
<td>A Vida é Bela</td>
<td>La Vita è Bella</td>
<td>A Vida e Bela</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>111</td>
<td>0</td>
<td><img src=Images\5600304160896.15F.jpg alt="a vida e bela" height=110 width=95></td>
</tr>
<tr>
<td>A Vida é um Milagre</td>
<td>Zivot Je Cudo</td>
<td>A Vida e um Milagre</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>149</td>
<td>0</td>
<td><img src=Images\5606699505212.15F.jpg alt="a vida e um milagre" height=110 width=95></td>
</tr>
<tr>
<td>A Vida Não É Uma Roleta</td>
<td>Duane Hopwood</td>
<td>A Vida Nao E Uma Roleta</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>80</td>
<td>Comédia</td>
<td><img src=Images\5602193340458.15F.jpg alt="a vida nao e uma roleta" height=110 width=95></td>
</tr>
<tr>
<td>A Vila</td>
<td>The Village</td>
<td>A Vila</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>104</td>
<td>0</td>
<td><img src=Images\5601887468157.15F.jpg alt="a vila" height=110 width=95></td>
</tr>
<tr>
<td>A Vizinha do Lado</td>
<td>0</td>
<td>A Vizinha do Lado</td>
<td>X</td>
<td>X</td>
<td>1945</td>
<td>115</td>
<td>Comédia</td>
<td><img src=Images\5601887482733.15F.jpg alt="a vizinha do lado" height=110 width=95></td>
</tr>
<tr>
<td>Abandonada</td>
<td>0</td>
<td>Abandonada</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>103</td>
<td>Horror</td>
<td><img src=Images\5601887432936.15F.jpg alt="abandonada" height=110 width=95></td>
</tr>
<tr>
<td>ABC da sedução</td>
<td>The Ugly Truth</td>
<td>ABC da seducao</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\8414533064477.15F.jpg alt="abc da seducao" height=110 width=95></td>
</tr>
<tr>
<td>Aberto até de Madrugada</td>
<td>From Dusk Till Dawn</td>
<td>Aberto ate de Madrugada</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>103</td>
<td>Acção</td>
<td><img src=Images\5600304190541.15F.jpg alt="aberto ate de madrugada" height=110 width=95></td>
</tr>
<tr>
<td>Abram Alas para o Noddy - Noddy Salva o Natal</td>
<td>Make Way for Noddy: Noddy Saves Christmas</td>
<td>Abram Alas para o Noddy - Noddy Salva o Natal</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>95</td>
<td>0</td>
<td><img src=Images\5601887476817.15F.jpg alt="abram alas para o noddy - noddy salva o natal" height=110 width=95></td>
</tr>
<tr>
<td>Abram alas para o Noddy - Segura bem o chapéu</td>
<td>Make Way for Noddy: Hold on to your hat</td>
<td>Abram alas para o Noddy - Segura bem o chapeu</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>81</td>
<td>Animação</td>
<td><img src=Images\5601887461813.15F.jpg alt="abram alas para o noddy - segura bem o chapeu" height=110 width=95></td>
</tr>
<tr>
<td>Abram alas para o Noddy - Uma bicicleta para o Orelhas</td>
<td>Make Way for Noddy: A Bike for Big Ears</td>
<td>Abram alas para o Noddy - Uma bicicleta para o Orelhas</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>70</td>
<td>Animação</td>
<td><img src=Images\5601887464357.15F.jpg alt="abram alas para o noddy - uma bicicleta para o orelhas" height=110 width=95></td>
</tr>
<tr>
<td>Acabados de morrer</td>
<td>Just Buried</td>
<td>Acabados de morrer</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\858423001643F.jpg alt="acabados de morrer" height=110 width=95></td>
</tr>
<tr>
<td>Academia De Gladiadores</td>
<td>0</td>
<td>Academia De Gladiadores</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M1.15F.jpg alt="academia de gladiadores" height=110 width=95></td>
</tr>
<tr>
<td>Acho que gosto da minha mulher</td>
<td>0</td>
<td>Acho que gosto da minha mulher</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M115.15F.jpg alt="acho que gosto da minha mulher" height=110 width=95></td>
</tr>
<tr>
<td>Aconteceu na Argentina</td>
<td>Imagining Argentina</td>
<td>Aconteceu na Argentina</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>109</td>
<td>0</td>
<td><img src=Images\5608652024891.15F.jpg alt="aconteceu na argentina" height=110 width=95></td>
</tr>
<tr>
<td>Acordado</td>
<td>Awake</td>
<td>Acordado</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>84</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304198967.15F.jpg alt="acordado" height=110 width=95></td>
</tr>
<tr>
<td>Acordar em Reno</td>
<td>Waking up in Reno</td>
<td>Acordar em Reno</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>87</td>
<td>Romance</td>
<td><img src=Images\5607727095965.15F.jpg alt="acordar em reno" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td><NAME>urrected</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>106</td>
<td>Drama</td>
<td><img src=Images\5606320001717.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Adepto Fanático</td>
<td>The Fan</td>
<td>Adepto Fanatico</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>0</td>
<td>0</td>
<td><img src=Images\5602193305907.15F.jpg alt="adepto fanatico" height=110 width=95></td>
</tr>
<tr>
<td>Adivinha Quem</td>
<td>Guess Who</td>
<td>Adivinha Quem</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>128</td>
<td>Comédia</td>
<td><img src=Images\5600304162494.15F.jpg alt="adivinha quem" height=110 width=95></td>
</tr>
<tr>
<td>Agente Acidental</td>
<td>The Man</td>
<td>Agente Acidental</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>80</td>
<td>Acção</td>
<td><img src=Images\5602193346115.15F.jpg alt="agente acidental" height=110 width=95></td>
</tr>
<tr>
<td>Agente Secreto 007</td>
<td>Dr. No</td>
<td>Agente Secreto 007</td>
<td>X</td>
<td>X</td>
<td>1962</td>
<td>105</td>
<td>Acção</td>
<td><img src=Images\IF38C4946CBC85754.15F.jpg alt="agente secreto 007" height=110 width=95></td>
</tr>
<tr>
<td>Ágora</td>
<td>0</td>
<td>Agora</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>126</td>
<td>Aventura</td>
<td><img src=Images\5600304214001.15F.jpg alt="agora" height=110 width=95></td>
</tr>
<tr>
<td>Air America</td>
<td>0</td>
<td>Air America</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>108</td>
<td>Acção</td>
<td><img src=Images\044007834824.15F.jpg alt="air america" height=110 width=95></td>
</tr>
<tr>
<td>Al Capone</td>
<td>Capone</td>
<td>Al Capone</td>
<td>X</td>
<td>X</td>
<td>1975</td>
<td>97</td>
<td>Crime</td>
<td><img src=Images\5600304216746.15F.jpg alt="al capone" height=110 width=95></td>
</tr>
<tr>
<td>Aladdin</td>
<td>0</td>
<td>Aladdin</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>87</td>
<td>Animação</td>
<td><img src=Images\5601887465248.15F.jpg alt="aladdin" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME>obbs</td>
<td></td>
<td>X</td>
<td>2011</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5606320028479.15F.jpg alt="albert nobbs" height=110 width=95></td>
</tr>
<tr>
<td>Aldeia da Roupa Branca</td>
<td>0</td>
<td>Aldeia da Roupa Branca</td>
<td>X</td>
<td>X</td>
<td>1938</td>
<td>84</td>
<td>0</td>
<td><img src=Images\5606699506943.15F.jpg alt="aldeia da roupa branca" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Alexander</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>107</td>
<td>0</td>
<td><img src=Images\5601887470839.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Ali</td>
<td>0</td>
<td>Ali</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>151</td>
<td>Drama</td>
<td><img src=Images\5602193310260.15F.jpg alt="ali" height=110 width=95></td>
</tr>
<tr>
<td>Ali Baba</td>
<td>0</td>
<td>Ali Baba</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M7.15F.jpg alt="ali baba" height=110 width=95></td>
</tr>
<tr>
<td>Alta Traição</td>
<td>No Way Out</td>
<td>Alta Traicao</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304176996.15F.jpg alt="alta traicao" height=110 width=95></td>
</tr>
<tr>
<td>Altos Voos</td>
<td>View from the top</td>
<td>Altos Voos</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>83</td>
<td>Comédia</td>
<td><img src=Images\5608652021159.15F.jpg alt="altos voos" height=110 width=95></td>
</tr>
<tr>
<td>Alvo em Movimento</td>
<td>A View to a Kill</td>
<td>Alvo em Movimento</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>126</td>
<td>Acção</td>
<td><img src=Images\IA72164A3BA5D8B22.15F.jpg alt="alvo em movimento" height=110 width=95></td>
</tr>
<tr>
<td>Alvo Marcado</td>
<td>Rabbit on the Moon</td>
<td>Alvo Marcado</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>109</td>
<td>0</td>
<td><img src=Images\4042564017335.5F.jpg alt="alvo marcado" height=110 width=95></td>
</tr>
<tr>
<td>Amar em Nova Iorque</td>
<td>Autumn in New York</td>
<td>Amar em Nova Iorque</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>101</td>
<td>Romance</td>
<td><img src=Images\5601887428236.15F.jpg alt="amar em nova iorque" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Come Early Morning</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>93</td>
<td>Romance</td>
<td><img src=Images\5600304177948.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>América Proibida</td>
<td>American History X</td>
<td>America Proibida</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5602193303606.15F.jpg alt="america proibida" height=110 width=95></td>
</tr>
<tr>
<td>American Pie - A Primeira Vez</td>
<td>American Pie</td>
<td>American Pie - A Primeira Vez</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>92</td>
<td>Comédia</td>
<td><img src=Images\5601887426409.15F.jpg alt="american pie - a primeira vez" height=110 width=95></td>
</tr>
<tr>
<td>American Splendor</td>
<td>0</td>
<td>American Splendor</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>101</td>
<td>0</td>
<td><img src=Images\5606699506073.15F.jpg alt="american splendor" height=110 width=95></td>
</tr>
<tr>
<td>Amigos Com Dinheiro</td>
<td>Friends With Money</td>
<td>Amigos Com Dinheiro</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>84</td>
<td>Comédia</td>
<td><img src=Images\8414533042970.15F.jpg alt="amigos com dinheiro" height=110 width=95></td>
</tr>
<tr>
<td>Amor e Mentiras</td>
<td>Something to Talk About</td>
<td>Amor e Mentiras</td>
<td></td>
<td>X</td>
<td>1995</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5600304179300.15F.jpg alt="amor e mentiras" height=110 width=95></td>
</tr>
<tr>
<td>Amor numa pequena cidade</td>
<td>I'm Reed Fish</td>
<td>Amor numa pequena cidade</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>93</td>
<td>Romance</td>
<td><img src=Images\025195015431F.jpg alt="amor numa pequena cidade" height=110 width=95></td>
</tr>
<tr>
<td>Amor por acaso</td>
<td>Love Happens</td>
<td>Amor por acaso</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>109</td>
<td>Comédia</td>
<td><img src=Images\5600304213981.15F.jpg alt="amor por acaso" height=110 width=95></td>
</tr>
<tr>
<td>Amor Sem Aviso</td>
<td>Two Weeks Notice</td>
<td>Amor Sem Aviso</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\7321976234187.15F.jpg alt="amor sem aviso" height=110 width=95></td>
</tr>
<tr>
<td>Amor sem Fronteiras</td>
<td>Beyond Borders</td>
<td>Amor sem Fronteiras</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>122</td>
<td>0</td>
<td><img src=Images\5601887464388.15F.jpg alt="amor sem fronteiras" height=110 width=95></td>
</tr>
<tr>
<td>Angelina Bailarina</td>
<td>0</td>
<td>Angelina Bailarina</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M5.15F.jpg alt="angelina bailarina" height=110 width=95></td>
</tr>
<tr>
<td>Animais Unidos Jamais Serão Vencidos</td>
<td><NAME></td>
<td>Animais Unidos Jamais Serao Vencidos</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>89</td>
<td>Animação</td>
<td><img src=Images\7898023246979.23F.jpg alt="animais unidos jamais serao vencidos" height=110 width=95></td>
</tr>
<tr>
<td>Animatrix</td>
<td>The Animatrix</td>
<td>Animatrix</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>89</td>
<td>0</td>
<td><img src=Images\7321976373169.15F.jpg alt="animatrix" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>State of Grace</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>129</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304176989.15F.jpg alt="anjos caidos" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Angels & Demons</td>
<td>Anjos e Demonios</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>140</td>
<td>Suspense/Thriller</td>
<td><img src=Images\8414533063425.15F.jpg alt="anjos e demonios" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>103</td>
<td>Drama</td>
<td><img src=Images\5601887430604.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Ano Novo, Vida Nova</td>
<td>New Year's Eve</td>
<td>Ano Novo, Vida Nova</td>
<td></td>
<td>X</td>
<td>2011</td>
<td>118</td>
<td>Romance</td>
<td><img src=Images\7892110134750.23F.jpg alt="ano novo, vida nova" height=110 width=95></td>
</tr>
<tr>
<td>Antwone Fisher</td>
<td>0</td>
<td>Antwone Fisher</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>120</td>
<td>Drama</td>
<td><img src=Images\5600304164412.15F.jpg alt="antwone fisher" height=110 width=95></td>
</tr>
<tr>
<td>Ao Serviço de Sua Majestade</td>
<td>On Her Majesty's Secret Service</td>
<td>Ao Servico de Sua Majestade</td>
<td>X</td>
<td>X</td>
<td>1969</td>
<td>136</td>
<td>Acção</td>
<td><img src=Images\I69A04C9AA32030DF.15F.jpg alt="ao servico de sua majestade" height=110 width=95></td>
</tr>
<tr>
<td>Apanha-me Se Puderes</td>
<td>Catch Me If You Can</td>
<td>Apanha-me Se Puderes</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>135</td>
<td>Drama</td>
<td><img src=Images\5601887492909.15F.jpg alt="apanha-me se puderes" height=110 width=95></td>
</tr>
<tr>
<td>Apenas Amigos</td>
<td>Just Friends</td>
<td>Apenas Amigos</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5602193330770.15F.jpg alt="apenas amigos" height=110 width=95></td>
</tr>
<tr>
<td>Apocalypse Now: Redux</td>
<td>Apocalypse Now</td>
<td>Apocalypse Now: Redux</td>
<td>X</td>
<td>X</td>
<td>1979</td>
<td>194</td>
<td>0</td>
<td><img src=Images\5601887439249.15F.jpg alt="apocalypse now: redux" height=110 width=95></td>
</tr>
<tr>
<td>Apollo 13</td>
<td>0</td>
<td>Apollo 13</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>135</td>
<td>Drama</td>
<td><img src=Images\I907104A68C51F0E3.15F.jpg alt="apollo 13" height=110 width=95></td>
</tr>
<tr>
<td>Aposta de Risco</td>
<td>Two for the Money</td>
<td>Aposta de Risco</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>123</td>
<td>0</td>
<td><img src=Images\5601887484706.15F.jpg alt="aposta de risco" height=110 width=95></td>
</tr>
<tr>
<td>Aritmética Emocional</td>
<td>Emotional Arithmetic</td>
<td>Aritmetica Emocional</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\ID798E85F85528831.15F.jpg alt="aritmetica emocional" height=110 width=95></td>
</tr>
<tr>
<td>Arma Biológica</td>
<td>The Enemy</td>
<td>Arma Biologica</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5608652013758.15F.jpg alt="arma biologica" height=110 width=95></td>
</tr>
<tr>
<td>Arma Mortífera 4</td>
<td>Lethal Weapon 4</td>
<td>Arma Mortifera 4</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\5606376506914.15F.jpg alt="arma mortifera 4" height=110 width=95></td>
</tr>
<tr>
<td>As Asas do Desejo</td>
<td><NAME> über Berlin</td>
<td>As Asas do Desejo</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>122</td>
<td>Drama</td>
<td><img src=Images\ICD1692F64F54CE71.15F.jpg alt="as asas do desejo" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras de Blueberry</td>
<td>Blueberry</td>
<td>As Aventuras de Blueberry</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>119</td>
<td>Western</td>
<td><img src=Images\5608652026574.15F.jpg alt="as aventuras de blueberry" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras De Mowgli</td>
<td>0</td>
<td>As Aventuras De Mowgli</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M9.15F.jpg alt="as aventuras de mowgli" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras de Peter Pan</td>
<td>Peter Pan</td>
<td>As Aventuras de Peter Pan</td>
<td>X</td>
<td>X</td>
<td>1953</td>
<td>75</td>
<td>Animação</td>
<td><img src=Images\5601887490073.15F.jpg alt="as aventuras de peter pan" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras de Tintim: A Ilha Negra</td>
<td>Les Aventures de Tintin: L'Ile Noire</td>
<td>As Aventuras de Tintim: A Ilha Negra</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>40</td>
<td>0</td>
<td><img src=Images\5605189006604.15F.jpg alt="as aventuras de tintim: a ilha negra" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras de Tintim: O Ceptro de Ottokar</td>
<td>Les Aventures de Tintin: Le Sceptre D'Ottokar</td>
<td>As Aventuras de Tintim: O Ceptro de Ottokar</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>50</td>
<td>0</td>
<td><img src=Images\I5F65E5490130B92A.15F.jpg alt="as aventuras de tintim: o ceptro de ottokar" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras de Tintim: Objetivo Lua</td>
<td>0</td>
<td>As Aventuras de Tintim: Objetivo Lua</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\5602227301844.15F.jpg alt="as aventuras de tintim: objetivo lua" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras De Tintim: Pisando a Lua</td>
<td>0</td>
<td>As Aventuras De Tintim: Pisando a Lua</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M10.15F.jpg alt="as aventuras de tintim: pisando a lua" height=110 width=95></td>
</tr>
<tr>
<td>As aventuras de Tintim: Tintim no Tibete</td>
<td>0</td>
<td>As aventuras de Tintim: Tintim no Tibete</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>41</td>
<td>Aventura</td>
<td><img src=Images\3309450018694.8F.jpg alt="as aventuras de tintim: tintim no tibete" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras Do Pica-pau</td>
<td>0</td>
<td>As Aventuras Do Pica-pau</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M11.15F.jpg alt="as aventuras do pica-pau" height=110 width=95></td>
</tr>
<tr>
<td>As Aventuras do Tigre</td>
<td>The Tigger Movie</td>
<td>As Aventuras do Tigre</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>77</td>
<td>Animação</td>
<td><img src=Images\5601887410651.15F.jpg alt="as aventuras do tigre" height=110 width=95></td>
</tr>
<tr>
<td>As bandeiras dos nossos pais</td>
<td>Flags of Our Fathers</td>
<td>As bandeiras dos nossos pais</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>132</td>
<td>Guerra</td>
<td><img src=Images\7321974121618.15F.jpg alt="as bandeiras dos nossos pais" height=110 width=95></td>
</tr>
<tr>
<td>As Confissões de Schmidt</td>
<td>About Schmidt</td>
<td>As Confissoes de Schmidt</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>120</td>
<td>Comédia</td>
<td><img src=Images\5608652018210.15F.jpg alt="as confissoes de schmidt" height=110 width=95></td>
</tr>
<tr>
<td>As Duas Feras</td>
<td>Bringing up Baby</td>
<td>As Duas Feras</td>
<td>X</td>
<td>X</td>
<td>1938</td>
<td>102</td>
<td>Comédia</td>
<td><img src=Images\I40E2855E5D4A3E71.15F.jpg alt="as duas feras" height=110 width=95></td>
</tr>
<tr>
<td>As Férias do Sr. Hulot</td>
<td>Les vacances de Monsieur Hulot</td>
<td>As Ferias do Sr. Hulot</td>
<td>X</td>
<td>X</td>
<td>1953</td>
<td>83</td>
<td>Comédia</td>
<td><img src=Images\5606699505281.15F.jpg alt="as ferias do sr. hulot" height=110 width=95></td>
</tr>
<tr>
<td>As Horas</td>
<td>The Hours</td>
<td>As Horas</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>112</td>
<td>Drama</td>
<td><img src=Images\5608652020039.15F.jpg alt="as horas" height=110 width=95></td>
</tr>
<tr>
<td>As Irmãs de Maria Madalena</td>
<td>The Magdalene Sisters</td>
<td>As Irmas de Maria Madalena</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\I0BBB3DBF5F646868.15F.jpg alt="as irmas de maria madalena" height=110 width=95></td>
</tr>
<tr>
<td>As Leis da Atracção</td>
<td>Laws of Attraction</td>
<td>As Leis da Atraccao</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5602193341950.15F.jpg alt="as leis da atraccao" height=110 width=95></td>
</tr>
<tr>
<td>As Minas do Rei Salomão</td>
<td>King Solomon's Mines</td>
<td>As Minas do Rei Salomao</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>169</td>
<td>0</td>
<td><img src=Images\5601887464319.15F.jpg alt="as minas do rei salomao" height=110 width=95></td>
</tr>
<tr>
<td>As Paixões de Júlia</td>
<td>Being Julia</td>
<td>As Paixoes de Julia</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5608652027076.15F.jpg alt="as paixoes de julia" height=110 width=95></td>
</tr>
<tr>
<td>As Quatro Penas Brancas</td>
<td>The Four Feathers</td>
<td>As Quatro Penas Brancas</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>130</td>
<td>Aventura</td>
<td><img src=Images\5601684000017.15F.jpg alt="as quatro penas brancas" height=110 width=95></td>
</tr>
<tr>
<td>As regras de Brooklyn</td>
<td>Brooklyn Rules</td>
<td>As regras de Brooklyn</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5051429101453.4F.jpg alt="as regras de brooklyn" height=110 width=95></td>
</tr>
<tr>
<td>Assalto á 13ª Esquadra</td>
<td>Assault on Precinct 13</td>
<td>Assalto a 13ª Esquadra</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\5602193324502.15F.jpg alt="assalto a 13ª esquadra" height=110 width=95></td>
</tr>
<tr>
<td>Assalto ao Aeroporto</td>
<td>Die Hard 2</td>
<td>Assalto ao Aeroporto</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>123</td>
<td>Acção</td>
<td><img src=Images\5600304162777.15F.jpg alt="assalto ao aeroporto" height=110 width=95></td>
</tr>
<tr>
<td>Assalto ao Arranha-Céus</td>
<td>Die Hard</td>
<td>Assalto ao Arranha-Ceus</td>
<td>X</td>
<td>X</td>
<td>1988</td>
<td>127</td>
<td>Acção</td>
<td><img src=Images\5608652000338.15F.jpg alt="assalto ao arranha-ceus" height=110 width=95></td>
</tr>
<tr>
<td>Assalto ao metro 123</td>
<td>The Taking of Pelham 1 2 3</td>
<td>Assalto ao metro 123</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>106</td>
<td>Acção</td>
<td><img src=Images\8414533064828.15F.jpg alt="assalto ao metro 123" height=110 width=95></td>
</tr>
<tr>
<td>Assalto Mortífero</td>
<td>Truth or Consequences, N.M.</td>
<td>Assalto Mortifero</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>107</td>
<td>Acção</td>
<td><img src=Images\043396826991F.jpg alt="assalto mortifero" height=110 width=95></td>
</tr>
<tr>
<td>Astérix & Obélix: Missão Cleópatra</td>
<td>Astérix & Obélix: Mission Cléopâtre</td>
<td>Asterix & Obelix: Missao Cleopatra</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887436439.15F.jpg alt="asterix & obelix: missao cleopatra" height=110 width=95></td>
</tr>
<tr>
<td>Até ao Fim</td>
<td>The Deep End</td>
<td>Ate ao Fim</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>96</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652011150.15F.jpg alt="ate ao fim" height=110 width=95></td>
</tr>
<tr>
<td>Até Que Me Encontrou ...</td>
<td>Then She Found Me</td>
<td>Ate Que Me Encontrou ...</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\IA43C15F845F96379.15F.jpg alt="ate que me encontrou ..." height=110 width=95></td>
</tr>
<tr>
<td>Atlântida: O Continente Perdido</td>
<td>Atlantis: The Lost Empire</td>
<td>Atlantida: O Continente Perdido</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>92</td>
<td>Animação</td>
<td><img src=Images\5601887432370.15F.jpg alt="atlantida: o continente perdido" height=110 width=95></td>
</tr>
<tr>
<td>Atracção Perigosa</td>
<td>In the Cut</td>
<td>Atraccao Perigosa</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>119</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193319027.15F.jpg alt="atraccao perigosa" height=110 width=95></td>
</tr>
<tr>
<td>Atrás das Linhas do Inimigo</td>
<td>Behind Enemy Lines</td>
<td>Atras das Linhas do Inimigo</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>118</td>
<td>0</td>
<td><img src=Images\5608652011013.15F.jpg alt="atras das linhas do inimigo" height=110 width=95></td>
</tr>
<tr>
<td>Austin Powers: O Agente Misterioso</td>
<td>Austin Powers: International Man of Mystery</td>
<td>Austin Powers: O Agente Misterioso</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\I3D50694ABA61F864.15F.jpg alt="austin powers: o agente misterioso" height=110 width=95></td>
</tr>
<tr>
<td>Australia</td>
<td>0</td>
<td>Australia</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>159</td>
<td>Acção</td>
<td><img src=Images\5600304208635.15F.jpg alt="australia" height=110 width=95></td>
</tr>
<tr>
<td>Autocarro 174</td>
<td>Última Parada 174</td>
<td>Autocarro 174</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>107</td>
<td>Crime</td>
<td><img src=Images\5606320007795.15F.jpg alt="autocarro 174" height=110 width=95></td>
</tr>
<tr>
<td>Autópsia de um Crime</td>
<td>Sleuth</td>
<td>Autopsia de um Crime</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>85</td>
<td>Drama</td>
<td><img src=Images\5608652033091.15F.jpg alt="autopsia de um crime" height=110 width=95></td>
</tr>
<tr>
<td>Avatar</td>
<td>0</td>
<td>Avatar</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>162</td>
<td>Fantasia</td>
<td><img src=Images\5600304213851.15F.jpg alt="avatar" height=110 width=95></td>
</tr>
<tr>
<td>Aventura no Espaço</td>
<td>Moonraker</td>
<td>Aventura no Espaco</td>
<td>X</td>
<td>X</td>
<td>1979</td>
<td>121</td>
<td>Acção</td>
<td><img src=Images\I2A4B9D486317A55C.15F.jpg alt="aventura no espaco" height=110 width=95></td>
</tr>
<tr>
<td>Aviões 2:Equipa de resgate</td>
<td>Planes: Fire & Rescu</td>
<td>Avioes 2:Equipa de resgate</td>
<td></td>
<td>X</td>
<td>2014</td>
<td>84</td>
<td>Animação</td>
<td><img src=Images\7899307921087.23F.jpg alt="avioes 2:equipa de resgate" height=110 width=95></td>
</tr>
<tr>
<td>Azul Escuro</td>
<td>Dark Blue</td>
<td>Azul Escuro</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>113</td>
<td>0</td>
<td><img src=Images\5601887454457.15F.jpg alt="azul escuro" height=110 width=95></td>
</tr>
<tr>
<td>Bad Boys</td>
<td>0</td>
<td>Bad Boys</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>114</td>
<td>Acção</td>
<td><img src=Images\8414533023818.15F.jpg alt="bad boys" height=110 width=95></td>
</tr>
<tr>
<td>Bad Boys 2</td>
<td>Bad Boys II</td>
<td>Bad Boys 2</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>141</td>
<td>Acção</td>
<td><img src=Images\8414533023665.15F.jpg alt="bad boys 2" height=110 width=95></td>
</tr>
<tr>
<td>Bad Company - Más Companhias</td>
<td>Bad Company</td>
<td>Bad Company - Mas Companhias</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>111</td>
<td>0</td>
<td><img src=Images\5601887444557.15F.jpg alt="bad company - mas companhias" height=110 width=95></td>
</tr>
<tr>
<td>Bad Santa - O Anti-Pai Natal</td>
<td>Bad Santa</td>
<td>Bad Santa - O Anti-Pai Natal</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5600304160049.15F.jpg alt="bad santa - o anti-pai natal" height=110 width=95></td>
</tr>
<tr>
<td>Bailey Um Cão que Vale Milhões</td>
<td>Bailey's Millions</td>
<td>Bailey Um Cao que Vale Milhoes</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>85</td>
<td>0</td>
<td><img src=Images\5600304160476.15F.jpg alt="bailey um cao que vale milhoes" height=110 width=95></td>
</tr>
<tr>
<td>Balas sobre a Broadway</td>
<td>Bullets Over Broadway</td>
<td>Balas sobre a Broadway</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\I16F85192C66DE09E.15F.jpg alt="balas sobre a broadway" height=110 width=95></td>
</tr>
<tr>
<td>Balbúrdia na Quinta</td>
<td>Barnyard</td>
<td>Balburdia na Quinta</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>86</td>
<td>0</td>
<td><img src=Images\5601887490363.15F.jpg alt="balburdia na quinta" height=110 width=95></td>
</tr>
<tr>
<td>Balto & Balto Aventura na Terra do Gelo</td>
<td>Balto II: Wolf Quest</td>
<td>Balto & Balto Aventura na Terra do Gelo</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>76</td>
<td>0</td>
<td><img src=Images\7892141404976.23F.jpg alt="balto & balto aventura na terra do gelo" height=110 width=95></td>
</tr>
<tr>
<td>Bandidas</td>
<td>0</td>
<td>Bandidas</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>99</td>
<td>0</td>
<td><img src=Images\5601887484904.15F.jpg alt="bandidas" height=110 width=95></td>
</tr>
<tr>
<td>Bandidos</td>
<td>Bandits</td>
<td>Bandidos</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>121</td>
<td>Comédia</td>
<td><img src=Images\5601887439195.15F.jpg alt="bandidos" height=110 width=95></td>
</tr>
<tr>
<td>Básico</td>
<td>Basic</td>
<td>Basico</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>94</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887458189.15F.jpg alt="basico" height=110 width=95></td>
</tr>
<tr>
<td>Batalha de Gigantes</td>
<td>Fun and Fancy Free</td>
<td>Batalha de Gigantes</td>
<td>X</td>
<td>X</td>
<td>1947</td>
<td>70</td>
<td>Animação</td>
<td><img src=Images\5601887430178.15F.jpg alt="batalha de gigantes" height=110 width=95></td>
</tr>
<tr>
<td>Batman para Sempre</td>
<td>Batman Forever</td>
<td>Batman para Sempre</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\5606376273946.15F.jpg alt="batman para sempre" height=110 width=95></td>
</tr>
<tr>
<td>Batman Regressa</td>
<td>Batman Returns</td>
<td>Batman Regressa</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\7321976150005.15F.jpg alt="batman regressa" height=110 width=95></td>
</tr>
<tr>
<td>Batman: O Cavaleiro das Trevas</td>
<td>The Dark Knight</td>
<td>Batman: O Cavaleiro das Trevas</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>146</td>
<td>Acção</td>
<td><img src=Images\5600304200684.15F.jpg alt="batman: o cavaleiro das trevas" height=110 width=95></td>
</tr>
<tr>
<td>Beijo da Morte</td>
<td>Kiss of Death</td>
<td>Beijo da Morte</td>
<td></td>
<td>X</td>
<td>1995</td>
<td>97</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304163552.15F.jpg alt="beijo da morte" height=110 width=95></td>
</tr>
<tr>
<td>Beijos & balas</td>
<td>Killers</td>
<td>Beijos & balas</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5602193354288.15F.jpg alt="beijos & balas" height=110 width=95></td>
</tr>
<tr>
<td>Bela loucura</td>
<td>Crazy/Beautiful</td>
<td>Bela loucura</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>95</td>
<td>Drama</td>
<td><img src=Images\5601887430086.15F.jpg alt="bela loucura" height=110 width=95></td>
</tr>
<tr>
<td>Beleza Americana</td>
<td>American Beauty</td>
<td>Beleza Americana</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\0678149096125.15F.jpg alt="beleza americana" height=110 width=95></td>
</tr>
<tr>
<td>Belleville Rendez-Vous</td>
<td>Les Triplettes de Belleville</td>
<td>Belleville Rendez-Vous</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>78</td>
<td>0</td>
<td><img src=Images\5602227302001.15F.jpg alt="belleville rendez-vous" height=110 width=95></td>
</tr>
<tr>
<td>Bem Vindos à Selva</td>
<td>The Rundown</td>
<td>Bem Vindos a Selva</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\8414533025928.15F.jpg alt="bem vindos a selva" height=110 width=95></td>
</tr>
<tr>
<td>Beowulf & Grendel - A lenda dos Vikings</td>
<td>Beowulf & Grendel</td>
<td>Beowulf & Grendel - A lenda dos Vikings</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5600304169677.15F.jpg alt="beowulf & grendel - a lenda dos vikings" height=110 width=95></td>
</tr>
<tr>
<td>Betty</td>
<td>N<NAME></td>
<td>Betty</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5601887461745.15F.jpg alt="betty" height=110 width=95></td>
</tr>
<tr>
<td>Big</td>
<td>0</td>
<td>Big</td>
<td>X</td>
<td>X</td>
<td>1988</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5608652005913.15F.jpg alt="big" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>106</td>
<td>Drama</td>
<td><img src=Images\5601887427666.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Birth - O Mistério</td>
<td>Birth</td>
<td>Birth - O Misterio</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>96</td>
<td>0</td>
<td><img src=Images\I4E85D939AD7E1019.15F.jpg alt="birth - o misterio" height=110 width=95></td>
</tr>
<tr>
<td>Biutiful</td>
<td>0</td>
<td>Biutiful</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>142</td>
<td>Drama</td>
<td><img src=Images\5600304220026.15F.jpg alt="biutiful" height=110 width=95></td>
</tr>
<tr>
<td>Blackmail</td>
<td>0</td>
<td>Blackmail</td>
<td>X</td>
<td>X</td>
<td>1929</td>
<td>86</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I738D1217FD5B1B10.15F.jpg alt="blackmail" height=110 width=95></td>
</tr>
<tr>
<td>Bloody Sunday - Domingo Sangrento</td>
<td>Bloody Sunday</td>
<td>Bloody Sunday - Domingo Sangrento</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>110</td>
<td>Drama</td>
<td><img src=Images\5608652014441.15F.jpg alt="bloody sunday - domingo sangrento" height=110 width=95></td>
</tr>
<tr>
<td>Blue Car</td>
<td>0</td>
<td>Blue Car</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>84</td>
<td>Drama</td>
<td><img src=Images\5600304160339.15F.jpg alt="blue car" height=110 width=95></td>
</tr>
<tr>
<td>Blue Smoke</td>
<td>0</td>
<td>Blue Smoke</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>95</td>
<td>0</td>
<td><img src=Images\043396212213F.jpg alt="blue smoke" height=110 width=95></td>
</tr>
<tr>
<td>Bob o Construtor: O <NAME> com a Lama</td>
<td>Bob The Builder: Mucky Muck</td>
<td>Bob o Construtor: O <NAME> com a Lama</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>54</td>
<td>Animação</td>
<td><img src=Images\5608652029711.15F.jpg alt="bob o construtor: o lagartas adora brincar com a lama" height=110 width=95></td>
</tr>
<tr>
<td>Bobby</td>
<td>0</td>
<td>Bobby</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>112</td>
<td>Drama</td>
<td><img src=Images\5600304175661.15F.jpg alt="bobby" height=110 width=95></td>
</tr>
<tr>
<td>Bobby Z</td>
<td>The Death and Life of Bobby Z</td>
<td>Bobby Z</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5602193346832.15F.jpg alt="bobby z" height=110 width=95></td>
</tr>
<tr>
<td>BOLT</td>
<td>Bolt</td>
<td>BOLT</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>93</td>
<td>Animação</td>
<td><img src=Images\5601887531257.15F.jpg alt="bolt" height=110 width=95></td>
</tr>
<tr>
<td>Bond Girls são Eternas</td>
<td>007 - Bond Girls Are Forever</td>
<td>Bond Girls sao Eternas</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>46</td>
<td>Documentário</td>
<td><img src=Images\I61A19BFAFF917684.15F.jpg alt="bond girls sao eternas" height=110 width=95></td>
</tr>
<tr>
<td>Bordertown - Cidade sob Ameaça</td>
<td>Bordertown</td>
<td>Bordertown - Cidade sob Ameaca</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>107</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193346153.15F.jpg alt="bordertown - cidade sob ameaca" height=110 width=95></td>
</tr>
<tr>
<td>Bounce Um Acaso com Sentido</td>
<td>Bounce</td>
<td>Bounce Um Acaso com Sentido</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>102</td>
<td>Romance</td>
<td><img src=Images\5608652021210.15F.jpg alt="bounce um acaso com sentido" height=110 width=95></td>
</tr>
<tr>
<td>Bourne 03: Ultimato</td>
<td>The Bourne Ultimatum</td>
<td>Bourne 03: Ultimato</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>110</td>
<td>Acção</td>
<td><img src=Images\5600402401365.15F.jpg alt="bourne 03: ultimato" height=110 width=95></td>
</tr>
<tr>
<td>Branca de Neve e os Sete Anões</td>
<td>Snow White and the Seven Dwarfs</td>
<td>Branca de Neve e os Sete Anoes</td>
<td>X</td>
<td>X</td>
<td>1937</td>
<td>80</td>
<td>0</td>
<td><img src=Images\5601887424061.15F.jpg alt="branca de neve e os sete anoes" height=110 width=95></td>
</tr>
<tr>
<td>Braveheart - O Desafio Do Guerreiro</td>
<td>Braveheart</td>
<td>Braveheart - O Desafio Do Guerreiro</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>171</td>
<td>0</td>
<td><img src=Images\5608652020381.15F.jpg alt="braveheart - o desafio do guerreiro" height=110 width=95></td>
</tr>
<tr>
<td>Breakfast on Pluto</td>
<td>0</td>
<td>Breakfast on Pluto</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>123</td>
<td>Drama</td>
<td><img src=Images\5608652034241.15F.jpg alt="breakfast on pluto" height=110 width=95></td>
</tr>
<tr>
<td>Breaking News - Cidade em Alerta</td>
<td>Dai si gein</td>
<td>Breaking News - Cidade em Alerta</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>Acção</td>
<td><img src=Images\IF6EFCB42093E5D14.15F.jpg alt="breaking news - cidade em alerta" height=110 width=95></td>
</tr>
<tr>
<td>Broken Flowers - Flores Partidas</td>
<td>Broken Flowers</td>
<td>Broken Flowers - Flores Partidas</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5602193353816.15F.jpg alt="broken flowers - flores partidas" height=110 width=95></td>
</tr>
<tr>
<td>Bucha & Estica a caminho do oeste</td>
<td>Way Out West</td>
<td>Bucha & Estica a caminho do oeste</td>
<td></td>
<td>X</td>
<td>1937</td>
<td>61</td>
<td>Comédia</td>
<td><img src=Images\I63479CB0420EA799.15F.jpg alt="bucha & estica a caminho do oeste" height=110 width=95></td>
</tr>
<tr>
<td>Bucha e estica: Em frente marche!</td>
<td>Great Guns</td>
<td>Bucha e estica: Em frente marche!</td>
<td></td>
<td>X</td>
<td>1941</td>
<td>70</td>
<td>0</td>
<td><img src=Images\5608652027526.15F.jpg alt="bucha e estica: em frente marche!" height=110 width=95></td>
</tr>
<tr>
<td>Buzz Lightyear</td>
<td>Buzz Lightyear of Star Command: The Adventure Begins</td>
<td>Buzz Lightyear</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>67</td>
<td>Animação</td>
<td><img src=Images\5601887417100.15F.jpg alt="buzz lightyear" height=110 width=95></td>
</tr>
<tr>
<td>Caçador de Diamantes</td>
<td>0</td>
<td>Cacador de Diamantes</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M111.15F.jpg alt="cacador de diamantes" height=110 width=95></td>
</tr>
<tr>
<td>Cães Danados</td>
<td>Reservoir Dogs</td>
<td>Caes Danados</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>95</td>
<td>Suspense/Thriller</td>
<td><img src=Images\044007838723.15F.jpg alt="caes danados" height=110 width=95></td>
</tr>
<tr>
<td>Call Girl</td>
<td>0</td>
<td>Call Girl</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>136</td>
<td>0</td>
<td><img src=Images\5601887524266.15F.jpg alt="call girl" height=110 width=95></td>
</tr>
<tr>
<td>Caminho para Perdição</td>
<td>Road to Perdition</td>
<td>Caminho para Perdicao</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>112</td>
<td>Crime</td>
<td><img src=Images\5600304165556.15F.jpg alt="caminho para perdicao" height=110 width=95></td>
</tr>
<tr>
<td>Caminhos Inesperados</td>
<td>World Traveler</td>
<td>Caminhos Inesperados</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5602193320054.15F.jpg alt="caminhos inesperados" height=110 width=95></td>
</tr>
<tr>
<td>Caminhos Perigosos</td>
<td>The Gingerbread Man</td>
<td>Caminhos Perigosos</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>109</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I89BF1C4340B1914E.15F.jpg alt="caminhos perigosos" height=110 width=95></td>
</tr>
<tr>
<td>CAMP ROCK</td>
<td>Camp Rock</td>
<td>CAMP ROCK</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>95</td>
<td>Comédia</td>
<td><img src=Images\5601887527052.15F.jpg alt="camp rock" height=110 width=95></td>
</tr>
<tr>
<td>Candy</td>
<td>0</td>
<td>Candy</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>103</td>
<td>Drama</td>
<td><img src=Images\I44CD240EAD24DBD0.15F.jpg alt="candy" height=110 width=95></td>
</tr>
<tr>
<td>Capitães de Abril</td>
<td>0</td>
<td>Capitaes de Abril</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>119</td>
<td>0</td>
<td><img src=Images\5601887419197.15F.jpg alt="capitaes de abril" height=110 width=95></td>
</tr>
<tr>
<td>Capuchinho Vermelho - A Verdadeira História</td>
<td>Hoodwinked!</td>
<td>Capuchinho Vermelho - A Verdadeira Historia</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>77</td>
<td>Animação</td>
<td><img src=Images\5608652029858.15F.jpg alt="capuchinho vermelho - a verdadeira historia" height=110 width=95></td>
</tr>
<tr>
<td>Carga Ultra Secreta</td>
<td>0</td>
<td>Carga Ultra Secreta</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5604779045818.15F.jpg alt="carga ultra secreta" height=110 width=95></td>
</tr>
<tr>
<td>Carros</td>
<td>Cars</td>
<td>Carros</td>
<td>X</td>
<td></td>
<td>2006</td>
<td>112</td>
<td>0</td>
<td><img src=Images\5601887487981.15F.jpg alt="carros" height=110 width=95></td>
</tr>
<tr>
<td>Casablanca</td>
<td>0</td>
<td>Casablanca</td>
<td>X</td>
<td>X</td>
<td>1942</td>
<td>98</td>
<td>Clássico</td>
<td><img src=Images\5601887402908.15F.jpg alt="casablanca" height=110 width=95></td>
</tr>
<tr>
<td>Casados de Fresco</td>
<td>Just Married</td>
<td>Casados de Fresco</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5600304163354.15F.jpg alt="casados de fresco" height=110 width=95></td>
</tr>
<tr>
<td>Casamento em dose dupla</td>
<td>Smother</td>
<td>Casamento em dose dupla</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5602193345910.15F.jpg alt="casamento em dose dupla" height=110 width=95></td>
</tr>
<tr>
<td>Casei Com Uma Feiticeira</td>
<td>Bewitched</td>
<td>Casei Com Uma Feiticeira</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>98</td>
<td>0</td>
<td><img src=Images\8414533033244.15F.jpg alt="casei com uma feiticeira" height=110 width=95></td>
</tr>
<tr>
<td>Casino</td>
<td>0</td>
<td>Casino</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>178</td>
<td>Drama</td>
<td><img src=Images\3259190305397.15F.jpg alt="casino" height=110 width=95></td>
</tr>
<tr>
<td>Casino Royale</td>
<td>0</td>
<td>Casino Royale</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>139</td>
<td>Acção</td>
<td><img src=Images\8414533040587.15F.jpg alt="casino royale" height=110 width=95></td>
</tr>
<tr>
<td>Catwoman</td>
<td>0</td>
<td>Catwoman</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\7321977314505.15F.jpg alt="catwoman" height=110 width=95></td>
</tr>
<tr>
<td>Cavalgar com o Diabo</td>
<td>Ride With the Devil</td>
<td>Cavalgar com o Diabo</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>132</td>
<td>Drama</td>
<td><img src=Images\5601887432974.15F.jpg alt="cavalgar com o diabo" height=110 width=95></td>
</tr>
<tr>
<td>Cercados</td>
<td>Black Hawk Down</td>
<td>Cercados</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>138</td>
<td>Guerra</td>
<td><img src=Images\5601887435142.15F.jpg alt="cercados" height=110 width=95></td>
</tr>
<tr>
<td>Chamavam-lhe... <NAME></td>
<td>White River Kid</td>
<td>Chamavam-lhe... <NAME></td>
<td></td>
<td>X</td>
<td>1999</td>
<td>99</td>
<td>0</td>
<td><img src=Images\8420172019716.10F.jpg alt="chamavam-lhe... frei edgar" height=110 width=95></td>
</tr>
<tr>
<td>Chefe de Estado</td>
<td>Head of State</td>
<td>Chefe de Estado</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5050583003764.15F.jpg alt="chefe de estado" height=110 width=95></td>
</tr>
<tr>
<td>Chéri</td>
<td>Cheri</td>
<td>Cheri</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>88</td>
<td>Comédia</td>
<td><img src=Images\5600304213813.15F.jpg alt="cheri" height=110 width=95></td>
</tr>
<tr>
<td>Chicago</td>
<td>0</td>
<td>Chicago</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>109</td>
<td>Musical</td>
<td><img src=Images\5608652019477.15F.jpg alt="chicago" height=110 width=95></td>
</tr>
<tr>
<td>Chicken Little</td>
<td>0</td>
<td>Chicken Little</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>78</td>
<td>Animação</td>
<td><img src=Images\5601887480821.15F.jpg alt="chicken little" height=110 width=95></td>
</tr>
<tr>
<td>Chocolate</td>
<td>Chocolat</td>
<td>Chocolate</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>117</td>
<td>Comédia</td>
<td><img src=Images\5608652007795.15F.jpg alt="chocolate" height=110 width=95></td>
</tr>
<tr>
<td>Chuva de Fogo</td>
<td>Blown Away</td>
<td>Chuva de Fogo</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>121</td>
<td>Acção</td>
<td><img src=Images\5600304177016.15F.jpg alt="chuva de fogo" height=110 width=95></td>
</tr>
<tr>
<td>Cidade de Deus</td>
<td>0</td>
<td>Cidade de Deus</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>124</td>
<td>Drama</td>
<td><img src=Images\5606118101155.15F.jpg alt="cidade de deus" height=110 width=95></td>
</tr>
<tr>
<td>Cinco dias, cinco noites</td>
<td>0</td>
<td>Cinco dias, cinco noites</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5606699501528.15F.jpg alt="cinco dias, cinco noites" height=110 width=95></td>
</tr>
<tr>
<td>Cinco Minutos de Paz</td>
<td>Five Minutes Of Heaven</td>
<td>Cinco Minutos de Paz</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>90</td>
<td>Crime</td>
<td><img src=Images\5606320011785.15F.jpg alt="cinco minutos de paz" height=110 width=95></td>
</tr>
<tr>
<td>Cinema Paraíso</td>
<td>Nuovo Cinema Paradiso</td>
<td>Cinema Paraiso</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>117</td>
<td>0</td>
<td><img src=Images\5601887443666.15F.jpg alt="cinema paraiso" height=110 width=95></td>
</tr>
<tr>
<td>Click</td>
<td>0</td>
<td>Click</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>103</td>
<td>0</td>
<td><img src=Images\8414533039925.15F.jpg alt="click" height=110 width=95></td>
</tr>
<tr>
<td>Clube das Solteironas</td>
<td>Crush</td>
<td>Clube das Solteironas</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>108</td>
<td>Romance</td>
<td><img src=Images\5601887441952.15F.jpg alt="clube das solteironas" height=110 width=95></td>
</tr>
<tr>
<td>Cocoon: A Aventura dos Corais Perdidos</td>
<td>Cocoon</td>
<td>Cocoon: A Aventura dos Corais Perdidos</td>
<td>X</td>
<td></td>
<td>1985</td>
<td>118</td>
<td>Ficção Científica</td>
<td><img src=Images\5608652011914.15F.jpg alt="cocoon: a aventura dos corais perdidos" height=110 width=95></td>
</tr>
<tr>
<td>Código 46</td>
<td>Code 46</td>
<td>Codigo 46</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>90</td>
<td>Ficção Científica</td>
<td><img src=Images\5608652037532.15F.jpg alt="codigo 46" height=110 width=95></td>
</tr>
<tr>
<td>Código de Silêncio</td>
<td>Code of Silence</td>
<td>Codigo de Silencio</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>97</td>
<td>Acção</td>
<td><img src=Images\5608652020527.15F.jpg alt="codigo de silencio" height=110 width=95></td>
</tr>
<tr>
<td>Códigos de Guerra</td>
<td>Windtalkers</td>
<td>Codigos de Guerra</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>129</td>
<td>Acção</td>
<td><img src=Images\5608652016377.15F.jpg alt="codigos de guerra" height=110 width=95></td>
</tr>
<tr>
<td>Colateral</td>
<td>Collateral</td>
<td>Colateral</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\5601887467556.15F.jpg alt="colateral" height=110 width=95></td>
</tr>
<tr>
<td>Cold Mountain</td>
<td>0</td>
<td>Cold Mountain</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>148</td>
<td>Drama</td>
<td><img src=Images\5601887463565.15F.jpg alt="cold mountain" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 1: A Lagoa Azul</td>
<td>The Blue Lagoon</td>
<td>Colecao Cinemania 1: A Lagoa Azul</td>
<td>X</td>
<td>X</td>
<td>1980</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\IE3545F5A29824FAD.15F.jpg alt="colecao cinemania 1: a lagoa azul" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 1: <NAME></td>
<td>Look Who's Talking</td>
<td>Colecao Cinemania 1: Olha Quem Fala</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>92</td>
<td>Comédia</td>
<td><img src=Images\IB960D0C8236FCC0B.15F.jpg alt="colecao cinemania 1: olha quem fala" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 1: Os Caça-Fantasmas</td>
<td>Ghostbusters</td>
<td>Colecao Cinemania 1: Os Caca-Fantasmas</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\I7957A3EAB6667F22.15F.jpg alt="colecao cinemania 1: os caca-fantasmas" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 2: Espirito Selvagem</td>
<td>All the Pretty Horses</td>
<td>Colecao Cinemania 2: Espirito Selvagem</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>112</td>
<td>0</td>
<td><img src=Images\5601887424122.15F.jpg alt="colecao cinemania 2: espirito selvagem" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 2: O Fim da Aventura</td>
<td>The End of the Affair</td>
<td>Colecao Cinemania 2: O Fim da Aventura</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5601887412136.15F.jpg alt="colecao cinemania 2: o fim da aventura" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 2: Os Miseráveis</td>
<td>0</td>
<td>Colecao Cinemania 2: Os Miseraveis</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>480</td>
<td>0</td>
<td><img src=Images\5602193324083.15F.jpg alt="colecao cinemania 2: os miseraveis" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 3: Desperado</td>
<td>0</td>
<td>Colecao Cinemania 3: Desperado</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5601887452453.15F.jpg alt="colecao cinemania 3: desperado" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 3: Duro de matar</td>
<td>Half Past Dead</td>
<td>Colecao Cinemania 3: Duro de matar</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>98</td>
<td>Acção</td>
<td><img src=Images\I95D7417EE6CD566A.15F.jpg alt="colecao cinemania 3: duro de matar" height=110 width=95></td>
</tr>
<tr>
<td>Coleção Cinemania 3: O Patriota</td>
<td>The Patriot</td>
<td>Colecao Cinemania 3: O Patriota</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>158</td>
<td>Drama</td>
<td><img src=Images\5601887415830.15F.jpg alt="colecao cinemania 3: o patriota" height=110 width=95></td>
</tr>
<tr>
<td>Colete de Forças</td>
<td>The Jacket</td>
<td>Colete de Forcas</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887475292.15F.jpg alt="colete de forcas" height=110 width=95></td>
</tr>
<tr>
<td>Colisão</td>
<td>Crash</td>
<td>Colisao</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5600304163972.15F.jpg alt="colisao" height=110 width=95></td>
</tr>
<tr>
<td>Colombiana</td>
<td>0</td>
<td>Colombiana</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>108</td>
<td>Acção</td>
<td><img src=Images\5601887574513.15F.jpg alt="colombiana" height=110 width=95></td>
</tr>
<tr>
<td>Columbo: Assacinato</td>
<td>0</td>
<td>Columbo: Assacinato</td>
<td>X</td>
<td>X</td>
<td>1971</td>
<td>725</td>
<td>Crime</td>
<td><img src=Images\025192160738F.jpg alt="columbo: assacinato" height=110 width=95></td>
</tr>
<tr>
<td>Comando</td>
<td>Commando</td>
<td>Comando</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>87</td>
<td>0</td>
<td><img src=Images\5608652005357.15F.jpg alt="comando" height=110 width=95></td>
</tr>
<tr>
<td>Combate ao Passado</td>
<td>Linewatch</td>
<td>Combate ao Passado</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>90</td>
<td>Drama</td>
<td><img src=Images\043396240766F.jpg alt="combate ao passado" height=110 width=95></td>
</tr>
<tr>
<td>Comboio em Fuga</td>
<td>Runaway Train</td>
<td>Comboio em Fuga</td>
<td></td>
<td>X</td>
<td>1985</td>
<td>106</td>
<td>Acção</td>
<td><img src=Images\5600304180276.15F.jpg alt="comboio em fuga" height=110 width=95></td>
</tr>
<tr>
<td>Como Assaltar Um Banco</td>
<td>How To Rob A Bank</td>
<td>Como Assaltar Um Banco</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>78</td>
<td>Drama</td>
<td><img src=Images\5600304207065.15F.jpg alt="como assaltar um banco" height=110 width=95></td>
</tr>
<tr>
<td>Como Cães e Gatos</td>
<td>Cats & Dogs</td>
<td>Como Caes e Gatos</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\7321919212531.15F.jpg alt="como caes e gatos" height=110 width=95></td>
</tr>
<tr>
<td>Comprometidos</td>
<td>Commited</td>
<td>Comprometidos</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5608652010573.15F.jpg alt="comprometidos" height=110 width=95></td>
</tr>
<tr>
<td>Compromisso de Honra</td>
<td>Rules of Engagement</td>
<td>Compromisso de Honra</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>127</td>
<td>Drama</td>
<td><img src=Images\5602193304900.15F.jpg alt="compromisso de honra" height=110 width=95></td>
</tr>
<tr>
<td>Confiança</td>
<td>Confidence</td>
<td>Confianca</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\5608652021500.15F.jpg alt="confianca" height=110 width=95></td>
</tr>
<tr>
<td>Confissões de Uma Mente Perigosa</td>
<td>Confessions of a Dangerous Mind</td>
<td>Confissoes de Uma Mente Perigosa</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>109</td>
<td>Drama</td>
<td><img src=Images\5600304160278.15F.jpg alt="confissoes de uma mente perigosa" height=110 width=95></td>
</tr>
<tr>
<td>Conhece Joe Black?</td>
<td>Meet Joe Black</td>
<td>Conhece Joe Black?</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>173</td>
<td>Drama</td>
<td><img src=Images\3259190353312.15F.jpg alt="conhece joe black?" height=110 width=95></td>
</tr>
<tr>
<td>Conspiração Mortifera</td>
<td>Proximity</td>
<td>Conspiracao Mortifera</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5604779041902.15F.jpg alt="conspiracao mortifera" height=110 width=95></td>
</tr>
<tr>
<td>Conspiração no Pentágono</td>
<td>Ignition</td>
<td>Conspiracao no Pentagono</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5608652010443.15F.jpg alt="conspiracao no pentagono" height=110 width=95></td>
</tr>
<tr>
<td>Contado ninguém Acredita</td>
<td>Stranger Than Fiction</td>
<td>Contado ninguem Acredita</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5608652030892.15F.jpg alt="contado ninguem acredita" height=110 width=95></td>
</tr>
<tr>
<td>Cop Land - Zona Exclusiva</td>
<td>Cop Land</td>
<td>Cop Land - Zona Exclusiva</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>101</td>
<td>Crime</td>
<td><img src=Images\5600304161145.15F.jpg alt="cop land - zona exclusiva" height=110 width=95></td>
</tr>
<tr>
<td>Corações Solitários</td>
<td>Lonely Hearts</td>
<td>Coracoes Solitarios</td>
<td>X</td>
<td>X</td>
<td>1982</td>
<td>103</td>
<td>Drama</td>
<td><img src=Images\5602193345583.15F.jpg alt="coracoes solitarios" height=110 width=95></td>
</tr>
<tr>
<td>Coragem Debaixo de Fogo</td>
<td>Courage Under Fire</td>
<td>Coragem Debaixo de Fogo</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>112</td>
<td>Acção</td>
<td><img src=Images\5600304197229.15F.jpg alt="coragem debaixo de fogo" height=110 width=95></td>
</tr>
<tr>
<td>Corrida para a montanha mágica</td>
<td>Race to Witch Mountain</td>
<td>Corrida para a montanha magica</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>94</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887538089.15F.jpg alt="corrida para a montanha magica" height=110 width=95></td>
</tr>
<tr>
<td>Corrigindo Beethoven</td>
<td>Copying Beethoven</td>
<td>Corrigindo Beethoven</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5608652030458.15F.jpg alt="corrigindo beethoven" height=110 width=95></td>
</tr>
<tr>
<td>Corrupção</td>
<td>0</td>
<td>Corrupcao</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\5602831084522.15F.jpg alt="corrupcao" height=110 width=95></td>
</tr>
<tr>
<td>Crank - Veneno No Sangue</td>
<td>Crank</td>
<td>Crank - Veneno No Sangue</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>84</td>
<td>Acção</td>
<td><img src=Images\5608652030212.15F.jpg alt="crank - veneno no sangue" height=110 width=95></td>
</tr>
<tr>
<td>Crepúsculo</td>
<td>Twilight</td>
<td>Crepusculo</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\5601887532216.15F.jpg alt="crepusculo" height=110 width=95></td>
</tr>
<tr>
<td>Criatura prefeita</td>
<td>Perfect Creature</td>
<td>Criatura prefeita</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>84</td>
<td>Horror</td>
<td><img src=Images\5600304196895.15F.jpg alt="criatura prefeita" height=110 width=95></td>
</tr>
<tr>
<td>Crime Em Primeiro Grau</td>
<td>High Crimes</td>
<td>Crime Em Primeiro Grau</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>111</td>
<td>Drama</td>
<td><img src=Images\5608652016995.15F.jpg alt="crime em primeiro grau" height=110 width=95></td>
</tr>
<tr>
<td>Crimes no Paraíso</td>
<td>Stone Cold</td>
<td>Crimes no Paraiso</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>83</td>
<td>Drama</td>
<td><img src=Images\8414533031356.15F.jpg alt="crimes no paraiso" height=110 width=95></td>
</tr>
<tr>
<td>Crimes ocultos</td>
<td>The Murdoch Mysteries</td>
<td>Crimes ocultos</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>95</td>
<td>Crime</td>
<td><img src=Images\5604779059297.15F.jpg alt="crimes ocultos" height=110 width=95></td>
</tr>
<tr>
<td>Crocodilo Dundee em Los Angeles</td>
<td>Crocodile Dundee in Los Angeles</td>
<td>Crocodilo Dundee em Los Angeles</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\5602193307444.15F.jpg alt="crocodilo dundee em los angeles" height=110 width=95></td>
</tr>
<tr>
<td>Crueldade Intolerável</td>
<td>Intolerable Cruelty</td>
<td>Crueldade Intoleravel</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5050582068207.15F.jpg alt="crueldade intoleravel" height=110 width=95></td>
</tr>
<tr>
<td>CSI 2: Crime Sob Investigação (1.5 a 1.8)</td>
<td>0</td>
<td>CSI 2: Crime Sob Investigacao (1.5 a 1.8)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>172</td>
<td>Drama</td>
<td><img src=Images\IA337C443A658A88F.15F.jpg alt="csi 2: crime sob investigacao (1.5 a 1.8)" height=110 width=95></td>
</tr>
<tr>
<td>CSI 3: Crime Sob Investigação (1.9 a1.12)</td>
<td>0</td>
<td>CSI 3: Crime Sob Investigacao (1.9 a1.12)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>172</td>
<td>Drama</td>
<td><img src=Images\IDADB90322FB0C0D5.15F.jpg alt="csi 3: crime sob investigacao (1.9 a1.12)" height=110 width=95></td>
</tr>
<tr>
<td>CSI 5: Crime Sob Investigação (1.17 a 1.20)</td>
<td>0</td>
<td>CSI 5: Crime Sob Investigacao (1.17 a 1.20)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>172</td>
<td>Drama</td>
<td><img src=Images\IE3931F3AF864BCB7.15F.jpg alt="csi 5: crime sob investigacao (1.17 a 1.20)" height=110 width=95></td>
</tr>
<tr>
<td>CSI 6: Crime Sob Investigação (1.21 a 1.23)</td>
<td>0</td>
<td>CSI 6: Crime Sob Investigacao (1.21 a 1.23)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>129</td>
<td>Drama</td>
<td><img src=Images\I458B66BEE10A8E62.15F.jpg alt="csi 6: crime sob investigacao (1.21 a 1.23)" height=110 width=95></td>
</tr>
<tr>
<td>CSI: Crime Sob Investigação (1.1 a 1.4)</td>
<td>0</td>
<td>CSI: Crime Sob Investigacao (1.1 a 1.4)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>172</td>
<td>Drama</td>
<td><img src=Images\IFC4DFDDEBD6406AA.15F.jpg alt="csi: crime sob investigacao (1.1 a 1.4)" height=110 width=95></td>
</tr>
<tr>
<td>CSI: Crime Sob Investigação (1.13 a 1.16)</td>
<td>0</td>
<td>CSI: Crime Sob Investigacao (1.13 a 1.16)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>172</td>
<td>Drama</td>
<td><img src=Images\I4B8F905FA402887B.15F.jpg alt="csi: crime sob investigacao (1.13 a 1.16)" height=110 width=95></td>
</tr>
<tr>
<td>CSI: Crime Sob Investigação - Segunda Série: Episódios 2.1 - 2.12</td>
<td>CSI: Crime Scene Investigation - Season 2: Part 1</td>
<td>CSI: Crime Sob Investigacao - Segunda Serie: Episodios 2.1 - 2.12</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>516</td>
<td>Televisão</td>
<td><img src=Images\5608652027083.15F.jpg alt="csi: crime sob investigacao - segunda serie: episodios 2.1 - 2.12" height=110 width=95></td>
</tr>
<tr>
<td>CSI: Crime Sob Investigação - Segunda Série: Episódios 2.13 - 2.23</td>
<td>CSI: Crime Scene Investigation - Season 2: Part 2</td>
<td>CSI: Crime Sob Investigacao - Segunda Serie: Episodios 2.13 - 2.23</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>473</td>
<td>Drama</td>
<td><img src=Images\5608652027465.15F.jpg alt="csi: crime sob investigacao - segunda serie: episodios 2.13 - 2.23" height=110 width=95></td>
</tr>
<tr>
<td>CSI: Crime Sob Investigação - Terceira Série: Episódios 3.1 - 3.12</td>
<td>CSI: Crime Scene Investigation - Season 3: Part 1</td>
<td>CSI: Crime Sob Investigacao - Terceira Serie: Episodios 3.1 - 3.12</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>516</td>
<td>Televisão</td>
<td><img src=Images\5608652027755.15F.jpg alt="csi: crime sob investigacao - terceira serie: episodios 3.1 - 3.12" height=110 width=95></td>
</tr>
<tr>
<td>Culpa Humana</td>
<td>The Human Stain</td>
<td>Culpa Humana</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887459964.15F.jpg alt="culpa humana" height=110 width=95></td>
</tr>
<tr>
<td>Cúmplices de um Crime</td>
<td>0</td>
<td>Cumplices de um Crime</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>95</td>
<td>0</td>
<td><img src=Images\5602193314640.15F.jpg alt="cumplices de um crime" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td>Cyrano de Begerac</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>135</td>
<td>Romance</td>
<td><img src=Images\I7833B844C9CAA486.15F.jpg alt="cyrano de begerac" height=110 width=95></td>
</tr>
<tr>
<td>D-Tox</td>
<td>0</td>
<td>D-Tox</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>92</td>
<td>Drama</td>
<td><img src=Images\3259190603639.15F.jpg alt="d-tox" height=110 width=95></td>
</tr>
<tr>
<td>Da Rússia com Amor</td>
<td>Birthday Girl</td>
<td>Da Russia com Amor</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5608652012331.15F.jpg alt="da russia com amor" height=110 width=95></td>
</tr>
<tr>
<td>Danças com Lobos</td>
<td>Dances With Wolves</td>
<td>Dancas com Lobos</td>
<td></td>
<td>X</td>
<td>1990</td>
<td>227</td>
<td>Western</td>
<td><img src=Images\5601887459278.15F.jpg alt="dancas com lobos" height=110 width=95></td>
</tr>
<tr>
<td>Danos Colaterais</td>
<td>Collateral Damage</td>
<td>Danos Colaterais</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>105</td>
<td>0</td>
<td><img src=Images\7321976213243.15F.jpg alt="danos colaterais" height=110 width=95></td>
</tr>
<tr>
<td>Dartacão - um por todos e todos por um</td>
<td>0</td>
<td>Dartacao - um por todos e todos por um</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M17.15F.jpg alt="dartacao - um por todos e todos por um" height=110 width=95></td>
</tr>
<tr>
<td>De Férias com Timon & Pumba</td>
<td>On Holiday with Timon & Pumba</td>
<td>De Ferias com Timon & Pumba</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>63</td>
<td>Animação</td>
<td><img src=Images\5601887466634.15F.jpg alt="de ferias com timon & pumba" height=110 width=95></td>
</tr>
<tr>
<td>De malas aviadas</td>
<td>New in Town</td>
<td>De malas aviadas</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5602193348744.15F.jpg alt="de malas aviadas" height=110 width=95></td>
</tr>
<tr>
<td>De Olhos Bem Fechados</td>
<td>Eyes Wide Shut</td>
<td>De Olhos Bem Fechados</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>153</td>
<td>Drama</td>
<td><img src=Images\5601887404810.15F.jpg alt="de olhos bem fechados" height=110 width=95></td>
</tr>
<tr>
<td>De Volta para o Inferno</td>
<td>Uncommon Valor</td>
<td>De Volta para o Inferno</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>105</td>
<td>Guerra</td>
<td><img src=Images\7896012216101.23F.jpg alt="de volta para o inferno" height=110 width=95></td>
</tr>
<tr>
<td>Dead Man Walking A Ultima Caminhada</td>
<td>Dead Man Walking</td>
<td>Dead Man Walking A Ultima Caminhada</td>
<td></td>
<td>X</td>
<td>1995</td>
<td>122</td>
<td>Drama</td>
<td><img src=Images\I3C2F131CC111C0E6.15F.jpg alt="dead man walking a ultima caminhada" height=110 width=95></td>
</tr>
<tr>
<td>Dempsey e Makepeace: Série 3</td>
<td>Dempsey & Makepeace</td>
<td>Dempsey e Makepeace: Serie 3</td>
<td></td>
<td>X</td>
<td>1986</td>
<td>520</td>
<td>Acção</td>
<td><img src=Images\5602193322119.15F.jpg alt="dempsey e makepeace: serie 3" height=110 width=95></td>
</tr>
<tr>
<td>Desaparecida!</td>
<td>The Lady Vanishes</td>
<td>Desaparecida!</td>
<td>X</td>
<td>X</td>
<td>1938</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I5E94B9E5E1FF381E.15F.jpg alt="desaparecida!" height=110 width=95></td>
</tr>
<tr>
<td>Desaparecidas</td>
<td>The Missing</td>
<td>Desaparecidas</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>131</td>
<td>Drama</td>
<td><img src=Images\5601887462100.15F.jpg alt="desaparecidas" height=110 width=95></td>
</tr>
<tr>
<td>Desaparecido na América</td>
<td>Missing in America</td>
<td>Desaparecido na America</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>102</td>
<td>Drama</td>
<td><img src=Images\5606320006613.15F.jpg alt="desaparecido na america" height=110 width=95></td>
</tr>
<tr>
<td>Desesperadamente Procurando Susana</td>
<td>Desperately Seeking Susan</td>
<td>Desesperadamente Procurando Susana</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5608652003834.15F.jpg alt="desesperadamente procurando susana" height=110 width=95></td>
</tr>
<tr>
<td>Destruir Depois de Ler</td>
<td>Burn After Reading</td>
<td>Destruir Depois de Ler</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5600304201735.15F.jpg alt="destruir depois de ler" height=110 width=95></td>
</tr>
<tr>
<td>Detenção de risco</td>
<td>Safe House</td>
<td>Detencao de risco</td>
<td></td>
<td>X</td>
<td>2012</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\5601887578528.15F.jpg alt="detencao de risco" height=110 width=95></td>
</tr>
<tr>
<td>Detenção Secreta</td>
<td>Rendition</td>
<td>Detencao Secreta</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\5602193342070.15F.jpg alt="detencao secreta" height=110 width=95></td>
</tr>
<tr>
<td>Dia D: A Caminho Da Vitória</td>
<td>0</td>
<td>Dia D: A Caminho Da Vitoria</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\5602841044165F.jpg alt="dia d: a caminho da vitoria" height=110 width=95></td>
</tr>
<tr>
<td>Dia e noite</td>
<td>Knight And Day</td>
<td>Dia e noite</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>117</td>
<td>Acção</td>
<td><img src=Images\5600304216944.15F.jpg alt="dia e noite" height=110 width=95></td>
</tr>
<tr>
<td>Diamante de Sangue</td>
<td>Blood Diamond</td>
<td>Diamante de Sangue</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>137</td>
<td>Acção</td>
<td><img src=Images\7321974117628.15F.jpg alt="diamante de sangue" height=110 width=95></td>
</tr>
<tr>
<td>Diário de um escândalo</td>
<td>Notes on a Scandal</td>
<td>Diario de um escandalo</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>88</td>
<td>Drama</td>
<td><img src=Images\5600304176460.15F.jpg alt="diario de um escandalo" height=110 width=95></td>
</tr>
<tr>
<td>Dias de Futebol</td>
<td>Días de Fútbol</td>
<td>Dias de Futebol</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>109</td>
<td>Comédia</td>
<td><img src=Images\5608652026413.15F.jpg alt="dias de futebol" height=110 width=95></td>
</tr>
<tr>
<td>Dias de Glória</td>
<td>Indigènes</td>
<td>Dias de Gloria</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>118</td>
<td>Guerra</td>
<td><img src=Images\5608652031615.15F.jpg alt="dias de gloria" height=110 width=95></td>
</tr>
<tr>
<td>Dinheiro Marcado</td>
<td>Run for the Money</td>
<td>Dinheiro Marcado</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5601887201174.15F.jpg alt="dinheiro marcado" height=110 width=95></td>
</tr>
<tr>
<td>Dinheiro Vivo</td>
<td>Mad Money</td>
<td>Dinheiro Vivo</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>104</td>
<td>0</td>
<td><img src=Images\013138000095F.jpg alt="dinheiro vivo" height=110 width=95></td>
</tr>
<tr>
<td>Dinossauro</td>
<td>Dinosaur</td>
<td>Dinossauro</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>79</td>
<td>Animação</td>
<td><img src=Images\5601887421640.15F.jpg alt="dinossauro" height=110 width=95></td>
</tr>
<tr>
<td>Discovery - O Guia Completo: Terra Em Erupção</td>
<td>0</td>
<td>Discovery - O Guia Completo: Terra Em Erupcao</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M18.15F.jpg alt="discovery - o guia completo: terra em erupcao" height=110 width=95></td>
</tr>
<tr>
<td>Disposta a Tudo</td>
<td>To Die For</td>
<td>Disposta a Tudo</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>102</td>
<td>0</td>
<td><img src=Images\5606118101865.15F.jpg alt="disposta a tudo" height=110 width=95></td>
</tr>
<tr>
<td>Divórcio de Milhões</td>
<td>Serving Sara</td>
<td>Divorcio de Milhoes</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5608652018470.15F.jpg alt="divorcio de milhoes" height=110 width=95></td>
</tr>
<tr>
<td>Dk Enciclopédia Visual - A Máquina Humana</td>
<td>0</td>
<td>Dk Enciclopedia Visual - A Maquina Humana</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M19.15F.jpg alt="dk enciclopedia visual - a maquina humana" height=110 width=95></td>
</tr>
<tr>
<td>Dk Enciclopédia Visual - Tragédias Naturais</td>
<td>0</td>
<td>Dk Enciclopedia Visual - Tragedias Naturais</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M20.15F.jpg alt="dk enciclopedia visual - tragedias naturais" height=110 width=95></td>
</tr>
<tr>
<td>Dois Destinos</td>
<td>The Family Man</td>
<td>Dois Destinos</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>126</td>
<td>Comédia</td>
<td><img src=Images\5601887422074.15F.jpg alt="dois destinos" height=110 width=95></td>
</tr>
<tr>
<td>Dois Estranhos, Um Casamento</td>
<td>The Pleasure of Your Company</td>
<td>Dois Estranhos, Um Casamento</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>88</td>
<td>Comédia</td>
<td><img src=Images\5600304194686.15F.jpg alt="dois estranhos, um casamento" height=110 width=95></td>
</tr>
<tr>
<td>Dom Quixote</td>
<td>Don Quixote</td>
<td>Dom Quixote</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>139</td>
<td>0</td>
<td><img src=Images\5601887463206.15F.jpg alt="dom quixote" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>126</td>
<td>Crime</td>
<td><img src=Images\5602193316217.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5060116724097.4F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Dormindo com o Inimigo</td>
<td>Sleeping With the Enemy</td>
<td>Dormindo com o Inimigo</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>100</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652008235.15F.jpg alt="dormindo com o inimigo" height=110 width=95></td>
</tr>
<tr>
<td>Doze desafios</td>
<td>12 Rounds</td>
<td>Doze desafios</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>108</td>
<td>Acção</td>
<td><img src=Images\5600304209694.15F.jpg alt="doze desafios" height=110 width=95></td>
</tr>
<tr>
<td>Dr. Dolittle</td>
<td>0</td>
<td>Dr. Dolittle</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>81</td>
<td>Comédia</td>
<td><img src=Images\5600304162685.15F.jpg alt="dr. dolittle" height=110 width=95></td>
</tr>
<tr>
<td>Dr. Dolittle 2</td>
<td>0</td>
<td>Dr. Dolittle 2</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5600304162753.15F.jpg alt="dr. dolittle 2" height=110 width=95></td>
</tr>
<tr>
<td>Dr. T e as Mulheres</td>
<td>Dr. T & the Women</td>
<td>Dr. T e as Mulheres</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>140</td>
<td>0</td>
<td><img src=Images\9771806952312.23F.jpg alt="dr. t e as mulheres" height=110 width=95></td>
</tr>
<tr>
<td>Dragão Vermelho</td>
<td>Red Dragon</td>
<td>Dragao Vermelho</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>119</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I33AAA95576D585E2.15F.jpg alt="dragao vermelho" height=110 width=95></td>
</tr>
<tr>
<td>Dreamgirls</td>
<td>0</td>
<td>Dreamgirls</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>125</td>
<td>Drama</td>
<td><img src=Images\5601887493418.15F.jpg alt="dreamgirls" height=110 width=95></td>
</tr>
<tr>
<td>Duas irmães e o rei</td>
<td>0</td>
<td>Duas irmaes e o rei</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\043396215269F.jpg alt="duas irmaes e o rei" height=110 width=95></td>
</tr>
<tr>
<td>Duas Obras Primas de Fritz Lang</td>
<td>0</td>
<td>Duas Obras Primas de Fritz Lang</td>
<td>X</td>
<td>X</td>
<td>1931</td>
<td>226</td>
<td>Clássico</td>
<td><img src=Images\5606118101667.15F.jpg alt="duas obras primas de fritz lang" height=110 width=95></td>
</tr>
<tr>
<td>Duas Vidas</td>
<td><NAME></td>
<td>Duas Vidas</td>
<td>X</td>
<td>X</td>
<td>2012</td>
<td>95</td>
<td>Drama</td>
<td><img src=Images\3700782600722.8F.jpg alt="duas vidas" height=110 width=95></td>
</tr>
<tr>
<td>Duas Vidas e um Rio</td>
<td>A River Runs Through It</td>
<td>Duas Vidas e um Rio</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>118</td>
<td>0</td>
<td><img src=Images\5608652021951.15F.jpg alt="duas vidas e um rio" height=110 width=95></td>
</tr>
<tr>
<td>Duelo de Titãs</td>
<td>Remember the Titans</td>
<td>Duelo de Titas</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5601887422999.15F.jpg alt="duelo de titas" height=110 width=95></td>
</tr>
<tr>
<td>Duelo Imortal 3</td>
<td>Highlander III: The Sorcerer</td>
<td>Duelo Imortal 3</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>95</td>
<td>Aventura</td>
<td><img src=Images\5602193330428.15F.jpg alt="duelo imortal 3" height=110 width=95></td>
</tr>
<tr>
<td>Dumbo</td>
<td>0</td>
<td>Dumbo</td>
<td>X</td>
<td>X</td>
<td>1941</td>
<td>64</td>
<td>Animação</td>
<td><img src=Images\5601887424498.15F.jpg alt="dumbo" height=110 width=95></td>
</tr>
<tr>
<td>Dupla sedução</td>
<td>Duplicity</td>
<td>Dupla seducao</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>125</td>
<td>Crime</td>
<td><img src=Images\5050582697896.15F.jpg alt="dupla seducao" height=110 width=95></td>
</tr>
<tr>
<td>Duplex</td>
<td>0</td>
<td>Duplex</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>85</td>
<td>Comédia</td>
<td><img src=Images\5608652024952.15F.jpg alt="duplex" height=110 width=95></td>
</tr>
<tr>
<td>Duplo Risco</td>
<td>Double Jeopardy</td>
<td>Duplo Risco</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>101</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887417285.15F.jpg alt="dup<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Duro Amor</td>
<td>Gigli</td>
<td>Duro Amor</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>116</td>
<td>Comédia</td>
<td><img src=Images\5601887459056.15F.jpg alt="duro amor" height=110 width=95></td>
</tr>
<tr>
<td>É Agora ou Nunca</td>
<td>The Good Girl</td>
<td>E Agora ou Nunca</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\I9508A7782F4CA91F.15F.jpg alt="e agora ou nunca" height=110 width=95></td>
</tr>
<tr>
<td>E.T. O Extraterrestre</td>
<td>E.T. The Extra-Terrestrial</td>
<td>E.T. O Extraterrestre</td>
<td></td>
<td>X</td>
<td>1982</td>
<td>115</td>
<td>Família</td>
<td><img src=Images\3259190344891.15F.jpg alt="e.t. o extraterrestre" height=110 width=95></td>
</tr>
<tr>
<td>Eclipse</td>
<td>The Twilight Saga: Eclipse</td>
<td>Eclipse</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>125</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887566105.15F.jpg alt="eclipse" height=110 width=95></td>
</tr>
<tr>
<td>Edison</td>
<td>0</td>
<td>Edison</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\5050582432473.15F.jpg alt="edison" height=110 width=95></td>
</tr>
<tr>
<td>Efeito Borboleta</td>
<td>The Butterfly Effect</td>
<td>Efeito Borboleta</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>115</td>
<td>0</td>
<td><img src=Images\5601887465576.15F.jpg alt="efeito borboleta" height=110 width=95></td>
</tr>
<tr>
<td>El Cid - A Lenda</td>
<td>El Cid - La leyenda</td>
<td>El Cid - A Lenda</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>80</td>
<td>0</td>
<td><img src=Images\5601887464784.15F.jpg alt="el cid - a lenda" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>She's All That</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5608652003148.15F.jpg alt="ela e demais" height=110 width=95></td>
</tr>
<tr>
<td>Ele não está assim tão interessado</td>
<td>He's Just Not That Into You</td>
<td>Ele nao esta assim tao interessado</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>129</td>
<td>Comédia</td>
<td><img src=Images\5602193343480.15F.jpg alt="ele nao esta assim tao interessado" height=110 width=95></td>
</tr>
<tr>
<td>Elektra</td>
<td>0</td>
<td>Elektra</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\5608652026741.15F.jpg alt="elektra" height=110 width=95></td>
</tr>
<tr>
<td>Elizabeth</td>
<td>0</td>
<td>Elizabeth</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5601887427673.15F.jpg alt="elizabeth" height=110 width=95></td>
</tr>
<tr>
<td>Ella Encantada</td>
<td>Ella Enchanted</td>
<td>Ella Encantada</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>92</td>
<td>Comédia</td>
<td><img src=Images\5600304160353.15F.jpg alt="ella encantada" height=110 width=95></td>
</tr>
<tr>
<td>Elvis Deu de Fuga</td>
<td>Elvis Has Left the Building</td>
<td>Elvis Deu de Fuga</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\5608652026888.15F.jpg alt="elvis deu de fuga" height=110 width=95></td>
</tr>
<tr>
<td>Em Bicos de Pés</td>
<td>Tiptoes</td>
<td>Em Bicos de Pes</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>86</td>
<td>0</td>
<td><img src=Images\5606118101179.15F.jpg alt="em bicos de pes" height=110 width=95></td>
</tr>
<tr>
<td>Em Busca da Esmeralda Perdida</td>
<td>Romancing the Stone</td>
<td>Em Busca da Esmeralda Perdida</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>101</td>
<td>Romance</td>
<td><img src=Images\5600304162876.15F.jpg alt="em busca da esmeralda perdida" height=110 width=95></td>
</tr>
<tr>
<td>Em Busca da Felicidade</td>
<td>The Pursuit of Happyness</td>
<td>Em Busca da Felicidade</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\8414533042383.15F.jpg alt="em busca da felicidade" height=110 width=95></td>
</tr>
<tr>
<td>Em Busca de Um Milagre</td>
<td><NAME></td>
<td>Em Busca de Um Milagre</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>94</td>
<td>Drama</td>
<td><img src=Images\I3AF4331217C19949.15F.jpg alt="em busca de um milagre" height=110 width=95></td>
</tr>
<tr>
<td>Em Defesa da Honra</td>
<td>Hart's War</td>
<td>Em Defesa da Honra</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>117</td>
<td>Acção</td>
<td><img src=Images\5600304176781.15F.jpg alt="em defesa da honra" height=110 width=95></td>
</tr>
<tr>
<td>Em Defesa de Sua Magestade</td>
<td>Shanghai Knights</td>
<td>Em Defesa de Sua Magestade</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>114</td>
<td>0</td>
<td><img src=Images\5601887451609.15F.jpg alt="em defesa de sua magestade" height=110 width=95></td>
</tr>
<tr>
<td>Em Nome do Rei: Ascensão e Luta</td>
<td>In the Name of the King: A Dungeon Siege Tale</td>
<td>Em Nome do Rei: Ascensao e Luta</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\5608652034296.15F.jpg alt="em nome do rei: ascensao e luta" height=110 width=95></td>
</tr>
<tr>
<td>Ema</td>
<td>Emma</td>
<td>Ema</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>116</td>
<td>Comédia</td>
<td><img src=Images\5600304176248.15F.jpg alt="ema" height=110 width=95></td>
</tr>
<tr>
<td>Embriagado de Amor</td>
<td>Punch-Drunk Love</td>
<td>Embriagado de Amor</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\5601887461134.15F.jpg alt="embriagado de amor" height=110 width=95></td>
</tr>
<tr>
<td>Encontro em Manhattan</td>
<td>Maid in Manhattan</td>
<td>Encontro em Manhattan</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5601887454853.15F.jpg alt="encontro em manhattan" height=110 width=95></td>
</tr>
<tr>
<td>Encurralada</td>
<td>Trapped</td>
<td>Encurralada</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>101</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887450282.15F.jpg alt="encurralada" height=110 width=95></td>
</tr>
<tr>
<td>Enquanto dormias</td>
<td>While You Were Sleeping</td>
<td>Enquanto dormias</td>
<td></td>
<td>X</td>
<td>1995</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5601887480609.15F.jpg alt="enquanto dormias" height=110 width=95></td>
</tr>
<tr>
<td>Ensaio sobre a cegueira</td>
<td>Blindness</td>
<td>Ensaio sobre a cegueira</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>116</td>
<td>Drama</td>
<td><img src=Images\5600304208536.15F.jpg alt="ensaio sobre a cegueira" height=110 width=95></td>
</tr>
<tr>
<td>Entrelaçados</td>
<td>Tangled</td>
<td>Entrelacados</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>97</td>
<td>Animação</td>
<td><img src=Images\5601887568659.15F.jpg alt="entrelacados" height=110 width=95></td>
</tr>
<tr>
<td>Era Uma Vez no México</td>
<td>Once Upon a Time in Mexico</td>
<td>Era Uma Vez no Mexico</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>98</td>
<td>Acção</td>
<td><img src=Images\8414533024532.15F.jpg alt="era uma vez no mexico" height=110 width=95></td>
</tr>
<tr>
<td>Era Uma Vez Um Rapaz</td>
<td>About a Boy</td>
<td>Era Uma Vez Um Rapaz</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>97</td>
<td>Drama</td>
<td><img src=Images\3259190397095.15F.jpg alt="era uma vez um rapaz" height=110 width=95></td>
</tr>
<tr>
<td>Era uma vez... um pai</td>
<td>Jersey Girl</td>
<td>Era uma vez... um pai</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>0</td>
<td>0</td>
<td><img src=Images\5601887465507.15F.jpg alt="era uma vez... um pai" height=110 width=95></td>
</tr>
<tr>
<td>Eram Todos Bons Rapazes</td>
<td>Very Bad Things</td>
<td>Eram Todos Bons Rapazes</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>96</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193302630.15F.jpg alt="eram todos bons rapazes" height=110 width=95></td>
</tr>
<tr>
<td>Eraser</td>
<td>0</td>
<td>Eraser</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>110</td>
<td>Acção</td>
<td><img src=Images\5606376283280.15F.jpg alt="eraser" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>126</td>
<td>Drama</td>
<td><img src=Images\5601887413010.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>És o maior, meu</td>
<td>I Love You, Man</td>
<td>Es o maior, meu</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5601887539475.15F.jpg alt="es o maior, meu" height=110 width=95></td>
</tr>
<tr>
<td>Escândalos do Candidato</td>
<td>Primary Colors</td>
<td>Escandalos do Candidato</td>
<td>X</td>
<td></td>
<td>1998</td>
<td>137</td>
<td>Drama</td>
<td><img src=Images\5601887461738.15F.jpg alt="escandalos do candidato" height=110 width=95></td>
</tr>
<tr>
<td>Escola de Criminosos</td>
<td>Animal Factory</td>
<td>Escola de Criminosos</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>90</td>
<td>Drama</td>
<td><img src=Images\5602193344524.15F.jpg alt="escola de criminosos" height=110 width=95></td>
</tr>
<tr>
<td>Escola de Sedução</td>
<td>School for Seduction</td>
<td>Escola de Seducao</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5600304160070.15F.jpg alt="escola de seducao" height=110 width=95></td>
</tr>
<tr>
<td>Espangles</td>
<td>Spanglish</td>
<td>Espangles</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>126</td>
<td>Romance</td>
<td><img src=Images\8414533029421.15F.jpg alt="espangles" height=110 width=95></td>
</tr>
<tr>
<td>Espíritos Inquietos</td>
<td>Stir of Echoes</td>
<td>Espiritos Inquietos</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652005043.15F.jpg alt="espiritos inquietos" height=110 width=95></td>
</tr>
<tr>
<td>Esquece...e siga</td>
<td>Get Over It</td>
<td>Esquece...e siga</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>83</td>
<td>Comédia</td>
<td><img src=Images\IE9C2EE01C8FB30B1.15F.jpg alt="esquece...e siga" height=110 width=95></td>
</tr>
<tr>
<td>Está Tudo Louco!</td>
<td>Rat Race</td>
<td>Esta Tudo Louco!</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>107</td>
<td>Comédia</td>
<td><img src=Images\5601887439270.15F.jpg alt="esta tudo louco!" height=110 width=95></td>
</tr>
<tr>
<td>Estado de Sítio</td>
<td>The Siege</td>
<td>Estado de Sitio</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>111</td>
<td>Acção</td>
<td><img src=Images\5608652002127.15F.jpg alt="estado de sitio" height=110 width=95></td>
</tr>
<tr>
<td>Este País Não é Para Velhos</td>
<td>No Country for old Men</td>
<td>Este Pais Nao e Para Velhos</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>118</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887523160.15F.jpg alt="este pais nao e para velhos" height=110 width=95></td>
</tr>
<tr>
<td>Estranha aliança</td>
<td>0</td>
<td>Estranha alianca</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>94</td>
<td>Acção</td>
<td><img src=Images\5050070020120.4F.jpg alt="estranha alianca" height=110 width=95></td>
</tr>
<tr>
<td>Estranhas Experiências</td>
<td>Rough Magic</td>
<td>Estranhas Experiencias</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>60</td>
<td>0</td>
<td><img src=Images\5608652022200.15F.jpg alt="estranhas experiencias" height=110 width=95></td>
</tr>
<tr>
<td>Estranhos</td>
<td>Unknown</td>
<td>Estranhos</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>82</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304173827.15F.jpg alt="estranhos" height=110 width=95></td>
</tr>
<tr>
<td>Estranhos Companheiros De Cama</td>
<td>Strange Bedfellows</td>
<td>Estranhos Companheiros De Cama</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>95</td>
<td>0</td>
<td><img src=Images\5600304167079.15F.jpg alt="estranhos companheiros de cama" height=110 width=95></td>
</tr>
<tr>
<td>Estranhos em casa</td>
<td>Winter Passing</td>
<td>Estranhos em casa</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\024543251187F.jpg alt="estranhos em casa" height=110 width=95></td>
</tr>
<tr>
<td>Eu, Robot</td>
<td>I, Robot</td>
<td>Eu, Robot</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>110</td>
<td>0</td>
<td><img src=Images\5608652024983.15F.jpg alt="eu, robot" height=110 width=95></td>
</tr>
<tr>
<td>Expiação</td>
<td>Atonement</td>
<td>Expiacao</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5600402400832.15F.jpg alt="expiacao" height=110 width=95></td>
</tr>
<tr>
<td>Explorando As Origens Da Vida</td>
<td>0</td>
<td>Explorando As Origens Da Vida</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M23.15F.jpg alt="explorando as origens da vida" height=110 width=95></td>
</tr>
<tr>
<td>Extras: A Primeira Série Completa</td>
<td>Extras: The Complete First Series</td>
<td>Extras: A Primeira Serie Completa</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>175</td>
<td>0</td>
<td><img src=Images\5602193331784.15F.jpg alt="extras: a primeira serie completa" height=110 width=95></td>
</tr>
<tr>
<td>Extremamente alto, incrivelmente perto</td>
<td>Extremely Loud & Incredibly Close</td>
<td>Extremamente alto, incrivelmente perto</td>
<td></td>
<td>X</td>
<td>2011</td>
<td>124</td>
<td>Drama</td>
<td><img src=Images\5601887578931.15F.jpg alt="extremamente alto, incrivelmente perto" height=110 width=95></td>
</tr>
<tr>
<td>Extremamente Perigosa</td>
<td>Swimfan</td>
<td>Extremamente Perigosa</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>81</td>
<td>0</td>
<td><img src=Images\5601887448944.15F.jpg alt="extremamente perigosa" height=110 width=95></td>
</tr>
<tr>
<td>F/X - Efeitos Mortais</td>
<td>F/X</td>
<td>F/X - Efeitos Mortais</td>
<td>X</td>
<td>X</td>
<td>1986</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\5600304173148.15F.jpg alt="f/x - efeitos mortais" height=110 width=95></td>
</tr>
<tr>
<td>Façam o Favor de Ser Felizes</td>
<td>0</td>
<td>Facam o Favor de Ser Felizes</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>45</td>
<td>Comédia</td>
<td><img src=Images\5603846048646.15F.jpg alt="facam o favor de ser felizes" height=110 width=95></td>
</tr>
<tr>
<td>Fado - História d' Uma Cantadeira</td>
<td>0</td>
<td>Fado - Historia d' Uma Cantadeira</td>
<td>X</td>
<td>X</td>
<td>1948</td>
<td>108</td>
<td>0</td>
<td><img src=Images\5606699504192.15F.jpg alt="fado - historia d' uma cantadeira" height=110 width=95></td>
</tr>
<tr>
<td>Fala Com Ela</td>
<td>Hable con ella</td>
<td>Fala Com Ela</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>109</td>
<td>Drama</td>
<td><img src=Images\5602193347952.15F.jpg alt="fala com ela" height=110 width=95></td>
</tr>
<tr>
<td>Falsas Aparências</td>
<td>The Whole Nine Yards</td>
<td>Falsas Aparencias</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5602193305938.15F.jpg alt="falsas aparencias" height=110 width=95></td>
</tr>
<tr>
<td>Falsas Aparências 2</td>
<td>The Whole Ten Yards</td>
<td>Falsas Aparencias 2</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5602193321235.15F.jpg alt="falsas aparencias 2" height=110 width=95></td>
</tr>
<tr>
<td>Fargo</td>
<td>0</td>
<td>Fargo</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>100</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193308229.15F.jpg alt="fargo" height=110 width=95></td>
</tr>
<tr>
<td>Fast Track - Velocidade sem Limites</td>
<td>Fast Track: No Limits</td>
<td>Fast Track - Velocidade sem Limites</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>96</td>
<td>Acção</td>
<td><img src=Images\5608652033886.15F.jpg alt="fast track - velocidade sem limites" height=110 width=95></td>
</tr>
<tr>
<td>Feliz Acaso</td>
<td>Serendipity</td>
<td>Feliz Acaso</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\I8F739EA37AAA6CEA.15F.jpg alt="feliz acaso" height=110 width=95></td>
</tr>
<tr>
<td>Feliz Natal Mr. Lawrence</td>
<td>Merry Christmas Mr. Lawrence</td>
<td>Feliz Natal Mr. Lawrence</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>122</td>
<td>Drama</td>
<td><img src=Images\5607727027607.15F.jpg alt="feliz natal mr. lawrence" height=110 width=95></td>
</tr>
<tr>
<td>Ficheiros secretos: Quero acreditar</td>
<td>The X-Files: I Want to Believe</td>
<td>Ficheiros secretos: Quero acreditar</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>104</td>
<td>Ficção Científica</td>
<td><img src=Images\5600304206938.15F.jpg alt="ficheiros secretos: quero acreditar" height=110 width=95></td>
</tr>
<tr>
<td>Filme da Treta</td>
<td>0</td>
<td>Filme da Treta</td>
<td>X</td>
<td></td>
<td>2006</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\5608652030182.15F.jpg alt="filme da treta" height=110 width=95></td>
</tr>
<tr>
<td>Final Cut - A Última Memória</td>
<td>The Final Cut</td>
<td>Final Cut - A Ultima Memoria</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652027922.15F.jpg alt="final cut - a ultima memoria" height=110 width=95></td>
</tr>
<tr>
<td>Fire - Sem Nada a Perder</td>
<td>Fire!</td>
<td>Fire - Sem Nada a Perder</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>90</td>
<td>Acção</td>
<td><img src=Images\I29D76675DEB1E916.15F.jpg alt="fire - sem nada a perder" height=110 width=95></td>
</tr>
<tr>
<td>Flightplan - Pânico a Bordo</td>
<td>Flightplan</td>
<td>Flightplan - Panico a Bordo</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>94</td>
<td>Acção</td>
<td><img src=Images\5601887481316.15F.jpg alt="flightplan - panico a bordo" height=110 width=95></td>
</tr>
<tr>
<td>Flyboys - Nascidos para voar</td>
<td>Flyboys</td>
<td>Flyboys - Nascidos para voar</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>133</td>
<td>0</td>
<td><img src=Images\5608652030977.15F.jpg alt="flyboys - nascidos para voar" height=110 width=95></td>
</tr>
<tr>
<td>Fomos Soldados</td>
<td>We Were Soldiers</td>
<td>Fomos Soldados</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>134</td>
<td>Acção</td>
<td><img src=Images\5601887445578.15F.jpg alt="fomos soldados" height=110 width=95></td>
</tr>
<tr>
<td>Fora Todas as Regras</td>
<td>Breakin' All the Rules</td>
<td>Fora Todas as Regras</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>82</td>
<td>Comédia</td>
<td><img src=Images\8414533028431.15F.jpg alt="fora todas as regras" height=110 width=95></td>
</tr>
<tr>
<td>Forças da Natureza</td>
<td>Forces of Nature</td>
<td>Forcas da Natureza</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>106</td>
<td>Comédia</td>
<td><img src=Images\0678149090895.15F.jpg alt="forcas da natureza" height=110 width=95></td>
</tr>
<tr>
<td>Fórmula 51</td>
<td>The 51st State</td>
<td>Formula 51</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\5608652015165.15F.jpg alt="formula 51" height=110 width=95></td>
</tr>
<tr>
<td>Forte Apache</td>
<td>Fort Apache</td>
<td>Forte Apache</td>
<td>X</td>
<td>X</td>
<td>1948</td>
<td>127</td>
<td>Western</td>
<td><img src=Images\I87992CD4DC9813A1.15F.jpg alt="forte apache" height=110 width=95></td>
</tr>
<tr>
<td>Freedomland: A Cor do Crime</td>
<td>Freedomland</td>
<td>Freedomland: A Cor do Crime</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>108</td>
<td>0</td>
<td><img src=Images\5601887485949.15F.jpg alt="freedomland: a cor do crime" height=110 width=95></td>
</tr>
<tr>
<td>Frequência</td>
<td>Frequency</td>
<td>Frequencia</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887427840.15F.jpg alt="frequencia" height=110 width=95></td>
</tr>
<tr>
<td>Fresh</td>
<td>0</td>
<td>Fresh</td>
<td></td>
<td>X</td>
<td>1994</td>
<td>114</td>
<td>0</td>
<td><img src=Images\717951002778F.jpg alt="fresh" height=110 width=95></td>
</tr>
<tr>
<td>Frida</td>
<td>0</td>
<td>Frida</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5608652019552.15F.jpg alt="frida" height=110 width=95></td>
</tr>
<tr>
<td>Fronteiras de Ambição</td>
<td>Beyond the City Limits</td>
<td>Fronteiras de Ambicao</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>92</td>
<td>0</td>
<td><img src=Images\5608652011761.15F.jpg alt="fronteiras de ambicao" height=110 width=95></td>
</tr>
<tr>
<td>Frost/Nixon</td>
<td>0</td>
<td>Frost/Nixon</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\5050582607482.15F.jpg alt="frost/nixon" height=110 width=95></td>
</tr>
<tr>
<td>Frosty o boneco de neve</td>
<td>0</td>
<td>Frosty o boneco de neve</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M24.15F.jpg alt="frosty o boneco de neve" height=110 width=95></td>
</tr>
<tr>
<td>Funcionário do mês</td>
<td>Employee of the Month</td>
<td>Funcionario do mes</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>104</td>
<td>Comédia</td>
<td><img src=Images\IE76CE7E9043A3EF3.15F.jpg alt="funcionario do mes" height=110 width=95></td>
</tr>
<tr>
<td>Fúria de Combater</td>
<td>Born To Defense ou Zhong hua ying xiong</td>
<td>Furia de Combater</td>
<td>X</td>
<td>X</td>
<td>1986</td>
<td>91</td>
<td>Artes Marciais</td>
<td><img src=Images\5608652028356.15F.jpg alt="furia de combater" height=110 width=95></td>
</tr>
<tr>
<td>Galileu</td>
<td>0</td>
<td>Galileu</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M25.15F.jpg alt="galileu" height=110 width=95></td>
</tr>
<tr>
<td>Gangs de Nova Iorque</td>
<td>Gangs of New York</td>
<td>Gangs de Nova Iorque</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>166</td>
<td>Drama</td>
<td><img src=Images\5602193314763.15F.jpg alt="gangs de nova iorque" height=110 width=95></td>
</tr>
<tr>
<td>Gangster No. 1</td>
<td>0</td>
<td>Gangster No. 1</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5014138290016.4F.jpg alt="gangster no. 1" height=110 width=95></td>
</tr>
<tr>
<td>Garfield: O Filme</td>
<td>Garfield</td>
<td>Garfield: O Filme</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>77</td>
<td>Animação</td>
<td><img src=Images\5600304168175.15F.jpg alt="garfield: o filme" height=110 width=95></td>
</tr>
<tr>
<td>Gente Conhecida</td>
<td>People I Know</td>
<td>Gente Conhecida</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>95</td>
<td>Drama</td>
<td><img src=Images\5608652017756.15F.jpg alt="gente conhecida" height=110 width=95></td>
</tr>
<tr>
<td>Gente Estranha</td>
<td>Fierce People</td>
<td>Gente Estranha</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>107</td>
<td>Drama</td>
<td><img src=Images\I9ADD8543B5974488.15F.jpg alt="gente estranha" height=110 width=95></td>
</tr>
<tr>
<td><NAME> vol.1</td>
<td>0</td>
<td><NAME> vol.1</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>25</td>
<td>Animação</td>
<td><img src=Images\5050582751598.10F.jpg alt="geronimo stilton vol.1" height=110 width=95></td>
</tr>
<tr>
<td>Get Low</td>
<td>0</td>
<td>Get Low</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\8716777934777.30F.jpg alt="get low" height=110 width=95></td>
</tr>
<tr>
<td>Giras e passadas</td>
<td>St Trinian's</td>
<td>Giras e passadas</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\IFAB370AE607773DB.15F.jpg alt="giras e passadas" height=110 width=95></td>
</tr>
<tr>
<td>Giras e Terríveis</td>
<td>Mean Girls</td>
<td>Giras e Terriveis</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5601887466375.15F.jpg alt="giras e terriveis" height=110 width=95></td>
</tr>
<tr>
<td>Godsend - O Enviado</td>
<td>Godsend</td>
<td>Godsend - O Enviado</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>98</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652025980.15F.jpg alt="godsend - o enviado" height=110 width=95></td>
</tr>
<tr>
<td>GoldenEye</td>
<td>0</td>
<td>GoldenEye</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>124</td>
<td>Acção</td>
<td><img src=Images\IF9BD1CFD98403808.15F.jpg alt="goldeneye" height=110 width=95></td>
</tr>
<tr>
<td>Golpe de Mestre</td>
<td>Art Heist</td>
<td>Golpe de Mestre</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>95</td>
<td>0</td>
<td><img src=Images\8414533026161.15F.jpg alt="golpe de mestre" height=110 width=95></td>
</tr>
<tr>
<td>Golpe de Natal</td>
<td>0</td>
<td>Golpe de Natal</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M27.15F.jpg alt="golpe de natal" height=110 width=95></td>
</tr>
<tr>
<td>Golpe no Paraíso</td>
<td>After the Sunset</td>
<td>Golpe no Paraiso</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>97</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193341400.15F.jpg alt="golpe no paraiso" height=110 width=95></td>
</tr>
<tr>
<td>Golpe Quase Perfeito</td>
<td>The Hoax</td>
<td>Golpe Quase Perfeito</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>116</td>
<td>Drama</td>
<td><img src=Images\5602193339339.15F.jpg alt="golpe quase perfeito" height=110 width=95></td>
</tr>
<tr>
<td>Good - Um Homem Bom</td>
<td>Good</td>
<td>Good - Um Homem Bom</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>92</td>
<td>Drama</td>
<td><img src=Images\5608652035552.15F.jpg alt="good - um homem bom" height=110 width=95></td>
</tr>
<tr>
<td>Good Bye Lenin! - Adeus Lenine!</td>
<td>Good Bye Lenin!</td>
<td>Good Bye Lenin! - Adeus Lenine!</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>113</td>
<td>0</td>
<td><img src=Images\5602193336222.15F.jpg alt="good bye lenin! - adeus lenine!" height=110 width=95></td>
</tr>
<tr>
<td>Gosford Park</td>
<td>0</td>
<td>Gosford Park</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>131</td>
<td>0</td>
<td><img src=Images\5601887439072.15F.jpg alt="gosford park" height=110 width=95></td>
</tr>
<tr>
<td>Grand Budapest Hotel</td>
<td>The Grand Budapest Hotel</td>
<td>Grand Budapest Hotel</td>
<td></td>
<td>X</td>
<td>2014</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5602193509305.15F.jpg alt="grand budapest hotel" height=110 width=95></td>
</tr>
<tr>
<td>Grandes Esperanças</td>
<td>Great Expectations</td>
<td>Grandes Esperancas</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>107</td>
<td>Drama</td>
<td><img src=Images\5608652010252.15F.jpg alt="grandes esperancas" height=110 width=95></td>
</tr>
<tr>
<td>Gritos - Scream</td>
<td>Scream</td>
<td>Gritos - Scream</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>106</td>
<td>0</td>
<td><img src=Images\5601887441792.15F.jpg alt="gritos - scream" height=110 width=95></td>
</tr>
<tr>
<td>Guerra</td>
<td>War</td>
<td>Guerra</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>98</td>
<td>Acção</td>
<td><img src=Images\5608652032445.15F.jpg alt="guerra" height=110 width=95></td>
</tr>
<tr>
<td>Guerra dos Mundos</td>
<td>War of the Worlds</td>
<td>Guerra dos Mundos</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>112</td>
<td>Aventura</td>
<td><img src=Images\5601887476824.15F.jpg alt="guerra dos mundos" height=110 width=95></td>
</tr>
<tr>
<td>Guerra, S. A.</td>
<td>War, Inc.</td>
<td>Guerra, S. A.</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>107</td>
<td>Comédia</td>
<td><img src=Images\5601887533497.15F.jpg alt="guerra, s. a." height=110 width=95></td>
</tr>
<tr>
<td>Hackers - Piratas Cibernéticos</td>
<td>Hackers</td>
<td>Hackers - Piratas Ciberneticos</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>101</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652006545.15F.jpg alt="hackers - piratas ciberneticos" height=110 width=95></td>
</tr>
<tr>
<td>Hairspray</td>
<td>0</td>
<td>Hairspray</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>112</td>
<td>Musical</td>
<td><img src=Images\5601887520022.15F.jpg alt="hairspray" height=110 width=95></td>
</tr>
<tr>
<td>Hamlet</td>
<td>0</td>
<td>Hamlet</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>129</td>
<td>0</td>
<td><img src=Images\5601887455102.15F.jpg alt="hamlet" height=110 width=95></td>
</tr>
<tr>
<td>Hannibal</td>
<td>0</td>
<td>Hannibal</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>126</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5050582320091.15F.jpg alt="hannibal" height=110 width=95></td>
</tr>
<tr>
<td>Hannibal - A Origem do Mal</td>
<td>Hannibal Rising</td>
<td>Hannibal - A Origem do Mal</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>126</td>
<td>Horror</td>
<td><img src=Images\5608652031004.15F.jpg alt="hannibal - a origem do mal" height=110 width=95></td>
</tr>
<tr>
<td>Hard Candy</td>
<td>0</td>
<td>Hard Candy</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\5600304171366.15F.jpg alt="hard candy" height=110 width=95></td>
</tr>
<tr>
<td>Harry Potter e o Cálice de Fogo</td>
<td>Harry Potter and the Goblet of Fire</td>
<td>Harry Potter e o Calice de Fogo</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>151</td>
<td>Aventura</td>
<td><img src=Images\5601887546916.15F.jpg alt="harry potter e o calice de fogo" height=110 width=95></td>
</tr>
<tr>
<td>Harry Potter e a Câmara dos Segredos</td>
<td>0</td>
<td>Harry Potter e a Camara dos Segredos</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>155</td>
<td>0</td>
<td><img src=Images\7321977235923.15F.jpg alt="harry potter e a camara dos segredos" height=110 width=95></td>
</tr>
<tr>
<td>Harry Potter e a Ordem da Fénix</td>
<td>Harry Potter and the Order of the Phoenix</td>
<td>Harry Potter e a Ordem da Fenix</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>133</td>
<td>Fantasia</td>
<td><img src=Images\5600304179959.15F.jpg alt="harry potter e a ordem da fenix" height=110 width=95></td>
</tr>
<tr>
<td>Harry Potter e a Pedra Filosofal</td>
<td>Harry Potter and the Philosopher's Stone</td>
<td>Harry Potter e a Pedra Filosofal</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>146</td>
<td>Fantasia</td>
<td><img src=Images\7321976226595.15F.jpg alt="harry potter e a pedra filosofal" height=110 width=95></td>
</tr>
<tr>
<td><NAME>ter e o Príncipe Misterioso</td>
<td>Harry Potter and the Half-Blood Prince</td>
<td>Harry Potter e o Principe Misterioso</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>147</td>
<td>Fantasia</td>
<td><img src=Images\5601887541911.15F.jpg alt="harry potter e o principe misterioso" height=110 width=95></td>
</tr>
<tr>
<td><NAME> e o Prisioneiro de Azkaban</td>
<td><NAME> and the Prisoner of Azkaban</td>
<td>Harry Potter e o Prisioneiro de Azkaban</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>136</td>
<td>0</td>
<td><img src=Images\7321977284457.15F.jpg alt="harry potter e o prisioneiro de azkaban" height=110 width=95></td>
</tr>
<tr>
<td><NAME>ter e os Talismãs da Morte Parte 1</td>
<td>0</td>
<td>Harry Potter e os Talismas da Morte Parte 1</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>140</td>
<td>Aventura</td>
<td><img src=Images\5601887568833.15F.jpg alt="harry potter e os talismas da morte parte 1" height=110 width=95></td>
</tr>
<tr>
<td>Harry Potter e os talismãs da morte: Parte 2</td>
<td>Harry Potter And The Deathly Hallows: Part 2</td>
<td>Harry Potter e os talismas da morte: Parte 2</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>125</td>
<td>Aventura</td>
<td><img src=Images\5601887574773.15F.jpg alt="harry potter e os talismas da morte: parte 2" height=110 width=95></td>
</tr>
<tr>
<td>Havana</td>
<td>0</td>
<td>Havana</td>
<td></td>
<td>X</td>
<td>1990</td>
<td>139</td>
<td>0</td>
<td><img src=Images\5050582001969.15F.jpg alt="havana" height=110 width=95></td>
</tr>
<tr>
<td>Havana - Cidade perdida</td>
<td>The Lost City</td>
<td>Havana - Cidade perdida</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>138</td>
<td>Drama</td>
<td><img src=Images\IF7ACB6DF8CAD13BC.15F.jpg alt="havana - cidade perdida" height=110 width=95></td>
</tr>
<tr>
<td>Heaven - Por Amor</td>
<td>0</td>
<td>Heaven - Por Amor</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\5608652015196.15F.jpg alt="heaven - por amor" height=110 width=95></td>
</tr>
<tr>
<td>Hellboy II: O Exército dourado</td>
<td>Hellboy II: The Golden Army</td>
<td>Hellboy II: O Exercito dourado</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>114</td>
<td>Acção</td>
<td><img src=Images\5050582595734.15F.jpg alt="hellboy ii: o exercito dourado" height=110 width=95></td>
</tr>
<tr>
<td>Hércules</td>
<td>Hercules</td>
<td>Hercules</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>89</td>
<td>0</td>
<td><img src=Images\5601887440412.15F.jpg alt="hercules" height=110 width=95></td>
</tr>
<tr>
<td>Heróis por acaso</td>
<td>Sneakers</td>
<td>Herois por acaso</td>
<td></td>
<td>X</td>
<td>1992</td>
<td>120</td>
<td>Acção</td>
<td><img src=Images\5601887408603.15F.jpg alt="herois por acaso" height=110 width=95></td>
</tr>
<tr>
<td>Histórias para adormecer</td>
<td>Bedtime Stories</td>
<td>Historias para adormecer</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>95</td>
<td>Comédia</td>
<td><img src=Images\5601887536139.15F.jpg alt="historias para adormecer" height=110 width=95></td>
</tr>
<tr>
<td>Hitchcock</td>
<td>0</td>
<td>Hitchcock</td>
<td>X</td>
<td>X</td>
<td>2012</td>
<td>94</td>
<td>Drama</td>
<td><img src=Images\5602193506298.15F.jpg alt="hitchcock" height=110 width=95></td>
</tr>
<tr>
<td>Hollywoodland</td>
<td>0</td>
<td>Hollywoodland</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>121</td>
<td>Drama</td>
<td><img src=Images\5601887493272.15F.jpg alt="hollywoodland" height=110 width=95></td>
</tr>
<tr>
<td>Home - O mundo é a nossa casa</td>
<td>Home</td>
<td>Home - O mundo e a nossa casa</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>96</td>
<td>Documentário</td>
<td><img src=Images\5601887535491.15F.jpg alt="home - o mundo e a nossa casa" height=110 width=95></td>
</tr>
<tr>
<td>Homem Aranha A saga de Venom</td>
<td>0</td>
<td>Homem Aranha A saga de Venom</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M98.15F.jpg alt="homem aranha a saga de venom" height=110 width=95></td>
</tr>
<tr>
<td>Homem de Ferro</td>
<td>Iron Man</td>
<td>Homem de Ferro</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5601887526550.15F.jpg alt="homem de ferro" height=110 width=95></td>
</tr>
<tr>
<td>Homem Morto</td>
<td>Dead Man</td>
<td>Homem Morto</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>117</td>
<td>0</td>
<td><img src=Images\5602193329880.15F.jpg alt="homem morto" height=110 width=95></td>
</tr>
<tr>
<td>Homem-Aranha</td>
<td>Spider-Man</td>
<td>Homem-Aranha</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>116</td>
<td>Fantasia</td>
<td><img src=Images\5601887438235.15F.jpg alt="homem-aranha" height=110 width=95></td>
</tr>
<tr>
<td>Homem-Aranha 2</td>
<td>Spider-Man 2</td>
<td>Homem-Aranha 2</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>121</td>
<td>0</td>
<td><img src=Images\8414533026116.15F.jpg alt="homem-aranha 2" height=110 width=95></td>
</tr>
<tr>
<td>Homem-Aranha 3</td>
<td>0</td>
<td>Homem-Aranha 3</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>133</td>
<td>Acção</td>
<td><img src=Images\8414533044691.15F.jpg alt="homem-aranha 3" height=110 width=95></td>
</tr>
<tr>
<td>Homens à Queima Roupa</td>
<td>At Close Range</td>
<td>Homens a Queima Roupa</td>
<td></td>
<td>X</td>
<td>1986</td>
<td>111</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652018814.15F.jpg alt="homens a queima roupa" height=110 width=95></td>
</tr>
<tr>
<td>Homens de Honra</td>
<td>Men of Honor</td>
<td>Homens de Honra</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>123</td>
<td>Drama</td>
<td><img src=Images\5600304165327.15F.jpg alt="homens de honra" height=110 width=95></td>
</tr>
<tr>
<td>Homens do Soul</td>
<td>Soul Men</td>
<td>Homens do Soul</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>96</td>
<td>Comédia</td>
<td><img src=Images\5600304209311.15F.jpg alt="homens do soul" height=110 width=95></td>
</tr>
<tr>
<td>Homicídio em Hollywood</td>
<td>Hollywood Homicide</td>
<td>Homicidio em Hollywood</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>110</td>
<td>0</td>
<td><img src=Images\5601887460007.15F.jpg alt="homicidio em hollywood" height=110 width=95></td>
</tr>
<tr>
<td>Hope Springs Terapia de amor</td>
<td>Hope Springs</td>
<td>Hope Springs Terapia de amor</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>92</td>
<td>0</td>
<td><img src=Images\7896012228616.23F.jpg alt="hope springs terapia de amor" height=110 width=95></td>
</tr>
<tr>
<td>Hora de Ponta 1</td>
<td>Rush Hour</td>
<td>Hora de Ponta 1</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>94</td>
<td>Acção</td>
<td><img src=Images\5602193307130.15F.jpg alt="hora de ponta 1" height=110 width=95></td>
</tr>
<tr>
<td>Hora de Ponta 2</td>
<td>Rush Hour 2</td>
<td>Hora de Ponta 2</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5602193307574.15F.jpg alt="hora de ponta 2" height=110 width=95></td>
</tr>
<tr>
<td>Hora de Ponta 3</td>
<td>Rush Hour 3</td>
<td>Hora de Ponta 3</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5602193340526.15F.jpg alt="hora de ponta 3" height=110 width=95></td>
</tr>
<tr>
<td>Horizonte Longínquo</td>
<td>Far and Away</td>
<td>Horizonte Longinquo</td>
<td></td>
<td>X</td>
<td>1992</td>
<td>134</td>
<td>Drama</td>
<td><img src=Images\5050582041224.15F.jpg alt="horizonte longinquo" height=110 width=95></td>
</tr>
<tr>
<td>Hostage - Reféns</td>
<td>Hostage</td>
<td>Hostage - Refens</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>113</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193343077.15F.jpg alt="hostage - refens" height=110 width=95></td>
</tr>
<tr>
<td>Hot Fuzz - Esquadrão de Província</td>
<td>Hot Fuzz</td>
<td>Hot Fuzz - Esquadrao de Provincia</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>116</td>
<td>Comédia</td>
<td><img src=Images\5050582528596.15F.jpg alt="hot fuzz - esquadrao de provincia" height=110 width=95></td>
</tr>
<tr>
<td>Hotel Ruanda</td>
<td>Hotel Rwanda</td>
<td>Hotel Ruanda</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\5608652027045.15F.jpg alt="hotel ruanda" height=110 width=95></td>
</tr>
<tr>
<td>Houdini: O Último Grande Mágico</td>
<td>Death Defying Acts</td>
<td>Houdini: O Ultimo Grande Magico</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\5608652033893.15F.jpg alt="houdini: o ultimo grande magico" height=110 width=95></td>
</tr>
<tr>
<td>I Am Sam - A Força do Amor</td>
<td>I Am Sam</td>
<td>I Am Sam - A Forca do Amor</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>132</td>
<td>0</td>
<td><img src=Images\5602193310208.15F.jpg alt="i am sam - a forca do amor" height=110 width=95></td>
</tr>
<tr>
<td>Identidade Falsa</td>
<td>0</td>
<td>Identidade Falsa</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\3259190706026.15F.jpg alt="identidade falsa" height=110 width=95></td>
</tr>
<tr>
<td>Identidade Sob Suspeita</td>
<td><NAME></td>
<td>Identidade Sob Suspeita</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>104</td>
<td>Drama</td>
<td><img src=Images\5602193309271.15F.jpg alt="identidade sob suspeita" height=110 width=95></td>
</tr>
<tr>
<td>Impacto Profundo</td>
<td>Deep Impact</td>
<td>Impacto Profundo</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>121</td>
<td>Acção</td>
<td><img src=Images\0678149096927.15F.jpg alt="impacto profundo" height=110 width=95></td>
</tr>
<tr>
<td>Inadaptado.</td>
<td>Adaptation.</td>
<td>Inadaptado.</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>110</td>
<td>Comédia</td>
<td><img src=Images\5608652020046.15F.jpg alt="inadaptado." height=110 width=95></td>
</tr>
<tr>
<td>Incendiario</td>
<td>Incendiary</td>
<td>Incendiario</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>96</td>
<td>Drama</td>
<td><img src=Images\5601887551637.15F.jpg alt="incendiario" height=110 width=95></td>
</tr>
<tr>
<td>Inconsciente</td>
<td>Undermind</td>
<td>Inconsciente</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5606320000345.15F.jpg alt="inconsciente" height=110 width=95></td>
</tr>
<tr>
<td>Indian - O Grande Desafio</td>
<td>The World's Fastest Indian</td>
<td>Indian - O Grande Desafio</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5602193334389.15F.jpg alt="indian - o grande desafio" height=110 width=95></td>
</tr>
<tr>
<td>Indiana Jones e a Grande Cruzada</td>
<td>Indiana Jones and the Last Crusade</td>
<td>Indiana Jones e a Grande Cruzada</td>
<td>X</td>
<td></td>
<td>1989</td>
<td>122</td>
<td>Aventura</td>
<td><img src=Images\5601887451715.15F.jpg alt="indiana jones e a grande cruzada" height=110 width=95></td>
</tr>
<tr>
<td>Indiana Jones e o Reino da Caveira de Cristal</td>
<td>Indiana Jones and the Kingdom of the Crystal Skull</td>
<td>Indiana Jones e o Reino da Caveira de Cristal</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\5601887527908.15F.jpg alt="indiana jones e o reino da caveira de cristal" height=110 width=95></td>
</tr>
<tr>
<td>Indiana Jones e o Templo Perdido</td>
<td>Indiana Jones and the Temple of Doom</td>
<td>Indiana Jones e o Templo Perdido</td>
<td>X</td>
<td></td>
<td>1984</td>
<td>114</td>
<td>Aventura</td>
<td><img src=Images\5601887451708.15F.jpg alt="indiana jones e o templo perdido" height=110 width=95></td>
</tr>
<tr>
<td>Indiana Jones e os Salteadores da Arca Perdida</td>
<td>Raider of the Lost Ark</td>
<td>Indiana Jones e os Salteadores da Arca Perdida</td>
<td>X</td>
<td></td>
<td>1981</td>
<td>115</td>
<td>0</td>
<td><img src=Images\5601887452989.15F.jpg alt="indiana jones e os salteadores da arca perdida" height=110 width=95></td>
</tr>
<tr>
<td>Infame</td>
<td>Infamous</td>
<td>Infame</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5600304173285.15F.jpg alt="infame" height=110 width=95></td>
</tr>
<tr>
<td>Infiel</td>
<td>Unfaithful</td>
<td>Infiel</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5600304166140.15F.jpg alt="infiel" height=110 width=95></td>
</tr>
<tr>
<td>Infiltrado</td>
<td>Inside Man</td>
<td>Infiltrado</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>123</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5050582430431.15F.jpg alt="infiltrado" height=110 width=95></td>
</tr>
<tr>
<td>Inimigos públicos</td>
<td>Public Enemies</td>
<td>Inimigos publicos</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>134</td>
<td>Drama</td>
<td><img src=Images\5050582739268.15F.jpg alt="inimigos publicos" height=110 width=95></td>
</tr>
<tr>
<td>Inocente ou Culpado</td>
<td>The Life of David Gale</td>
<td>Inocente ou Culpado</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>125</td>
<td>0</td>
<td><img src=Images\5601887458127.15F.jpg alt="inocente ou culpado" height=110 width=95></td>
</tr>
<tr>
<td>Insomnia</td>
<td>0</td>
<td>Insomnia</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\IA707F40B5CCB1F75.15F.jpg alt="insomnia" height=110 width=95></td>
</tr>
<tr>
<td>Inspector Maigret - Série 1</td>
<td>Maigret</td>
<td>Inspector Maigret - Serie 1</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>338</td>
<td>0</td>
<td><img src=Images\5602193325967.15F.jpg alt="inspector maigret - serie 1" height=110 width=95></td>
</tr>
<tr>
<td>Inspector Maigret - Série 2</td>
<td>Maigret</td>
<td>Inspector Maigret - Serie 2</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>312</td>
<td>0</td>
<td><img src=Images\5602193327541.15F.jpg alt="inspector maigret - serie 2" height=110 width=95></td>
</tr>
<tr>
<td>Instantes Decisivos</td>
<td>Sliding Doors</td>
<td>Instantes Decisivos</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>95</td>
<td>Comédia</td>
<td><img src=Images\5601887461714.15F.jpg alt="instantes decisivos" height=110 width=95></td>
</tr>
<tr>
<td>Instinto</td>
<td>Instinct</td>
<td>Instinto</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>119</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887430505.15F.jpg alt="instinto" height=110 width=95></td>
</tr>
<tr>
<td>Instinto Fatal</td>
<td>Basic Instinct</td>
<td>Instinto Fatal</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>123</td>
<td>Suspense/Thriller</td>
<td><img src=Images\3259190258396.15F.jpg alt="instinto fatal" height=110 width=95></td>
</tr>
<tr>
<td>Instinto Fatal 2</td>
<td>Basic Instinct 2</td>
<td>Instinto Fatal 2</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>111</td>
<td>0</td>
<td><img src=Images\5608652029384.15F.jpg alt="instinto fatal 2" height=110 width=95></td>
</tr>
<tr>
<td>Intervalo</td>
<td>InterMission</td>
<td>Intervalo</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>102</td>
<td>Drama</td>
<td><img src=Images\5608652025959.15F.jpg alt="intervalo" height=110 width=95></td>
</tr>
<tr>
<td>Invencível</td>
<td>Invincible</td>
<td>Invencivel</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\5601887493296.15F.jpg alt="invencivel" height=110 width=95></td>
</tr>
<tr>
<td>Ira & Abby</td>
<td>Ira and Abby</td>
<td>Ira & Abby</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\I10FCBF75916E7AAC.15F.jpg alt="ira & abby" height=110 width=95></td>
</tr>
<tr>
<td>Iris</td>
<td>0</td>
<td>Iris</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>87</td>
<td>0</td>
<td><img src=Images\5601887437955.15F.jpg alt="iris" height=110 width=95></td>
</tr>
<tr>
<td>Irmão, Onde Estás?</td>
<td>O Brother, Where Art Thou?</td>
<td>Irmao, Onde Estas?</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>102</td>
<td>Comédia</td>
<td><img src=Images\5601887426522.15F.jpg alt="irmao, onde estas?" height=110 width=95></td>
</tr>
<tr>
<td>Irresistível Adam</td>
<td>About Adam</td>
<td>Irresistivel Adam</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\I7DEA206D647C2D20.15F.jpg alt="irresistivel adam" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>151</td>
<td>0</td>
<td><img src=Images\5608652000512.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Janela indiscreta</td>
<td>Rear Window</td>
<td>Janela indiscreta</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>85</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304160544.15F.jpg alt="janela indiscreta" height=110 width=95></td>
</tr>
<tr>
<td>Jantando Fora com Timon & Pumba</td>
<td>Dining out With Timon & Pumba</td>
<td>Jantando Fora com Timon & Pumba</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>70</td>
<td>Animação</td>
<td><img src=Images\5601887466641.15F.jpg alt="jantando fora com timon & pumba" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME>uire</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>134</td>
<td>0</td>
<td><img src=Images\5606376284485.15F.jpg alt="jerry maguire" height=110 width=95></td>
</tr>
<tr>
<td><NAME> - O Pequeno Génio</td>
<td>Jimmy Neutron: Boy Genius</td>
<td>Jimmy Neutron - O Pequeno Genio</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>79</td>
<td>0</td>
<td><img src=Images\5601887438631.15F.jpg alt="jimmy neutron - o pequeno genio" height=110 width=95></td>
</tr>
<tr>
<td>Jogo de Espiões</td>
<td>Spy Game</td>
<td>Jogo de Espioes</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>121</td>
<td>Acção</td>
<td><img src=Images\5601887439157.15F.jpg alt="jogo de espioes" height=110 width=95></td>
</tr>
<tr>
<td>Jogo de Lágrimas</td>
<td>The Crying Game</td>
<td>Jogo de Lagrimas</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>108</td>
<td>0</td>
<td><img src=Images\5606118000083.15F.jpg alt="jogo de lagrimas" height=110 width=95></td>
</tr>
<tr>
<td>Jogo de Traições</td>
<td>Reindeer Games</td>
<td>Jogo de Traicoes</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>101</td>
<td>Acção</td>
<td><img src=Images\5608652004664.15F.jpg alt="jogo de traicoes" height=110 width=95></td>
</tr>
<tr>
<td>Jogo Sujo</td>
<td>Leatherheads</td>
<td>Jogo Sujo</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>114</td>
<td>Comédia</td>
<td><img src=Images\5050582575446.15F.jpg alt="jogo sujo" height=110 width=95></td>
</tr>
<tr>
<td>Jogos de Poder</td>
<td>Charlie Wilson's War</td>
<td>Jogos de Poder</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\5050582544763.15F.jpg alt="jogos de poder" height=110 width=95></td>
</tr>
<tr>
<td>Jogos Quase Perigosos</td>
<td>Get Shorty</td>
<td>Jogos Quase Perigosos</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5608652006095.15F.jpg alt="jogos quase perigosos" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M29.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td><NAME>.</td>
<td><NAME></td>
<td><NAME>.</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>111</td>
<td>Drama</td>
<td><img src=Images\5602193310222.15F.jpg alt="<NAME>." height=110 width=95></td>
</tr>
<tr>
<td><NAME> 2</td>
<td><NAME>: Chapter 2</td>
<td><NAME> 2</td>
<td>X</td>
<td>X</td>
<td>2017</td>
<td>122</td>
<td>Crime</td>
<td><img src=Images\031398259442F.jpg alt="<NAME> 2" height=110 width=95></td>
</tr>
<tr>
<td>Julgamento</td>
<td>0</td>
<td>Julgamento</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>102</td>
<td>Drama</td>
<td><img src=Images\5600304194693.15F.jpg alt="julgamento" height=110 width=95></td>
</tr>
<tr>
<td>Julie e Julia</td>
<td>Julie & Julia</td>
<td>Julie e Julia</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>118</td>
<td>Comédia</td>
<td><img src=Images\8414533066280.15F.jpg alt="julie e julia" height=110 width=95></td>
</tr>
<tr>
<td>Jumper</td>
<td>0</td>
<td>Jumper</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>85</td>
<td>Ficção Científica</td>
<td><img src=Images\5600304204057.15F.jpg alt="jumper" height=110 width=95></td>
</tr>
<tr>
<td>Junior</td>
<td>0</td>
<td>Junior</td>
<td></td>
<td>X</td>
<td>1994</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5050582003307.15F.jpg alt="junior" height=110 width=95></td>
</tr>
<tr>
<td>Juno</td>
<td>0</td>
<td>Juno</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>92</td>
<td>Comédia</td>
<td><img src=Images\5608652033176.15F.jpg alt="juno" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Internal Affairs</td>
<td>Justica Cega</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\7896012250662.23F.jpg alt="justica cega" height=110 width=95></td>
</tr>
<tr>
<td>Justiça Vermelha</td>
<td>Red Corner</td>
<td>Justica Vermelha</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>117</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304176798.15F.jpg alt="justica vermelha" height=110 width=95></td>
</tr>
<tr>
<td>Justiceiro Incorruptível</td>
<td>Walking Tall</td>
<td>Justiceiro Incorruptivel</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>83</td>
<td>Acção</td>
<td><img src=Images\5600304174534.15F.jpg alt="justiceiro incorruptivel" height=110 width=95></td>
</tr>
<tr>
<td>K-19</td>
<td>K-19: The Widowmaker</td>
<td>K-19</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>131</td>
<td>Guerra</td>
<td><img src=Images\5601887448623.15F.jpg alt="k-19" height=110 width=95></td>
</tr>
<tr>
<td>K-Pax - Um Homem de Outro Mundo</td>
<td>K-Pax</td>
<td>K-Pax - Um Homem de Outro Mundo</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\5601887449897.15F.jpg alt="k-pax - um homem de outro mundo" height=110 width=95></td>
</tr>
<tr>
<td>Kate & Leopold</td>
<td>0</td>
<td>Kate & Leopold</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>130</td>
<td>Romance</td>
<td><img src=Images\5608652013796.15F.jpg alt="kate & leopold" height=110 width=95></td>
</tr>
<tr>
<td>Kenai e Koda</td>
<td>Brother Bear</td>
<td>Kenai e Koda</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>83</td>
<td>Animação</td>
<td><img src=Images\5601887462568.15F.jpg alt="kenai e koda" height=110 width=95></td>
</tr>
<tr>
<td>Kill Bill - A Vingança</td>
<td>Kill Bill: Vol. 1</td>
<td>Kill Bill - A Vinganca</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>106</td>
<td>Acção</td>
<td><img src=Images\5601887459100.15F.jpg alt="kill bill - a vinganca" height=110 width=95></td>
</tr>
<tr>
<td>Kill Bill - A Vingança - Volume 2</td>
<td>Kill Bill: Vol. 2</td>
<td>Kill Bill - A Vinganca - Volume 2</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>131</td>
<td>Acção</td>
<td><img src=Images\5601887464104.15F.jpg alt="kill bill - a vinganca - volume 2" height=110 width=95></td>
</tr>
<tr>
<td>King Kong</td>
<td>0</td>
<td>King Kong</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>180</td>
<td>0</td>
<td><img src=Images\5050582411416.15F.jpg alt="king kong" height=110 width=95></td>
</tr>
<tr>
<td>Kingsman: Serviços Secretos</td>
<td>Kingsman: The Secret Service</td>
<td>Kingsman: Servicos Secretos</td>
<td>X</td>
<td>X</td>
<td>2014</td>
<td>129</td>
<td>Acção</td>
<td><img src=Images\5602193510974.15F.jpg alt="kingsman: servicos secretos" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td>Lady Chatterley</td>
<td></td>
<td>X</td>
<td>1993</td>
<td>204</td>
<td>Drama</td>
<td><img src=Images\ICD161AB5BFF0C5F3.15F.jpg alt="lady chatterley" height=110 width=95></td>
</tr>
<tr>
<td>Lara Croft - Tomb Raider: O Berço da Vida</td>
<td>Lara Croft Tomb Raider: The Cradle of Life</td>
<td>Lara Croft - Tomb Raider: O Berco da Vida</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>125</td>
<td>Aventura</td>
<td><img src=Images\5601887456208.15F.jpg alt="lara croft - tomb raider: o berco da vida" height=110 width=95></td>
</tr>
<tr>
<td>Lara Croft: Tomb Raider</td>
<td>0</td>
<td>Lara Croft: Tomb Raider</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>96</td>
<td>Acção</td>
<td><img src=Images\5601887428588.15F.jpg alt="lara croft: tomb raider" height=110 width=95></td>
</tr>
<tr>
<td>Larry Flynt</td>
<td>The People vs. Larry Flint</td>
<td>Larry Flynt</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>124</td>
<td>0</td>
<td><img src=Images\5606376286380.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Lassie</td>
<td>0</td>
<td>Lassie</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>96</td>
<td>Aventura</td>
<td><img src=Images\I446A6F736615BCC6.15F.jpg alt="lassie" height=110 width=95></td>
</tr>
<tr>
<td>Lemony Snicket: Uma Série de Desgraças</td>
<td>Lemony Snicket's A Series of Unfortunate Events</td>
<td>Lemony Snicket: Uma Serie de Desgracas</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>103</td>
<td>Comédia</td>
<td><img src=Images\5050583020082.15F.jpg alt="lemony snicket: uma serie de desgracas" height=110 width=95></td>
</tr>
<tr>
<td>Leopoldina e a tartaruga bebé</td>
<td>0</td>
<td>Leopoldina e a tartaruga bebe</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M30.15F.jpg alt="leopoldina e a tartaruga bebe" height=110 width=95></td>
</tr>
<tr>
<td>Licença Para Casar</td>
<td>License to Wed</td>
<td>Licenca Para Casar</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5601887543250.15F.jpg alt="licenca para casar" height=110 width=95></td>
</tr>
<tr>
<td>Licença Para Matar</td>
<td>Licence to Kill</td>
<td>Licenca Para Matar</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>127</td>
<td>Acção</td>
<td><img src=Images\I9091112C1FFE2083.15F.jpg alt="licenca para matar" height=110 width=95></td>
</tr>
<tr>
<td>Liga de Cavalheiros Extraordinários</td>
<td>The League of Extraordinary Gentlemen</td>
<td>Liga de Cavalheiros Extraordinarios</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>106</td>
<td>Aventura</td>
<td><img src=Images\5608652026024.15F.jpg alt="liga de cavalheiros extraordinarios" height=110 width=95></td>
</tr>
<tr>
<td>Ligação de Alto Risco</td>
<td>Cellular</td>
<td>Ligacao de Alto Risco</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5602193323864.15F.jpg alt="ligacao de alto risco" height=110 width=95></td>
</tr>
<tr>
<td>Lilo & Stitch</td>
<td>0</td>
<td>Lilo & Stitch</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>82</td>
<td>Comédia</td>
<td><img src=Images\5601887441730.15F.jpg alt="lilo & stitch" height=110 width=95></td>
</tr>
<tr>
<td>Lola & Virgínia 1</td>
<td>0</td>
<td>Lola & Virginia 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M31.15F.jpg alt="lola & virginia 1" height=110 width=95></td>
</tr>
<tr>
<td>Lola & Virgínia 2</td>
<td>0</td>
<td>Lola & Virginia 2</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M32.15F.jpg alt="lola & virginia 2" height=110 width=95></td>
</tr>
<tr>
<td>Londres</td>
<td>0</td>
<td>Londres</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M33.15F.jpg alt="londres" height=110 width=95></td>
</tr>
<tr>
<td>Lost in Translation - O Amor é um Lugar Estranho</td>
<td>Lost in Translation</td>
<td>Lost in Translation - O Amor e um Lugar Estranho</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5608652023375.15F.jpg alt="lost in translation - o amor e um lugar estranho" height=110 width=95></td>
</tr>
<tr>
<td>Louca por compras</td>
<td>Confessions of a Shopaholic</td>
<td>Louca por compras</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5601887537563.15F.jpg alt="louca por compras" height=110 width=95></td>
</tr>
<tr>
<td>Loucuras em Las Vegas</td>
<td>What Happens in Vegas</td>
<td>Loucuras em Las Vegas</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\024543528784F.jpg alt="loucuras em las vegas" height=110 width=95></td>
</tr>
<tr>
<td>Lua nova</td>
<td>The Twilight Saga: New Moon</td>
<td>Lua nova</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>130</td>
<td>Drama</td>
<td><img src=Images\5601887556519.15F.jpg alt="lua nova" height=110 width=95></td>
</tr>
<tr>
<td>Luther</td>
<td>0</td>
<td>Luther</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\I7103BADC4095BE09.15F.jpg alt="luther" height=110 width=95></td>
</tr>
<tr>
<td>Má vizinhança</td>
<td>Bad Neighbours</td>
<td>Ma vizinhanca</td>
<td></td>
<td>X</td>
<td>2014</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5053083001476.4F.jpg alt="ma vizinhanca" height=110 width=95></td>
</tr>
<tr>
<td>Macacos no espaço</td>
<td>Space Chimps</td>
<td>Macacos no espaco</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>77</td>
<td>Animação</td>
<td><img src=Images\I07426E9EA7A22095.15F.jpg alt="macacos no espaco" height=110 width=95></td>
</tr>
<tr>
<td>Madagáscar 2</td>
<td>Madagascar: Escape 2 Africa</td>
<td>Madagascar 2</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>86</td>
<td>Animação</td>
<td><img src=Images\5601887533213.15F.jpg alt="madagascar 2" height=110 width=95></td>
</tr>
<tr>
<td>Mafalda - O Filme</td>
<td>Mafalda</td>
<td>Mafalda - O Filme</td>
<td>X</td>
<td>X</td>
<td>1979</td>
<td>75</td>
<td>0</td>
<td><img src=Images\5604779047034.15F.jpg alt="mafalda - o filme" height=110 width=95></td>
</tr>
<tr>
<td>Mafioso quanto baste</td>
<td>Find Me Guilty</td>
<td>Mafioso quanto baste</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>124</td>
<td>Comédia</td>
<td><img src=Images\5602193335300.15F.jpg alt="mafioso quanto baste" height=110 width=95></td>
</tr>
<tr>
<td>Magnolia</td>
<td>0</td>
<td>Magnolia</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>180</td>
<td>Drama</td>
<td><img src=Images\5605248029667.15F.jpg alt="magnolia" height=110 width=95></td>
</tr>
<tr>
<td>Malavita</td>
<td>Malavita aka The Family</td>
<td>Malavita</td>
<td>X</td>
<td>X</td>
<td>2013</td>
<td>111</td>
<td>Comédia</td>
<td><img src=Images\5601887602667.15F.jpg alt="malavita" height=110 width=95></td>
</tr>
<tr>
<td>Malcolm X</td>
<td>0</td>
<td>Malcolm X</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>193</td>
<td>Drama</td>
<td><img src=Images\5601887458592.15F.jpg alt="malcolm x" height=110 width=95></td>
</tr>
<tr>
<td>Mamma Mia!: O Filme</td>
<td>Mamma Mia!</td>
<td>Mamma Mia!: O Filme</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>104</td>
<td>Musical</td>
<td><img src=Images\5050582595826.15F.jpg alt="mamma mia!: o filme" height=110 width=95></td>
</tr>
<tr>
<td>Mandela Meu Prisioneiro Meu Amigo</td>
<td>Goodbye Bafana</td>
<td>Mandela Meu Prisioneiro Meu Amigo</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>113</td>
<td>0</td>
<td><img src=Images\5608652032216.15F.jpg alt="mandela meu prisioneiro meu amigo" height=110 width=95></td>
</tr>
<tr>
<td>Manobras na Casa Branca</td>
<td>Wag the Dog</td>
<td>Manobras na Casa Branca</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>92</td>
<td>Comédia</td>
<td><img src=Images\5602193307055.15F.jpg alt="manobras na casa branca" height=110 width=95></td>
</tr>
<tr>
<td>Máquina Zero</td>
<td>Jarhead</td>
<td>Maquina Zero</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5050582411447.15F.jpg alt="maquina zero" height=110 width=95></td>
</tr>
<tr>
<td>Marados da dança</td>
<td>Dance Flick</td>
<td>Marados da danca</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>83</td>
<td>Comédia</td>
<td><img src=Images\5601887553860.15F.jpg alt="marados da danca" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Crimson Tide</td>
<td><NAME></td>
<td></td>
<td>X</td>
<td>1995</td>
<td>111</td>
<td>Acção</td>
<td><img src=Images\5601887447084.15F.jpg alt="mare vermelha" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME>inette</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\8414533042147.15F.jpg alt="marie antoinette" height=110 width=95></td>
</tr>
<tr>
<td>Master and Commander - O Lado Longínquo do Mundo</td>
<td>Master and Commander: The Far Side of the World</td>
<td>Master and Commander - O Lado Longinquo do Mundo</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>133</td>
<td>Acção</td>
<td><img src=Images\5600304166478.15F.jpg alt="master and commander - o lado longinquo do mundo" height=110 width=95></td>
</tr>
<tr>
<td>Match Point</td>
<td>0</td>
<td>Match Point</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\IED436C5B800B15B2.15F.jpg alt="match point" height=110 width=95></td>
</tr>
<tr>
<td>Matéria Negra</td>
<td>Dark Matter</td>
<td>Materia Negra</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>85</td>
<td>Drama</td>
<td><img src=Images\I080428513E22BD84.15F.jpg alt="materia negra" height=110 width=95></td>
</tr>
<tr>
<td>Matrix</td>
<td>The Matrix</td>
<td>Matrix</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>131</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887403394.15F.jpg alt="matrix" height=110 width=95></td>
</tr>
<tr>
<td>Matrix Reloaded</td>
<td>The Matrix Reloaded</td>
<td>Matrix Reloaded</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>132</td>
<td>Ficção Científica</td>
<td><img src=Images\7321976286483.15F.jpg alt="matrix reloaded" height=110 width=95></td>
</tr>
<tr>
<td>Matrix Revolutions</td>
<td>The Matrix Revolutions</td>
<td>Matrix Revolutions</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>124</td>
<td>Ficção Científica</td>
<td><img src=Images\7321976332098.15F.jpg alt="matrix revolutions" height=110 width=95></td>
</tr>
<tr>
<td>Max Payne</td>
<td>0</td>
<td>Max Payne</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>99</td>
<td>Fantasia</td>
<td><img src=Images\5600304208697.15F.jpg alt="max payne" height=110 width=95></td>
</tr>
<tr>
<td>Máximo 10 Unidades</td>
<td>10 Items or Less</td>
<td>Maximo 10 Unidades</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>77</td>
<td>Drama</td>
<td><img src=Images\5608652031790.15F.jpg alt="maximo 10 unidades" height=110 width=95></td>
</tr>
<tr>
<td>McQuade - O Lobo Solitário</td>
<td>Lone Wolf McQuade</td>
<td>McQuade - O Lobo Solitario</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>103</td>
<td>Acção</td>
<td><img src=Images\5608652020510.15F.jpg alt="mcquade - o lobo solitario" height=110 width=95></td>
</tr>
<tr>
<td>Medidas Extremas</td>
<td>Extreme Measures</td>
<td>Medidas Extremas</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>114</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304181327.15F.jpg alt="medidas extremas" height=110 width=95></td>
</tr>
<tr>
<td>Miami Vice</td>
<td>0</td>
<td>Miami Vice</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>126</td>
<td>Acção</td>
<td><img src=Images\5050582466058.15F.jpg alt="miami vice" height=110 width=95></td>
</tr>
<tr>
<td>MIB: Homens de Negro</td>
<td>Men in Black</td>
<td>MIB: Homens de Negro</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>94</td>
<td>Acção</td>
<td><img src=Images\5601887411849.15F.jpg alt="mib: homens de negro" height=110 width=95></td>
</tr>
<tr>
<td>MIB: Homens De Negro 2</td>
<td>Men in Black II</td>
<td>MIB: Homens De Negro 2</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>94</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887444250.15F.jpg alt="mib: homens de negro 2" height=110 width=95></td>
</tr>
<tr>
<td><NAME> - Uma Questão de Consciência</td>
<td><NAME></td>
<td><NAME> - Uma Questao de Consciencia</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>115</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887523313.15F.jpg alt="<NAME> - uma questao de consciencia" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME>lant</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>99</td>
<td>Acção</td>
<td><img src=Images\5601887461493.15F.jpg alt="michel vaillant" height=110 width=95></td>
</tr>
<tr>
<td>Mickey - Um Natal Mágico</td>
<td>Mickey's once upon a Christmas</td>
<td>Mickey - Um Natal Magico</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>63</td>
<td>Animação</td>
<td><img src=Images\5601887466405.15F.jpg alt="mickey - um natal magico" height=110 width=95></td>
</tr>
<tr>
<td><NAME>: Os Tres Mosqueteiros</td>
<td>Mickey - Donald - Goofy: The Three Musketeers</td>
<td><NAME>: Os Tres Mosqueteiros</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>66</td>
<td>Animação</td>
<td><img src=Images\5601887462858.15F.jpg alt="mic<NAME>: os tres mosqueteiros" height=110 width=95></td>
</tr>
<tr>
<td>Milk</td>
<td>0</td>
<td>Milk</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5600304203166.15F.jpg alt="milk" height=110 width=95></td>
</tr>
<tr>
<td>Million Dollar Baby - Sonhos Vencidos</td>
<td>Million Dollar Baby</td>
<td>Million Dollar Baby - Sonhos Vencidos</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>127</td>
<td>Drama</td>
<td><img src=Images\5601887471485.15F.jpg alt="million dollar baby - sonhos vencidos" height=110 width=95></td>
</tr>
<tr>
<td>Miss Detective</td>
<td>Miss Congeniality</td>
<td>Miss Detective</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>106</td>
<td>0</td>
<td><img src=Images\5601887424160.15F.jpg alt="miss detective" height=110 width=95></td>
</tr>
<tr>
<td>Miss Detective 2: Armada e Fabulosa</td>
<td>Miss Congeniality 2: Armed & Fabulous</td>
<td>Miss Detective 2: Armada e Fabulosa</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>110</td>
<td>Comédia</td>
<td><img src=Images\7321976593314.15F.jpg alt="miss detective 2: armada e fabulosa" height=110 width=95></td>
</tr>
<tr>
<td>Missão Impossível</td>
<td>Mission: Impossible</td>
<td>Missao Impossivel</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>105</td>
<td>Acção</td>
<td><img src=Images\5601887417292.15F.jpg alt="missao impossivel" height=110 width=95></td>
</tr>
<tr>
<td>Missão Ultra-Secreta</td>
<td>For Your Eyes Only</td>
<td>Missao Ultra-Secreta</td>
<td>X</td>
<td>X</td>
<td>1981</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\I34B3F0B28957894A.15F.jpg alt="missao ultra-secreta" height=110 width=95></td>
</tr>
<tr>
<td>Missão: Impossível 2</td>
<td>Mission: Impossible II</td>
<td>Missao: Impossivel 2</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>118</td>
<td>Acção</td>
<td><img src=Images\5601887417841.15F.jpg alt="missao: impossivel 2" height=110 width=95></td>
</tr>
<tr>
<td>Mistérios de Lisboa</td>
<td>0</td>
<td>Misterios de Lisboa</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>266</td>
<td>Drama</td>
<td><img src=Images\5606699511183.15F.jpg alt="misterios de lisboa" height=110 width=95></td>
</tr>
<tr>
<td>Mistérios do sexo oposto</td>
<td>Town & Country</td>
<td>Misterios do sexo oposto</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5601887434473.15F.jpg alt="misterios do sexo oposto" height=110 width=95></td>
</tr>
<tr>
<td>Modesty Blaise - Jogo explosivo</td>
<td>My Name Is Modesty: A Modesty Blaise Adventure</td>
<td>Modesty Blaise - Jogo explosivo</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>75</td>
<td>Drama</td>
<td><img src=Images\5600304161336.15F.jpg alt="modesty blaise - jogo explosivo" height=110 width=95></td>
</tr>
<tr>
<td>Momentos Hilariantes</td>
<td>0</td>
<td>Momentos Hilariantes</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M114.15F.jpg alt="momentos hilariantes" height=110 width=95></td>
</tr>
<tr>
<td>Monkeybone - O Rei da Macacada</td>
<td>Monkeybone</td>
<td>Monkeybone - O Rei da Macacada</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\5600304165372.15F.jpg alt="monkeybone - o rei da macacada" height=110 width=95></td>
</tr>
<tr>
<td>Monster's Ball - Depois do Ódio</td>
<td>Monster's Ball</td>
<td>Monster's Ball - Depois do Odio</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>112</td>
<td>Drama</td>
<td><img src=Images\5608652034258.15F.jpg alt="monster's ball - depois do odio" height=110 width=95></td>
</tr>
<tr>
<td>Monstros e Companhia</td>
<td>Monsters, Inc.</td>
<td>Monstros e Companhia</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>88</td>
<td>0</td>
<td><img src=Images\5601887433414.15F.jpg alt="monstros e companhia" height=110 width=95></td>
</tr>
<tr>
<td>Monstros vs Aliens</td>
<td>Monsters vs Aliens</td>
<td>Monstros vs Aliens</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>90</td>
<td>Animação</td>
<td><img src=Images\5601887541201.15F.jpg alt="monstros vs aliens" height=110 width=95></td>
</tr>
<tr>
<td>Monty Python - E Agora Algo Completamente Diferente</td>
<td>And Now for Something Completely Different</td>
<td>Monty Python - E Agora Algo Completamente Diferente</td>
<td></td>
<td>X</td>
<td>1971</td>
<td>85</td>
<td>Comédia</td>
<td><img src=Images\5608652024013.15F.jpg alt="monty python - e agora algo completamente diferente" height=110 width=95></td>
</tr>
<tr>
<td>Monty Python e o Cálice Sagrado</td>
<td>Monty Python and the Holy Grail</td>
<td>Monty Python e o Calice Sagrado</td>
<td>X</td>
<td>X</td>
<td>1975</td>
<td>86</td>
<td>Comédia</td>
<td><img src=Images\5601887438730.15F.jpg alt="monty python e o calice sagrado" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Die Another Day</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>127</td>
<td>Acção</td>
<td><img src=Images\I3D44DA5F1C750D1E.15F.jpg alt="morre noutro dia" height=110 width=95></td>
</tr>
<tr>
<td>Moulin Rouge</td>
<td>Moulin Rouge!</td>
<td>Moulin Rouge</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>123</td>
<td>Musical</td>
<td><img src=Images\8010312054242.13F.jpg alt="moulin rouge" height=110 width=95></td>
</tr>
<tr>
<td>Mr. & Mrs. Smith</td>
<td>0</td>
<td>Mr. & Mrs. Smith</td>
<td>X</td>
<td></td>
<td>2005</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\5600304166508.15F.jpg alt="mr. & mrs. smith" height=110 width=95></td>
</tr>
<tr>
<td>Mulan</td>
<td>0</td>
<td>Mulan</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>84</td>
<td>Animação</td>
<td><img src=Images\5601887404513.15F.jpg alt="mulan" height=110 width=95></td>
</tr>
<tr>
<td>Mulher Com Cão Procura Homem Com Coração</td>
<td>Must Love Dogs</td>
<td>Mulher Com Cao Procura Homem Com Coracao</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\7321977593450.15F.jpg alt="mulher com cao procura homem com coracao" height=110 width=95></td>
</tr>
<tr>
<td>Mulher Fatal</td>
<td>Femme Fatale</td>
<td>Mulher Fatal</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887447008.15F.jpg alt="mulher fatal" height=110 width=95></td>
</tr>
<tr>
<td>Mulher Por Cima</td>
<td>Woman On Top</td>
<td>Mulher Por Cima</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>88</td>
<td>Comédia</td>
<td><img src=Images\5600304168878.15F.jpg alt="mulher por cima" height=110 width=95></td>
</tr>
<tr>
<td>Mulheres à Beira de um Ataque de Nervos</td>
<td>Mujeres al borde de un ataque de nervios</td>
<td>Mulheres a Beira de um Ataque de Nervos</td>
<td>X</td>
<td>X</td>
<td>1988</td>
<td>85</td>
<td>Comédia</td>
<td><img src=Images\5602193347907.15F.jpg alt="mulheres a beira de um ataque de nervos" height=110 width=95></td>
</tr>
<tr>
<td>Mulheres Perfeitas</td>
<td>The Stepford Wives</td>
<td>Mulheres Perfeitas</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>89</td>
<td>Drama</td>
<td><img src=Images\5050583016238.15F.jpg alt="mulheres perfeitas" height=110 width=95></td>
</tr>
<tr>
<td>Mundo jurássico</td>
<td>Jurassic World</td>
<td>Mundo jurassico</td>
<td>X</td>
<td>X</td>
<td>2015</td>
<td>124</td>
<td>Ficção Científica</td>
<td><img src=Images\025192212192F.jpg alt="mundo jurassico" height=110 width=95></td>
</tr>
<tr>
<td>Munique</td>
<td>Munich</td>
<td>Munique</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>157</td>
<td>Drama</td>
<td><img src=Images\5050583028743.15F.jpg alt="munique" height=110 width=95></td>
</tr>
<tr>
<td>Música no Coração</td>
<td>The Sound of Music</td>
<td>Musica no Coracao</td>
<td>X</td>
<td>X</td>
<td>1965</td>
<td>167</td>
<td>Musical</td>
<td><img src=Images\5608652006255.15F.jpg alt="musica no coracao" height=110 width=95></td>
</tr>
<tr>
<td>Na Sombra de Um Rapto</td>
<td>The Clearing</td>
<td>Na Sombra de Um Rapto</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>91</td>
<td>Drama</td>
<td><img src=Images\5608652026444.15F.jpg alt="na sombra de um rapto" height=110 width=95></td>
</tr>
<tr>
<td>Na Sombra do Assassino</td>
<td>Shadowboxer</td>
<td>Na Sombra do Assassino</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>93</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652031110.15F.jpg alt="na sombra do assassino" height=110 width=95></td>
</tr>
<tr>
<td>Na sombra do caçador</td>
<td>The Hunting Party</td>
<td>Na sombra do cacador</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887524235.15F.jpg alt="na sombra do cacador" height=110 width=95></td>
</tr>
<tr>
<td>Na Sombra e No Silêncio</td>
<td>To Kill a Mockingbird</td>
<td>Na Sombra e No Silencio</td>
<td>X</td>
<td>X</td>
<td>1962</td>
<td>124</td>
<td>0</td>
<td><img src=Images\5601887415137.15F.jpg alt="na sombra e no silencio" height=110 width=95></td>
</tr>
<tr>
<td>Nadine - Um Amor à Prova de Bala</td>
<td>Nadine</td>
<td>Nadine - Um Amor a Prova de Bala</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>79</td>
<td>Acção</td>
<td><img src=Images\8414533029803.15F.jpg alt="nadine - um amor a prova de bala" height=110 width=95></td>
</tr>
<tr>
<td><NAME> - A Ama Mágica</td>
<td><NAME></td>
<td><NAME> - A Ama Magica</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>94</td>
<td>Família</td>
<td><img src=Images\5050582349399.15F.jpg alt="nanny mcphee - a ama magica" height=110 width=95></td>
</tr>
<tr>
<td>Não Brinques Com Estranhos</td>
<td><NAME></td>
<td>Nao Brinques Com Estranhos</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>94</td>
<td>Horror</td>
<td><img src=Images\5608652011907.15F.jpg alt="nao brinques com estranhos" height=110 width=95></td>
</tr>
<tr>
<td>Narc</td>
<td>0</td>
<td>Narc</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5050582292145.15F.jpg alt="narc" height=110 width=95></td>
</tr>
<tr>
<td>Nascido a 4 de Julho</td>
<td>Born on the Fourth of July</td>
<td>Nascido a 4 de Julho</td>
<td></td>
<td>X</td>
<td>1989</td>
<td>138</td>
<td>Drama</td>
<td><img src=Images\5050582038859.15F.jpg alt="nascido a 4 de julho" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic - A Jornada do Homem</td>
<td>0</td>
<td>National Geographic - A Jornada do Homem</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>93</td>
<td>Documentário</td>
<td><img src=Images\5601887531134.15F.jpg alt="national geographic - a jornada do homem" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A clonagem</td>
<td>0</td>
<td>National Geographic: A clonagem</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M113.15F.jpg alt="national geographic: a clonagem" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A explosão solar</td>
<td>0</td>
<td>National Geographic: A explosao solar</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M41.15F.jpg alt="national geographic: a explosao solar" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A ilha da Páscoa</td>
<td>0</td>
<td>National Geographic: A ilha da Pascoa</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M42.15F.jpg alt="national geographic: a ilha da pascoa" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A Incrível Máquina Humana</td>
<td>Incredible Human Machine</td>
<td>National Geographic: A Incrivel Maquina Humana</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Documentário</td>
<td><img src=Images\5601887499922.15F.jpg alt="national geographic: a incrivel maquina humana" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A montanha mágica</td>
<td>0</td>
<td>National Geographic: A montanha magica</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M43.15F.jpg alt="national geographic: a montanha magica" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: A viagem perdida de Darwin</td>
<td>0</td>
<td>National Geographic: A viagem perdida de Darwin</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M44.15F.jpg alt="national geographic: a viagem perdida de darwin" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Caçador de vulcões</td>
<td>0</td>
<td>National Geographic: Cacador de vulcoes</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M45.15F.jpg alt="national geographic: cacador de vulcoes" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Corpos em transformação</td>
<td>0</td>
<td>National Geographic: Corpos em transformacao</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M46.15F.jpg alt="national geographic: corpos em transformacao" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Engenharia Ecológica</td>
<td>Eco Engineering Geothermal - The Heat from Within</td>
<td>National Geographic: Engenharia Ecologica</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>50</td>
<td>Documentário</td>
<td><img src=Images\5601887535347.15F.jpg alt="national geographic: engenharia ecologica" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Gorongosa</td>
<td>0</td>
<td>National Geographic: Gorongosa</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M47.15F.jpg alt="national geographic: gorongosa" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: O faraó Guerreiro</td>
<td>0</td>
<td>National Geographic: O farao Guerreiro</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M48.15F.jpg alt="national geographic: o farao guerreiro" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: O incrível corpo humano</td>
<td>0</td>
<td>National Geographic: O incrivel corpo humano</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M49.15F.jpg alt="national geographic: o incrivel corpo humano" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Radiografia do planeta</td>
<td>0</td>
<td>National Geographic: Radiografia do planeta</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M50.15F.jpg alt="national geographic: radiografia do planeta" height=110 width=95></td>
</tr>
<tr>
<td>National Geographic: Segredos do mediterrâneo</td>
<td>0</td>
<td>National Geographic: Segredos do mediterraneo</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M51.15F.jpg alt="national geographic: segredos do mediterraneo" height=110 width=95></td>
</tr>
<tr>
<td>Negros Hábitos</td>
<td>Entre Tinieblas</td>
<td>Negros Habitos</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>110</td>
<td>Drama</td>
<td><img src=Images\5602193347938.15F.jpg alt="negros habitos" height=110 width=95></td>
</tr>
<tr>
<td>Nem Contigo... Nem Sem Ti!</td>
<td>I Could Never Be Your Woman</td>
<td>Nem Contigo... Nem Sem Ti!</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5601887498543.15F.jpg alt="nem contigo... nem sem ti!" height=110 width=95></td>
</tr>
<tr>
<td>Nem Uma Palavra</td>
<td>Don't Say a Word</td>
<td>Nem Uma Palavra</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>109</td>
<td>Acção</td>
<td><img src=Images\5608652011563.15F.jpg alt="nem uma palavra" height=110 width=95></td>
</tr>
<tr>
<td>Next - Sem Alternativa</td>
<td>Next</td>
<td>Next - Sem Alternativa</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>92</td>
<td>0</td>
<td><img src=Images\5602193339377.15F.jpg alt="next - sem alternativa" height=110 width=95></td>
</tr>
<tr>
<td>Nicky Filho... do Diabo</td>
<td>Little Nicky</td>
<td>Nicky Filho... do Diabo</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5601887425976.15F.jpg alt="nicky filho... do diabo" height=110 width=95></td>
</tr>
<tr>
<td>No Limiar da Verdade</td>
<td>Half Light</td>
<td>No Limiar da Verdade</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>105</td>
<td>0</td>
<td><img src=Images\5601887486212.15F.jpg alt="no limiar da verdade" height=110 width=95></td>
</tr>
<tr>
<td>No limite</td>
<td>The Edge</td>
<td>No limite</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5600304163484.15F.jpg alt="no limite" height=110 width=95></td>
</tr>
<tr>
<td>No Mundo das Mulheres</td>
<td>In the Land of Women</td>
<td>No Mundo das Mulheres</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\5602193346139.15F.jpg alt="no mundo das mulheres" height=110 width=95></td>
</tr>
<tr>
<td>Noiva Procura-se</td>
<td>The Bachelor</td>
<td>Noiva Procura-se</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\5601887426454.15F.jpg alt="noiva procura-se" height=110 width=95></td>
</tr>
<tr>
<td>Nome de Código Mercúrio</td>
<td>Mercury Rising</td>
<td>Nome de Codigo Mercurio</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>112</td>
<td>Acção</td>
<td><img src=Images\5601887404162.15F.jpg alt="nome de codigo mercurio" height=110 width=95></td>
</tr>
<tr>
<td>Nome de código: Limpeza</td>
<td>Code Name: The Cleaner</td>
<td>Nome de codigo: Limpeza</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>0</td>
<td><img src=Images\9321337094366.2F.jpg alt="nome de codigo: limpeza" height=110 width=95></td>
</tr>
<tr>
<td>Nos Limites Do Silêncio</td>
<td>The Unsaid</td>
<td>Nos Limites Do Silencio</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>105</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I40BC22D45FAF2709.15F.jpg alt="nos limites do silencio" height=110 width=95></td>
</tr>
<tr>
<td>Notting Hill</td>
<td>0</td>
<td>Notting Hill</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>119</td>
<td>Comédia</td>
<td><img src=Images\5601887426669.15F.jpg alt="notting hill" height=110 width=95></td>
</tr>
<tr>
<td>Nova Iorque - Uma História de Amor</td>
<td>Sidewalks Of New York</td>
<td>Nova Iorque - Uma Historia de Amor</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>103</td>
<td>Comédia</td>
<td><img src=Images\5601887434176.15F.jpg alt="nova iorque - uma historia de amor" height=110 width=95></td>
</tr>
<tr>
<td>Nove</td>
<td>Nine</td>
<td>Nove</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5600304214889.15F.jpg alt="nove" height=110 width=95></td>
</tr>
<tr>
<td>Nove Meses</td>
<td>Nine Months</td>
<td>Nove Meses</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>106</td>
<td>Comédia</td>
<td><img src=Images\5600304193603.15F.jpg alt="nove meses" height=110 width=95></td>
</tr>
<tr>
<td>Nove Semanas e Meia</td>
<td>9 1/2 Weeks</td>
<td>Nove Semanas e Meia</td>
<td>X</td>
<td>X</td>
<td>1986</td>
<td>93</td>
<td>Romance</td>
<td><img src=Images\5600304162654.15F.jpg alt="nove semanas e meia" height=110 width=95></td>
</tr>
<tr>
<td>Número 17</td>
<td>0</td>
<td>Numero 17</td>
<td>X</td>
<td>X</td>
<td>1932</td>
<td>64</td>
<td>Suspense/Thriller</td>
<td><img src=Images\IBDB92789D885CA39.15F.jpg alt="numero 17" height=110 width=95></td>
</tr>
<tr>
<td>Número 23</td>
<td>The Number 23</td>
<td>Numero 23</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>97</td>
<td>Drama</td>
<td><img src=Images\5602193337670.15F.jpg alt="numero 23" height=110 width=95></td>
</tr>
<tr>
<td>Nunca é Tarde</td>
<td>0</td>
<td>Nunca e Tarde</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5601887417131.15F.jpg alt="nunca e tarde" height=110 width=95></td>
</tr>
<tr>
<td>Nuremberg</td>
<td>0</td>
<td>Nuremberg</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>186</td>
<td>Drama</td>
<td><img src=Images\I2E343688538747A8.15F.jpg alt="nuremberg" height=110 width=95></td>
</tr>
<tr>
<td>O 6º Dia</td>
<td>The 6th Day</td>
<td>O 6º Dia</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>118</td>
<td>Acção</td>
<td><img src=Images\5601887420278.15F.jpg alt="o 6º dia" height=110 width=95></td>
</tr>
<tr>
<td>O Agente Disfarçado</td>
<td>Big Momma's House</td>
<td>O Agente Disfarcado</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>98</td>
<td>Comédia</td>
<td><img src=Images\5600304164467.15F.jpg alt="o agente disfarcado" height=110 width=95></td>
</tr>
<tr>
<td>O Agente Irresistivel</td>
<td>The Spy Who Loved Me</td>
<td>O Agente Irresistivel</td>
<td>X</td>
<td>X</td>
<td>1977</td>
<td>120</td>
<td>Acção</td>
<td><img src=Images\IF3B94BDF334447AB.15F.jpg alt="o agente irresistivel" height=110 width=95></td>
</tr>
<tr>
<td>O Agente secreto</td>
<td>Secret Agent</td>
<td>O Agente secreto</td>
<td>X</td>
<td>X</td>
<td>1936</td>
<td>85</td>
<td>Suspense/Thriller</td>
<td><img src=Images\IC49670A63375F3CC.15F.jpg alt="o agente secreto" height=110 width=95></td>
</tr>
<tr>
<td>O Alfaiate do Panamá</td>
<td>The Tailor of Panamá</td>
<td>O Alfaiate do Panama</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5601887425495.15F.jpg alt="o alfaiate do panama" height=110 width=95></td>
</tr>
<tr>
<td>O <NAME></td>
<td>Tomorrow Never Dies</td>
<td>O <NAME></td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>114</td>
<td>Acção</td>
<td><img src=Images\IE49F4E34E8436066.15F.jpg alt="o amanha nunca morre" height=110 width=95></td>
</tr>
<tr>
<td>O Amigo Oculto</td>
<td>Hide and Seek</td>
<td>O Amigo Oculto</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>97</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652026833.15F.jpg alt="o amigo oculto" height=110 width=95></td>
</tr>
<tr>
<td>O Amor <NAME></td>
<td>The Holiday</td>
<td>O Amor Nao Tira Ferias</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>130</td>
<td>Romance</td>
<td><img src=Images\5050582479980.15F.jpg alt="o amor nao tira ferias" height=110 width=95></td>
</tr>
<tr>
<td>O Artista</td>
<td>The Artist</td>
<td>O Artista</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>96</td>
<td>Drama</td>
<td><img src=Images\5600402415072.15F.jpg alt="o artista" height=110 width=95></td>
</tr>
<tr>
<td>O Assassínio de <NAME></td>
<td>The Assassination of <NAME></td>
<td>O Assassinio de <NAME></td>
<td></td>
<td>X</td>
<td>2004</td>
<td>91</td>
<td>Crime</td>
<td><img src=Images\5608652027281.15F.jpg alt="o assassinio de <NAME>" height=110 width=95></td>
</tr>
<tr>
<td>O Assassino Da Porta Ao Lado</td>
<td>0</td>
<td>O Assassino Da Porta Ao Lado</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M53.15F.jpg alt="o assassino da porta ao lado" height=110 width=95></td>
</tr>
<tr>
<td>O Assassino do Alfabeto</td>
<td>The Alphabet Killer</td>
<td>O Assassino do Alfabeto</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>94</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5606320000468.15F.jpg alt="o assassino do alfabeto" height=110 width=95></td>
</tr>
<tr>
<td>O Assassino do Presidente</td>
<td>Blind Horizon</td>
<td>O Assassino do Presidente</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>108</td>
<td>0</td>
<td><img src=Images\5050582276183.15F.jpg alt="o assassino do presidente" height=110 width=95></td>
</tr>
<tr>
<td>O atirador</td>
<td>Shooter</td>
<td>O atirador</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>126</td>
<td>Acção</td>
<td><img src=Images\5601887495665.15F.jpg alt="o atirador" height=110 width=95></td>
</tr>
<tr>
<td>O Aviador</td>
<td>The Aviator</td>
<td>O Aviador</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>163</td>
<td>Drama</td>
<td><img src=Images\5602193323895.15F.jpg alt="o aviador" height=110 width=95></td>
</tr>
<tr>
<td>O Banquete do amor</td>
<td>Feast of Love</td>
<td>O Banquete do amor</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5601887522644.15F.jpg alt="o banquete do amor" height=110 width=95></td>
</tr>
<tr>
<td>O Barbeiro</td>
<td>The Man Who Wasn't There</td>
<td>O Barbeiro</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\5602193309356.15F.jpg alt="o barbeiro" height=110 width=95></td>
</tr>
<tr>
<td>O Bom Pastor</td>
<td>The Good Shepherd</td>
<td>O Bom Pastor</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>160</td>
<td>0</td>
<td><img src=Images\5601887494019.15F.jpg alt="o bom pastor" height=110 width=95></td>
</tr>
<tr>
<td>O Bom, o Mau e o Vilão</td>
<td>Il buono, il brutto, il cattivo</td>
<td>O Bom, o Mau e o Vilao</td>
<td>X</td>
<td>X</td>
<td>1966</td>
<td>171</td>
<td>Acção</td>
<td><img src=Images\5600304177924.15F.jpg alt="o bom, o mau e o vilao" height=110 width=95></td>
</tr>
<tr>
<td>O Bombeiro SAM</td>
<td>0</td>
<td>O Bombeiro SAM</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M54.15F.jpg alt="o bombeiro sam" height=110 width=95></td>
</tr>
<tr>
<td>O Cabo do Medo</td>
<td>Cape Fear</td>
<td>O Cabo do Medo</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>123</td>
<td>Horror</td>
<td><img src=Images\5050582039764.15F.jpg alt="o cabo do medo" height=110 width=95></td>
</tr>
<tr>
<td>O Caçador</td>
<td>The Deer Hunter</td>
<td>O Cacador</td>
<td>X</td>
<td>X</td>
<td>1978</td>
<td>175</td>
<td>Drama</td>
<td><img src=Images\I0586AEA9A179DDDE.15F.jpg alt="o cacador" height=110 width=95></td>
</tr>
<tr>
<td>O caminho do poder</td>
<td>All the King's Men</td>
<td>O caminho do poder</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>122</td>
<td>Drama</td>
<td><img src=Images\8414533040532.15F.jpg alt="o caminho do poder" height=110 width=95></td>
</tr>
<tr>
<td>O Caminho para El Dorado</td>
<td>The Road to El Dorado</td>
<td>O Caminho para El Dorado</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>89</td>
<td>0</td>
<td><img src=Images\0678149092691.15F.jpg alt="o caminho para el dorado" height=110 width=95></td>
</tr>
<tr>
<td>O Candidato da Verdade</td>
<td>The Manchurian Candidate</td>
<td>O Candidato da Verdade</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>125</td>
<td>0</td>
<td><img src=Images\5601887469345.15F.jpg alt="o candidato da verdade" height=110 width=95></td>
</tr>
<tr>
<td>O Capitão Corelli</td>
<td>Capt<NAME>andolin</td>
<td>O Capitao Corelli</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>124</td>
<td>0</td>
<td><img src=Images\5601887432110.15F.jpg alt="o capitao corelli" height=110 width=95></td>
</tr>
<tr>
<td>O Capuchinho Vermelho</td>
<td>0</td>
<td>O Capuchinho Vermelho</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M55.15F.jpg alt="o capuchinho vermelho" height=110 width=95></td>
</tr>
<tr>
<td>O Casamento do Meu Melhor Amigo</td>
<td>My Best Friend's Wedding</td>
<td>O Casamento do Meu Melhor Amigo</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5606376290110.15F.jpg alt="o casamento do meu melhor amigo" height=110 width=95></td>
</tr>
<tr>
<td>O Caso Farewell</td>
<td>L'<NAME></td>
<td>O Caso Farewell</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5606320011921.15F.jpg alt="o caso farewell" height=110 width=95></td>
</tr>
<tr>
<td>O Castelo Andante</td>
<td>Hauru no ugoku shiro</td>
<td>O Castelo Andante</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>116</td>
<td>Anime</td>
<td><img src=Images\5606118102350.15F.jpg alt="o castelo andante" height=110 width=95></td>
</tr>
<tr>
<td>O Cavaleiro Negro</td>
<td>Black Knight</td>
<td>O Cavaleiro Negro</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>92</td>
<td>Aventura</td>
<td><img src=Images\5600304162890.15F.jpg alt="o cavaleiro negro" height=110 width=95></td>
</tr>
<tr>
<td>O Chacal</td>
<td>The Jackal</td>
<td>O Chacal</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>119</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887425037.15F.jpg alt="o chacal" height=110 width=95></td>
</tr>
<tr>
<td>O código base</td>
<td>Source Code</td>
<td>O codigo base</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>89</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887572687.15F.jpg alt="o codigo base" height=110 width=95></td>
</tr>
<tr>
<td>O Código Da Vinci</td>
<td>The Da Vinci Code</td>
<td>O Codigo Da Vinci</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>143</td>
<td>Aventura</td>
<td><img src=Images\8414533037228.15F.jpg alt="o codigo da vinci" height=110 width=95></td>
</tr>
<tr>
<td>O Código Da Vinci Descodificado</td>
<td>Cracking the Da Vinci code</td>
<td>O Codigo Da Vinci Descodificado</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5602841048637.15F.jpg alt="o codigo da vinci descodificado" height=110 width=95></td>
</tr>
<tr>
<td>O Código de Cristo: O Túmulo Perdido</td>
<td>The Lost Tomb of Jesus</td>
<td>O Codigo de Cristo: O Tumulo Perdido</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>102</td>
<td>Documentário</td>
<td><img src=Images\5608652031721.15F.jpg alt="o codigo de cristo: o tumulo perdido" height=110 width=95></td>
</tr>
<tr>
<td>O Coleccionador de Ossos</td>
<td>The Bone Collector</td>
<td>O Coleccionador de Ossos</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>113</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887411054.15F.jpg alt="o coleccionador de ossos" height=110 width=95></td>
</tr>
<tr>
<td>O Comboio das 3 e 10</td>
<td>3:10 to Yuma</td>
<td>O Comboio das 3 e 10</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>117</td>
<td>Western</td>
<td><img src=Images\5608652036108.15F.jpg alt="o comboio das 3 e 10" height=110 width=95></td>
</tr>
<tr>
<td>O Conde de Monte Cristo</td>
<td>0</td>
<td>O Conde de Monte Cristo</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>Animação</td>
<td><img src=Images\M57.15F.jpg alt="o conde de monte cristo" height=110 width=95></td>
</tr>
<tr>
<td>O Condenado</td>
<td>The Woodsman</td>
<td>O Condenado</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>83</td>
<td>Drama</td>
<td><img src=Images\5608652027731.15F.jpg alt="o condenado" height=110 width=95></td>
</tr>
<tr>
<td>O Conselheiro</td>
<td>The Counselor</td>
<td>O Conselheiro</td>
<td>X</td>
<td>X</td>
<td>2013</td>
<td>117</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193508797.15F.jpg alt="o conselheiro" height=110 width=95></td>
</tr>
<tr>
<td>O Corcunda de Notre Dame</td>
<td>The Hunchback of Notre Dame</td>
<td>O Corcunda de Notre Dame</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>87</td>
<td>Animação</td>
<td><img src=Images\5601887424443.15F.jpg alt="o corcunda de notre dame" height=110 width=95></td>
</tr>
<tr>
<td>O Corpo</td>
<td>The Body</td>
<td>O Corpo</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>104</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887434114.15F.jpg alt="o corpo" height=110 width=95></td>
</tr>
<tr>
<td>O Corpo da Mentira</td>
<td>Body of Lies</td>
<td>O Corpo da Mentira</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>124</td>
<td>Acção</td>
<td><img src=Images\5600304201179.15F.jpg alt="o corpo da mentira" height=110 width=95></td>
</tr>
<tr>
<td>O Costa do Castelo</td>
<td>0</td>
<td>O Costa do Castelo</td>
<td>X</td>
<td>X</td>
<td>1943</td>
<td>135</td>
<td>0</td>
<td><img src=Images\5606699505168.15F.jpg alt="o costa do castelo" height=110 width=95></td>
</tr>
<tr>
<td>O Cume de Dante</td>
<td>Dante's Peak</td>
<td>O Cume de Dante</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\3259190266520.15F.jpg alt="o cume de dante" height=110 width=95></td>
</tr>
<tr>
<td>O Desconhecido do Norte Expresso</td>
<td>Strangers on a Train</td>
<td>O Desconhecido do Norte Expresso</td>
<td>X</td>
<td>X</td>
<td>1951</td>
<td>96</td>
<td>Suspense/Thriller</td>
<td><img src=Images\7321976319754.15F.jpg alt="o desconhecido do norte expresso" height=110 width=95></td>
</tr>
<tr>
<td>O Despertar da Mente</td>
<td>Eternal Sunshine of the Spotless Mind</td>
<td>O Despertar da Mente</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>103</td>
<td>Drama</td>
<td><img src=Images\5602193321006.15F.jpg alt="o despertar da mente" height=110 width=95></td>
</tr>
<tr>
<td>O Dia da Independência</td>
<td>Independence Day</td>
<td>O Dia da Independencia</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>147</td>
<td>Ficção Científica</td>
<td><img src=Images\5608652004954.15F.jpg alt="o dia da independencia" height=110 width=95></td>
</tr>
<tr>
<td>O Dia Depois de Amanhã</td>
<td>The Day After Tomorrow</td>
<td>O Dia Depois de Amanha</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>118</td>
<td>Acção</td>
<td><img src=Images\5608652023863.15F.jpg alt="o dia depois de amanha" height=110 width=95></td>
</tr>
<tr>
<td>O Dia em que a Terra Parou</td>
<td>The Day the Earth Stood Still</td>
<td>O Dia em que a Terra Parou</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>98</td>
<td>Ficção Científica</td>
<td><img src=Images\5600304208642.15F.jpg alt="o dia em que a terra parou" height=110 width=95></td>
</tr>
<tr>
<td>O Diabo Veste Prada</td>
<td>The Devil Wears Prada</td>
<td>O Diabo Veste Prada</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>105</td>
<td>Comédia</td>
<td><img src=Images\5602193501828.15F.jpg alt="o diabo veste prada" height=110 width=95></td>
</tr>
<tr>
<td>O Diário de Bridget Jones</td>
<td>Bridget Jones's Diary</td>
<td>O Diario de Bridget Jones</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5601887430116.15F.jpg alt="o diario de bridget jones" height=110 width=95></td>
</tr>
<tr>
<td>O discurso do rei</td>
<td>The King's Speech</td>
<td>O discurso do rei</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5601887569892.15F.jpg alt="o discurso do rei" height=110 width=95></td>
</tr>
<tr>
<td>O Divórcio</td>
<td>Le Divorce</td>
<td>O Divorcio</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>112</td>
<td>0</td>
<td><img src=Images\5608652021524.15F.jpg alt="o divorcio" height=110 width=95></td>
</tr>
<tr>
<td>O Dom</td>
<td>The Gift</td>
<td>O Dom</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>107</td>
<td>Drama</td>
<td><img src=Images\5601887428359.15F.jpg alt="o dom" height=110 width=95></td>
</tr>
<tr>
<td>O Enigma do Horizonte</td>
<td>Event Horizon</td>
<td>O Enigma do Horizonte</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>92</td>
<td>0</td>
<td><img src=Images\5601887413911.15F.jpg alt="o enigma do horizonte" height=110 width=95></td>
</tr>
<tr>
<td>O Enviado da Manchúria</td>
<td>The Manchurian Candidate</td>
<td>O Enviado da Manchuria</td>
<td>X</td>
<td>X</td>
<td>1962</td>
<td>121</td>
<td>Ficção Científica</td>
<td><img src=Images\5600304176965.15F.jpg alt="o enviado da manchuria" height=110 width=95></td>
</tr>
<tr>
<td>O Espião Acidental</td>
<td>Dak miu mai shing</td>
<td>O Espiao Acidental</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>84</td>
<td>Acção</td>
<td><img src=Images\5608652014915.15F.jpg alt="o espiao acidental" height=110 width=95></td>
</tr>
<tr>
<td>O Espião Sou Eu</td>
<td>I Spy</td>
<td>O Espiao Sou Eu</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>97</td>
<td>Suspense/Thriller</td>
<td><img src=Images\8414533022217.15F.jpg alt="o espiao sou eu" height=110 width=95></td>
</tr>
<tr>
<td>O Estranho Mundo de Jack</td>
<td>The Nightmare Before Christmas</td>
<td>O Estranho Mundo de Jack</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>73</td>
<td>Animação</td>
<td><img src=Images\5601887424559.15F.jpg alt="o estranho mundo de jack" height=110 width=95></td>
</tr>
<tr>
<td>O Falcão Inglês</td>
<td>The Limey</td>
<td>O Falcao Ingles</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>85</td>
<td>Drama</td>
<td><img src=Images\5601887427697.15F.jpg alt="o falcao ingles" height=110 width=95></td>
</tr>
<tr>
<td>O Fantasma</td>
<td>The Phantom</td>
<td>O Fantasma</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>169</td>
<td>Acção</td>
<td><img src=Images\5608652038300.15F.jpg alt="o fantasma" height=110 width=95></td>
</tr>
<tr>
<td>O Fantasma da Ópera</td>
<td>The Phantom of the Opera</td>
<td>O Fantasma da Opera</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>135</td>
<td>0</td>
<td><img src=Images\5608652026376.15F.jpg alt="o fantasma da opera" height=110 width=95></td>
</tr>
<tr>
<td>O Feitiço da Lua</td>
<td>Moonstruck</td>
<td>O Feitico da Lua</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>97</td>
<td>Romance</td>
<td><img src=Images\5600304177818.15F.jpg alt="o feitico da lua" height=110 width=95></td>
</tr>
<tr>
<td>O Fiel Jardineiro</td>
<td>The Constant Gardener</td>
<td>O Fiel Jardineiro</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>123</td>
<td>Drama</td>
<td><img src=Images\5608652028561.15F.jpg alt="o fiel jardineiro" height=110 width=95></td>
</tr>
<tr>
<td>O Filho da Noiva</td>
<td>El Hijo de la novia</td>
<td>O Filho da Noiva</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>120</td>
<td>Comédia</td>
<td><img src=Images\5608652015141.15F.jpg alt="o filho da noiva" height=110 width=95></td>
</tr>
<tr>
<td>O Furacão</td>
<td>The Hurricane</td>
<td>O Furacao</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>140</td>
<td>Drama</td>
<td><img src=Images\5601887410668.15F.jpg alt="o furacao" height=110 width=95></td>
</tr>
<tr>
<td>O Gang dos Tubarões</td>
<td>Shark Tale</td>
<td>O Gang dos Tubaroes</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>86</td>
<td>0</td>
<td><img src=Images\5050583018560.15F.jpg alt="o gang dos tubaroes" height=110 width=95></td>
</tr>
<tr>
<td>O Gato Das Botas</td>
<td>Puss in Boots</td>
<td>O Gato Das Botas</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>87</td>
<td>Animação</td>
<td><img src=Images\5601887577057.15F.jpg alt="o gato das botas" height=110 width=95></td>
</tr>
<tr>
<td>O Golpe de Baker Street</td>
<td>The Bank Job</td>
<td>O Golpe de Baker Street</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>107</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304205658.15F.jpg alt="o golpe de baker street" height=110 width=95></td>
</tr>
<tr>
<td>O Grande Elias</td>
<td>0</td>
<td>O Grande Elias</td>
<td>X</td>
<td>X</td>
<td>1950</td>
<td>108</td>
<td>Comédia</td>
<td><img src=Images\I66AA0AF4EF39916F.15F.jpg alt="o grande elias" height=110 width=95></td>
</tr>
<tr>
<td>O Grilo feliz</td>
<td>0</td>
<td>O Grilo feliz</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M60.15F.jpg alt="o grilo feliz" height=110 width=95></td>
</tr>
<tr>
<td>O Guarda Fraldas</td>
<td>Daddy Day Care</td>
<td>O Guarda Fraldas</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>88</td>
<td>Comédia</td>
<td><img src=Images\5601887460434.15F.jpg alt="o guarda fraldas" height=110 width=95></td>
</tr>
<tr>
<td>O Homem da Máscara de Ferro</td>
<td>The Man in The Iron Mask</td>
<td>O Homem da Mascara de Ferro</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>132</td>
<td>Acção</td>
<td><img src=Images\5600304217934.15F.jpg alt="o homem da mascara de ferro" height=110 width=95></td>
</tr>
<tr>
<td>O Homem da Pistola Dourada</td>
<td>The Man With the Golden Gun</td>
<td>O Homem da Pistola Dourada</td>
<td>X</td>
<td>X</td>
<td>1974</td>
<td>120</td>
<td>Acção</td>
<td><img src=Images\I1C67EC976EE68012.15F.jpg alt="o homem da pistola dourada" height=110 width=95></td>
</tr>
<tr>
<td>O Homem das Cavernas Vol. 1</td>
<td>0</td>
<td>O Homem das Cavernas Vol. 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M83.15F.jpg alt="o homem das cavernas vol. 1" height=110 width=95></td>
</tr>
<tr>
<td>O Homem das Cavernas Vol. 2</td>
<td>0</td>
<td>O Homem das Cavernas Vol. 2</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M110F.jpg alt="o homem das cavernas vol. 2" height=110 width=95></td>
</tr>
<tr>
<td>O Homem Perfeito</td>
<td>The Perfect Man</td>
<td>O Homem Perfeito</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5050582384758.15F.jpg alt="o homem perfeito" height=110 width=95></td>
</tr>
<tr>
<td>O Homem Que Sabia Demasiado</td>
<td>The Man Who Knew Too Much</td>
<td>O Homem Que Sabia Demasiado</td>
<td>X</td>
<td>X</td>
<td>1934</td>
<td>75</td>
<td>Suspense/Thriller</td>
<td><img src=Images\IDD38714EDD9FEE30.15F.jpg alt="o homem que sabia demasiado" height=110 width=95></td>
</tr>
<tr>
<td>O Hotel</td>
<td>The Million Dollar Hotel</td>
<td>O Hotel</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>117</td>
<td>Drama</td>
<td><img src=Images\5601887427260.15F.jpg alt="o hotel" height=110 width=95></td>
</tr>
<tr>
<td>O Ilusionista</td>
<td>The Illusionist</td>
<td>O Ilusionista</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>109</td>
<td>Drama</td>
<td><img src=Images\5602193335577.15F.jpg alt="o ilusionista" height=110 width=95></td>
</tr>
<tr>
<td>O Império dos Lobos</td>
<td>L'Empire des Loups</td>
<td>O Imperio dos Lobos</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>123</td>
<td>0</td>
<td><img src=Images\5601887478798.15F.jpg alt="o imperio dos lobos" height=110 width=95></td>
</tr>
<tr>
<td>O Jogo</td>
<td>The Game</td>
<td>O Jogo</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>123</td>
<td>Drama</td>
<td><img src=Images\I2F27C78B1E50CEEE.15F.jpg alt="o jogo" height=110 width=95></td>
</tr>
<tr>
<td>O Jogo da Imitação</td>
<td>The Imitation Game</td>
<td>O Jogo da Imitacao</td>
<td></td>
<td>X</td>
<td>2014</td>
<td>108</td>
<td>Drama</td>
<td><img src=Images\5601887614219.15F.jpg alt="o jogo da imitacao" height=110 width=95></td>
</tr>
<tr>
<td>O Jogo da sedução</td>
<td>0</td>
<td>O Jogo da seducao</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M112.15F.jpg alt="o jogo da seducao" height=110 width=95></td>
</tr>
<tr>
<td>O Jogo de Mr. Ripley</td>
<td>Ripley's Game</td>
<td>O Jogo de Mr. Ripley</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>105</td>
<td>Crime</td>
<td><img src=Images\5602193342599.15F.jpg alt="o jogo de mr. ripley" height=110 width=95></td>
</tr>
<tr>
<td>O Jogo do Poder</td>
<td>The Contender</td>
<td>O Jogo do Poder</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5601887424894.15F.jpg alt="o jogo do poder" height=110 width=95></td>
</tr>
<tr>
<td>O Julgamento do Diabo</td>
<td>Shortcut to Happiness</td>
<td>O Julgamento do Diabo</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5602193348607.15F.jpg alt="o julgamento do diabo" height=110 width=95></td>
</tr>
<tr>
<td>O Júri</td>
<td>Runaway Jury</td>
<td>O Juri</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5608652022019.15F.jpg alt="o juri" height=110 width=95></td>
</tr>
<tr>
<td>O Lago</td>
<td>Lake Placid</td>
<td>O Lago</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>81</td>
<td>0</td>
<td><img src=Images\5601887429066.15F.jpg alt="o lago" height=110 width=95></td>
</tr>
<tr>
<td>O Leão da Estrela</td>
<td>0</td>
<td>O Leao da Estrela</td>
<td>X</td>
<td>X</td>
<td>1947</td>
<td>113</td>
<td>0</td>
<td><img src=Images\5606699505342.15F.jpg alt="o leao da estrela" height=110 width=95></td>
</tr>
<tr>
<td>O Leão de Oz (Lion of Oz)</td>
<td>0</td>
<td>O Leao de Oz (Lion of Oz)</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>71</td>
<td>0</td>
<td><img src=Images\5608652004862.15F.jpg alt="o leao de oz (lion of oz)" height=110 width=95></td>
</tr>
<tr>
<td>O Libertino</td>
<td>The Libertine</td>
<td>O Libertino</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>109</td>
<td>Drama</td>
<td><img src=Images\5601684094542.15F.jpg alt="o libertino" height=110 width=95></td>
</tr>
<tr>
<td>O Mar é Azul - A História Natural dos Oceanos</td>
<td>0</td>
<td>O Mar e Azul - A Historia Natural dos Oceanos</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>488</td>
<td>0</td>
<td><img src=Images\5601887447671.15F.jpg alt="o mar e azul - a historia natural dos oceanos" height=110 width=95></td>
</tr>
<tr>
<td>O Maravilhoso Mundo dos Brinquedos</td>
<td>Mr. Magorium's Wonder Emporium</td>
<td>O Maravilhoso Mundo dos Brinquedos</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\5608652032391.15F.jpg alt="o maravilhoso mundo dos brinquedos" height=110 width=95></td>
</tr>
<tr>
<td>O Matador</td>
<td>The Matador</td>
<td>O Matador</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5602193332309.15F.jpg alt="o matador" height=110 width=95></td>
</tr>
<tr>
<td>O Mercador de Veneza</td>
<td>The Merchant of Venice</td>
<td>O Mercador de Veneza</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>126</td>
<td>Drama</td>
<td><img src=Images\5600304160148.15F.jpg alt="o mercador de veneza" height=110 width=95></td>
</tr>
<tr>
<td>O Meu Encontro Com Drew</td>
<td>My Date With Drew</td>
<td>O Meu Encontro Com Drew</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5606118101759.15F.jpg alt="o meu encontro com drew" height=110 width=95></td>
</tr>
<tr>
<td>O Meu Nome É Bill</td>
<td>Meet Bill</td>
<td>O Meu Nome E Bill</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\5600304203241.15F.jpg alt="o meu nome e bill" height=110 width=95></td>
</tr>
<tr>
<td>O Meu primo Vinny</td>
<td>My Cousin Vinny</td>
<td>O Meu primo Vinny</td>
<td>X</td>
<td>X</td>
<td>1992</td>
<td>114</td>
<td>Comédia</td>
<td><img src=Images\5608652009584.15F.jpg alt="o meu primo vinny" height=110 width=95></td>
</tr>
<tr>
<td>O Meu Tio</td>
<td>Mon oncle</td>
<td>O Meu Tio</td>
<td></td>
<td>X</td>
<td>1958</td>
<td>111</td>
<td>Comédia</td>
<td><img src=Images\5606699505298.15F.jpg alt="o meu tio" height=110 width=95></td>
</tr>
<tr>
<td>O Mito</td>
<td>San wa</td>
<td>O Mito</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>117</td>
<td>Acção</td>
<td><img src=Images\5608652034975.15F.jpg alt="o mito" height=110 width=95></td>
</tr>
<tr>
<td>O Mosqueteiro</td>
<td>The Musketeer</td>
<td>O Mosqueteiro</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5050582009767.15F.jpg alt="o mosqueteiro" height=110 width=95></td>
</tr>
<tr>
<td>O Motel</td>
<td>Vacancy</td>
<td>O Motel</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>82</td>
<td>Suspense/Thriller</td>
<td><img src=Images\8414533047975.15F.jpg alt="o motel" height=110 width=95></td>
</tr>
<tr>
<td>O Mundo a seus Pés</td>
<td>Citizen Kane</td>
<td>O Mundo a seus Pes</td>
<td>X</td>
<td>X</td>
<td>1941</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5602227301615.15F.jpg alt="o mundo a seus pes" height=110 width=95></td>
</tr>
<tr>
<td>O Mundo Não Chega</td>
<td>The World Is Not Enough</td>
<td>O Mundo Nao Chega</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>123</td>
<td>Acção</td>
<td><img src=Images\IA36E55B9EF8F0CE0.15F.jpg alt="o mundo nao chega" height=110 width=95></td>
</tr>
<tr>
<td>O Namorado Atómico</td>
<td>Blast from the Past</td>
<td>O Namorado Atomico</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5601887424962.15F.jpg alt="o namorado atomico" height=110 width=95></td>
</tr>
<tr>
<td>O Novo Diário de Bridget Jones</td>
<td>Bridget Jones: The Edge of Reason</td>
<td>O Novo Diario de Bridget Jones</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>103</td>
<td>Comédia</td>
<td><img src=Images\5050582310740.15F.jpg alt="o novo diario de bridget jones" height=110 width=95></td>
</tr>
<tr>
<td>O Olho</td>
<td>The Eye</td>
<td>O Olho</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>120</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652033671.15F.jpg alt="o olho" height=110 width=95></td>
</tr>
<tr>
<td>O outro homem</td>
<td>The Other Man</td>
<td>O outro homem</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>87</td>
<td>Drama</td>
<td><img src=Images\5600304213790.15F.jpg alt="o outro homem" height=110 width=95></td>
</tr>
<tr>
<td>O Outro Lado da Fronteira</td>
<td>Across the Line: The Exodus of Charlie Wright</td>
<td>O Outro Lado da Fronteira</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>94</td>
<td>Crime</td>
<td><img src=Images\5600351700984.15F.jpg alt="o outro lado da fronteira" height=110 width=95></td>
</tr>
<tr>
<td>O Pacificador</td>
<td>The Peacemaker</td>
<td>O Pacificador</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>119</td>
<td>0</td>
<td><img src=Images\0678149097924.15F.jpg alt="o pacificador" height=110 width=95></td>
</tr>
<tr>
<td>O Pacto dos Lobos</td>
<td>Le Pacte des loups</td>
<td>O Pacto dos Lobos</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>138</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652016544.15F.jpg alt="o pacto dos lobos" height=110 width=95></td>
</tr>
<tr>
<td>O Pai Tirano</td>
<td>0</td>
<td>O Pai Tirano</td>
<td>X</td>
<td>X</td>
<td>1941</td>
<td>114</td>
<td>Clássico</td>
<td><img src=Images\IB652695230AA6521.15F.jpg alt="o pai tirano" height=110 width=95></td>
</tr>
<tr>
<td>O Panda do Kung Fu</td>
<td>Kung Fu Panda</td>
<td>O Panda do Kung Fu</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>88</td>
<td>Animação</td>
<td><img src=Images\5601887528608.15F.jpg alt="o panda do kung fu" height=110 width=95></td>
</tr>
<tr>
<td>O panda do kung fu 2</td>
<td>Kung Fu Panda 2</td>
<td>O panda do kung fu 2</td>
<td></td>
<td>X</td>
<td>2011</td>
<td>90</td>
<td><NAME>is</td>
<td><img src=Images\5601887573134.15F.jpg alt="o panda do kung fu 2" height=110 width=95></td>
</tr>
<tr>
<td>O Par do Ano</td>
<td>America's Sweethearts</td>
<td>O Par do Ano</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5601887438310.15F.jpg alt="o par do ano" height=110 width=95></td>
</tr>
<tr>
<td>O Paraíso da Barafunda</td>
<td>Home on the Range</td>
<td>O Paraiso da Barafunda</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>73</td>
<td>0</td>
<td><img src=Images\5601887466443.15F.jpg alt="o paraiso da barafunda" height=110 width=95></td>
</tr>
<tr>
<td>O Pastor - Alguém tem de Morrer</td>
<td>Saving God</td>
<td>O Pastor - Alguem tem de Morrer</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>97</td>
<td>Crime</td>
<td><img src=Images\5600351701127.15F.jpg alt="o pastor - alguem tem de morrer" height=110 width=95></td>
</tr>
<tr>
<td>O Pátio das Cantigas</td>
<td>0</td>
<td>O Patio das Cantigas</td>
<td>X</td>
<td>X</td>
<td>1942</td>
<td>127</td>
<td>Comédia</td>
<td><img src=Images\I5A5F6A11F53E7BC6.15F.jpg alt="o patio das cantigas" height=110 width=95></td>
</tr>
<tr>
<td>O Pianista</td>
<td>The Pianist</td>
<td>O Pianista</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>142</td>
<td>Drama</td>
<td><img src=Images\5601684045506.15F.jpg alt="o pianista" height=110 width=95></td>
</tr>
<tr>
<td>O Pistoleiro do diabo</td>
<td>High Plains Drifter</td>
<td>O Pistoleiro do diabo</td>
<td>X</td>
<td>X</td>
<td>1973</td>
<td>101</td>
<td>Western</td>
<td><img src=Images\IED899127B1E56F83.15F.jpg alt="o pistoleiro do diabo" height=110 width=95></td>
</tr>
<tr>
<td>O Planeta do Tesouro</td>
<td>Treasure Planet</td>
<td>O Planeta do Tesouro</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>91</td>
<td>Animação</td>
<td><img src=Images\5601887447039.15F.jpg alt="o planeta do tesouro" height=110 width=95></td>
</tr>
<tr>
<td>O Plano</td>
<td>A Simple Plan</td>
<td>O Plano</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>116</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887429806.15F.jpg alt="o plano" height=110 width=95></td>
</tr>
<tr>
<td>O Poder da Justiça</td>
<td>The Rainmaker</td>
<td>O Poder da Justica</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>130</td>
<td>Drama</td>
<td><img src=Images\5601887417322.15F.jpg alt="o poder da justica" height=110 width=95></td>
</tr>
<tr>
<td>O Preço da Coragem</td>
<td>0</td>
<td>O Preco da Coragem</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5601887459391.15F.jpg alt="o preco da coragem" height=110 width=95></td>
</tr>
<tr>
<td>O Príncipe e eu</td>
<td>The Prince & Me</td>
<td>O Principe e eu</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>106</td>
<td>Comédia</td>
<td><img src=Images\IB0A5C8A4E9E9147C.15F.jpg alt="o principe e eu" height=110 width=95></td>
</tr>
<tr>
<td>O Quarto Anjo</td>
<td>0</td>
<td>O Quarto Anjo</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>91</td>
<td>0</td>
<td><img src=Images\5601887445059.15F.jpg alt="o quarto anjo" height=110 width=95></td>
</tr>
<tr>
<td>O Que As Mulheres Querem</td>
<td>What Women Want</td>
<td>O Que As Mulheres Querem</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5601887426782.15F.jpg alt="o que as mulheres querem" height=110 width=95></td>
</tr>
<tr>
<td>O Quebra Nozes - O Rei dos Ratos</td>
<td>The Nutcracker and the Mouseking</td>
<td>O Quebra Nozes - O Rei dos Ratos</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>0</td>
<td>Animação</td>
<td><img src=Images\5601073514217.15F.jpg alt="o quebra nozes - o rei dos ratos" height=110 width=95></td>
</tr>
<tr>
<td>O Quinteto da Morte</td>
<td>The Ladykillers</td>
<td>O Quinteto da Morte</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5601887466535.15F.jpg alt="o quinteto da morte" height=110 width=95></td>
</tr>
<tr>
<td>O Rapaz Formiga</td>
<td>The Ant Bully</td>
<td>O Rapaz Formiga</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>85</td>
<td>Animação</td>
<td><img src=Images\7321977736680.15F.jpg alt="o rapaz formiga" height=110 width=95></td>
</tr>
<tr>
<td>O Recruta</td>
<td>0</td>
<td>O Recruta</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887457373.15F.jpg alt="o recruta" height=110 width=95></td>
</tr>
<tr>
<td>O Regresso de Henry</td>
<td>Regarding Henry</td>
<td>O Regresso de Henry</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>103</td>
<td>Drama</td>
<td><img src=Images\5601887452835.15F.jpg alt="o regresso de henry" height=110 width=95></td>
</tr>
<tr>
<td>O Rei da Califórnia</td>
<td>King of California</td>
<td>O Rei da California</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\5602193346818.15F.jpg alt="o rei da california" height=110 width=95></td>
</tr>
<tr>
<td>O Rei Leão</td>
<td>The Lion King</td>
<td>O Rei Leao</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>85</td>
<td>Família</td>
<td><img src=Images\5601887451326.15F.jpg alt="o rei leao" height=110 width=95></td>
</tr>
<tr>
<td>O reino proibido</td>
<td>The Forbidden Kingdom</td>
<td>O reino proibido</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>105</td>
<td>Acção</td>
<td><img src=Images\5600304207041.15F.jpg alt="o reino proibido" height=110 width=95></td>
</tr>
<tr>
<td>O repórter</td>
<td>Anchorman: The Legend of Ron Burgundy</td>
<td>O reporter</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>Comédia</td>
<td><img src=Images\5050583013909.15F.jpg alt="o reporter" height=110 width=95></td>
</tr>
<tr>
<td>O Ringue</td>
<td>Play It To The Bone</td>
<td>O Ringue</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>125</td>
<td>0</td>
<td><img src=Images\5601887429844.15F.jpg alt="o ringue" height=110 width=95></td>
</tr>
<tr>
<td>O Rio</td>
<td>The River</td>
<td>O Rio</td>
<td></td>
<td>X</td>
<td>1984</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5050582005097.15F.jpg alt="o rio" height=110 width=95></td>
</tr>
<tr>
<td>O Salta Pocinhas</td>
<td>Le roman de Renart</td>
<td>O Salta Pocinhas</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>95</td>
<td>Animação</td>
<td><img src=Images\I0454C84155479BFB.15F.jpg alt="o salta pocinhas" height=110 width=95></td>
</tr>
<tr>
<td>O Segredo de Brokeback Mountain</td>
<td>Brokeback Mountain</td>
<td>O Segredo de Brokeback Mountain</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>129</td>
<td>Drama</td>
<td><img src=Images\5608652034807.15F.jpg alt="o segredo de brokeback mountain" height=110 width=95></td>
</tr>
<tr>
<td>O Senhor dos Anéis: A Irmandade do Anel</td>
<td>The Lord of the Rings: The Fellowship of the Ring</td>
<td>O Senhor dos Aneis: A Irmandade do Anel</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>178</td>
<td>Acção</td>
<td><img src=Images\5608652034746.15F.jpg alt="o senhor dos aneis: a irmandade do anel" height=110 width=95></td>
</tr>
<tr>
<td>O Senhor dos Anéis: As Duas Torres</td>
<td>The Lord of the Rings: The Two Towers</td>
<td>O Senhor dos Aneis: As Duas Torres</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>179</td>
<td>Acção</td>
<td><img src=Images\5608652034753.15F.jpg alt="o senhor dos aneis: as duas torres" height=110 width=95></td>
</tr>
<tr>
<td>O Senhor dos Anéis: O Regresso do Rei</td>
<td>The Lord of the Rings: The Return of the King</td>
<td>O Senhor dos Aneis: O Regresso do Rei</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>200</td>
<td>Acção</td>
<td><img src=Images\5608652034760.15F.jpg alt="o senhor dos aneis: o regresso do rei" height=110 width=95></td>
</tr>
<tr>
<td>O Sentinela</td>
<td>The Sentinel</td>
<td>O Sentinela</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5600304169912.15F.jpg alt="o sentinela" height=110 width=95></td>
</tr>
<tr>
<td>O Sexto Sentido</td>
<td>The Sixth Sense</td>
<td>O Sexto Sentido</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887409938.15F.jpg alt="o sexto sentido" height=110 width=95></td>
</tr>
<tr>
<td>O Soldado de Chumbo</td>
<td>0</td>
<td>O Soldado de Chumbo</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M63.15F.jpg alt="o soldado de chumbo" height=110 width=95></td>
</tr>
<tr>
<td>O Sorriso das Estrelas</td>
<td>Nights in Rodanthe</td>
<td>O Sorriso das Estrelas</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>97</td>
<td>Romance</td>
<td><img src=Images\5600304201148.15F.jpg alt="o sorriso das estrelas" height=110 width=95></td>
</tr>
<tr>
<td>O Sorriso de Mona Lisa</td>
<td>Mona Lisa Smile</td>
<td>O Sorriso de Mona Lisa</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5601887461264.15F.jpg alt="o sorriso de mona lisa" height=110 width=95></td>
</tr>
<tr>
<td>O suspeito da Rua Arlington</td>
<td>Arlington Road</td>
<td>O suspeito da Rua Arlington</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>113</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887415175.15F.jpg alt="o suspeito da rua arlington" height=110 width=95></td>
</tr>
<tr>
<td>O Suspeito Zero</td>
<td>Suspect Zero</td>
<td>O Suspeito Zero</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>0</td>
<td><img src=Images\8414533031066.15F.jpg alt="o suspeito zero" height=110 width=95></td>
</tr>
<tr>
<td>O Talentoso Mr. Ripley</td>
<td>The Talented Mr. Ripley</td>
<td>O Talentoso Mr. Ripley</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>134</td>
<td>Crime</td>
<td><img src=Images\5601887442133.15F.jpg alt="o talentoso mr. ripley" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo das feras Vol. 1</td>
<td>0</td>
<td>O Tempo das feras Vol. 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M102.15F.jpg alt="o tempo das feras vol. 1" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo das feras Vol. 2</td>
<td>0</td>
<td>O Tempo das feras Vol. 2</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M103.15F.jpg alt="o tempo das feras vol. 2" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo das feras Vol. 3</td>
<td>0</td>
<td>O Tempo das feras Vol. 3</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M104.15F.jpg alt="o tempo das feras vol. 3" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo das feras Vol. 4</td>
<td>0</td>
<td>O Tempo das feras Vol. 4</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M105.15F.jpg alt="o tempo das feras vol. 4" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo dos dinossauros Vol. 1</td>
<td>0</td>
<td>O Tempo dos dinossauros Vol. 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M106.15F.jpg alt="o tempo dos dinossauros vol. 1" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo dos dinossauros Vol. 2</td>
<td>0</td>
<td>O Tempo dos dinossauros Vol. 2</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M107.15F.jpg alt="o tempo dos dinossauros vol. 2" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo dos dinossauros Vol. 3</td>
<td>0</td>
<td>O Tempo dos dinossauros Vol. 3</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M108.15F.jpg alt="o tempo dos dinossauros vol. 3" height=110 width=95></td>
</tr>
<tr>
<td>O Tempo dos dinossauros Vol. 4</td>
<td>0</td>
<td>O Tempo dos dinossauros Vol. 4</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M109.15F.jpg alt="o tempo dos dinossauros vol. 4" height=110 width=95></td>
</tr>
<tr>
<td>O Tesouro</td>
<td>National Treasure</td>
<td>O Tesouro</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>126</td>
<td>Aventura</td>
<td><img src=Images\5601887471089.15F.jpg alt="o tesouro" height=110 width=95></td>
</tr>
<tr>
<td>O Tesouro 2 - Livro dos Segredos</td>
<td>National Treasure 2 - Book of Secrets</td>
<td>O Tesouro 2 - Livro dos Segredos</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>119</td>
<td>0</td>
<td><img src=Images\5601887521906.15F.jpg alt="o tesouro 2 - livro dos segredos" height=110 width=95></td>
</tr>
<tr>
<td>O Tesouro Encalhado</td>
<td>Fool's Gold</td>
<td>O Tesouro Encalhado</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>108</td>
<td>Aventura</td>
<td><img src=Images\5600304199131.15F.jpg alt="o tesouro encalhado" height=110 width=95></td>
</tr>
<tr>
<td>O triângulo</td>
<td>The triangle</td>
<td>O triangulo</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>244</td>
<td>0</td>
<td><img src=Images\5608652031554.15F.jpg alt="o triangulo" height=110 width=95></td>
</tr>
<tr>
<td>O turista</td>
<td>The Tourist</td>
<td>O turista</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>99</td>
<td>Acção</td>
<td><img src=Images\5602193404341.15F.jpg alt="o turista" height=110 width=95></td>
</tr>
<tr>
<td>O último atirador</td>
<td>0</td>
<td>O ultimo atirador</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>84</td>
<td>Drama</td>
<td><img src=Images\5706152310008.4F.jpg alt="o ultimo atirador" height=110 width=95></td>
</tr>
<tr>
<td>O Último Castelo</td>
<td>The Last Castle</td>
<td>O Ultimo Castelo</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>126</td>
<td>Acção</td>
<td><img src=Images\5601887495832.15F.jpg alt="o ultimo castelo" height=110 width=95></td>
</tr>
<tr>
<td>O Último Comboio</td>
<td>Night Train</td>
<td>O Ultimo Comboio</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>87</td>
<td>Acção</td>
<td><img src=Images\I755140C57F68607E.15F.jpg alt="o ultimo comboio" height=110 width=95></td>
</tr>
<tr>
<td>O Último Samurai</td>
<td>The Last Samurai</td>
<td>O Ultimo Samurai</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>148</td>
<td>0</td>
<td><img src=Images\7321976283833.15F.jpg alt="o ultimo samurai" height=110 width=95></td>
</tr>
<tr>
<td>O Último Viking</td>
<td>The 13th Warrior</td>
<td>O Ultimo Viking</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>98</td>
<td>Acção</td>
<td><img src=Images\5601887426386.15F.jpg alt="o ultimo viking" height=110 width=95></td>
</tr>
<tr>
<td>O Verão Louco do Mickey</td>
<td>Mickey Summer Madness</td>
<td>O Verao Louco do Mickey</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>45</td>
<td>Animação</td>
<td><img src=Images\5601887485710.15F.jpg alt="o verao louco do mickey" height=110 width=95></td>
</tr>
<tr>
<td>O Véu Pintado</td>
<td>The Painted Veil</td>
<td>O Veu Pintado</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>119</td>
<td>0</td>
<td><img src=Images\5602193337649.15F.jpg alt="o veu pintado" height=110 width=95></td>
</tr>
<tr>
<td>Obsessão mortal</td>
<td>The Flock</td>
<td>Obsessao mortal</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>101</td>
<td>Suspense/Thriller</td>
<td><img src=Images\8032807024707.13F.jpg alt="obsessao mortal" height=110 width=95></td>
</tr>
<tr>
<td>Ocean's 13</td>
<td>Ocean's Thirteen</td>
<td>Ocean's 13</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>122</td>
<td>Acção</td>
<td><img src=Images\5600304179850.15F.jpg alt="ocean's 13" height=110 width=95></td>
</tr>
<tr>
<td>Ocean's Eleven - Façam as Vossas Apostas</td>
<td>Ocean's Eleven</td>
<td>Ocean's Eleven - Facam as Vossas Apostas</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>112</td>
<td>Comédia</td>
<td><img src=Images\7321976221859.15F.jpg alt="ocean's eleven - facam as vossas apostas" height=110 width=95></td>
</tr>
<tr>
<td>Ocean's Twelve</td>
<td>0</td>
<td>Ocean's Twelve</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>120</td>
<td>0</td>
<td><img src=Images\7321976389481.15F.jpg alt="ocean's twelve" height=110 width=95></td>
</tr>
<tr>
<td>Oficial e Cavalheiro</td>
<td>0</td>
<td>Oficial e Cavalheiro</td>
<td>X</td>
<td>X</td>
<td>1982</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5601887418053.15F.jpg alt="oficial e cavalheiro" height=110 width=95></td>
</tr>
<tr>
<td>Oito Mulheres</td>
<td>8 Femmes</td>
<td>Oito Mulheres</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5606699504949.15F.jpg alt="oito mulheres" height=110 width=95></td>
</tr>
<tr>
<td>Oliver e Seus Companheiros</td>
<td>Oliver & Company</td>
<td>Oliver e Seus Companheiros</td>
<td>X</td>
<td>X</td>
<td>1988</td>
<td>71</td>
<td>0</td>
<td><img src=Images\5601887424535.15F.jpg alt="oliver e seus companheiros" height=110 width=95></td>
</tr>
<tr>
<td>Onde Tá O Carro, Meu?</td>
<td>Dude, Where's my car?</td>
<td>Onde Ta O Carro, Meu?</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>79</td>
<td>Comédia</td>
<td><img src=Images\5600304163361.15F.jpg alt="onde ta o carro, meu?" height=110 width=95></td>
</tr>
<tr>
<td>One Hour Photo - Câmara Indiscreta</td>
<td>One Hour Photo</td>
<td>One Hour Photo - Camara Indiscreta</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>92</td>
<td>Drama</td>
<td><img src=Images\5600304165433.15F.jpg alt="one hour photo - camara indiscreta" height=110 width=95></td>
</tr>
<tr>
<td>Operação Flecha Quebrada</td>
<td>Broken Arrow</td>
<td>Operacao Flecha Quebrada</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\5608652001953.15F.jpg alt="operacao flecha quebrada" height=110 width=95></td>
</tr>
<tr>
<td>Operação Relâmpago</td>
<td>Thunderball</td>
<td>Operacao Relampago</td>
<td>X</td>
<td>X</td>
<td>1965</td>
<td>125</td>
<td>Acção</td>
<td><img src=Images\IB2DA0FCAECB684CA.15F.jpg alt="operacao relampago" height=110 width=95></td>
</tr>
<tr>
<td>Operação Swordfish</td>
<td>Swordfish</td>
<td>Operacao Swordfish</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>96</td>
<td>Acção</td>
<td><img src=Images\7321976213229.15F.jpg alt="operacao swordfish" height=110 width=95></td>
</tr>
<tr>
<td>Operação Tentáculo</td>
<td>Octopussy</td>
<td>Operacao Tentaculo</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>125</td>
<td>Acção</td>
<td><img src=Images\IFBF91A3A10DFF389.15F.jpg alt="operacao tentaculo" height=110 width=95></td>
</tr>
<tr>
<td>Ordem para Matar</td>
<td>From Russia With Love</td>
<td>Ordem para Matar</td>
<td>X</td>
<td>X</td>
<td>1963</td>
<td>110</td>
<td>Acção</td>
<td><img src=Images\I3D566D93E76AF2DE.15F.jpg alt="ordem para matar" height=110 width=95></td>
</tr>
<tr>
<td>Orgulho</td>
<td>Pride</td>
<td>Orgulho</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>109</td>
<td>Drama</td>
<td><img src=Images\031398215400F.jpg alt="orgulho" height=110 width=95></td>
</tr>
<tr>
<td>Orgulho e Preconceito</td>
<td>Pride & Prejudice</td>
<td>Orgulho e Preconceito</td>
<td>X</td>
<td></td>
<td>2005</td>
<td>121</td>
<td>0</td>
<td><img src=Images\5050582402179.15F.jpg alt="orgulho e preconceito" height=110 width=95></td>
</tr>
<tr>
<td>Os 39 Degraus</td>
<td>0</td>
<td>Os 39 Degraus</td>
<td>X</td>
<td>X</td>
<td>1935</td>
<td>81</td>
<td>Suspense/Thriller</td>
<td><img src=Images\ID5C0DB80EC86F504.15F.jpg alt="os 39 degraus" height=110 width=95></td>
</tr>
<tr>
<td>Os 5 & Eu</td>
<td>5 Children & It</td>
<td>Os 5 & Eu</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>85</td>
<td>Família</td>
<td><img src=Images\I924016B7EE87D5CF.15F.jpg alt="os 5 & eu" height=110 width=95></td>
</tr>
<tr>
<td>Os agentes do destino</td>
<td>The Adjustment Bureau</td>
<td>Os agentes do destino</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>106</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600402400214.15F.jpg alt="os agentes do destino" height=110 width=95></td>
</tr>
<tr>
<td>Os Anjos de Charlie</td>
<td>Charlie's Angels</td>
<td>Os Anjos de Charlie</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>94</td>
<td>Acção</td>
<td><img src=Images\5601887450626.15F.jpg alt="os anjos de charlie" height=110 width=95></td>
</tr>
<tr>
<td>Os Anjos de Charlie: Potência Máxima</td>
<td>Charlie's Angels: Full Throttle</td>
<td>Os Anjos de Charlie: Potencia Maxima</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>103</td>
<td>Acção</td>
<td><img src=Images\8414533022545.15F.jpg alt="os anjos de charlie: potencia maxima" height=110 width=95></td>
</tr>
<tr>
<td>Os Condenados de Shawshank</td>
<td>The Shawshank Redemption</td>
<td>Os Condenados de Shawshank</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>136</td>
<td>0</td>
<td><img src=Images\5602193334013.15F.jpg alt="os condenados de shawshank" height=110 width=95></td>
</tr>
<tr>
<td>Os crimes do rio rei</td>
<td>The River King</td>
<td>Os crimes do rio rei</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>98</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652028721.15F.jpg alt="os crimes do rio rei" height=110 width=95></td>
</tr>
<tr>
<td>Os Daltons à Solta</td>
<td>Les Dalton en cavale</td>
<td>Os Daltons a Solta</td>
<td>X</td>
<td>X</td>
<td>1983</td>
<td>82</td>
<td>Animação</td>
<td><img src=Images\5601887437276.15F.jpg alt="os daltons a solta" height=110 width=95></td>
</tr>
<tr>
<td>Os Despojos do Dia</td>
<td>The Remains of the Day</td>
<td>Os Despojos do Dia</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>129</td>
<td>0</td>
<td><img src=Images\5601887422449.15F.jpg alt="os despojos do dia" height=110 width=95></td>
</tr>
<tr>
<td>Os Diamantes são Eternos</td>
<td>Diamonds Are Forever</td>
<td>Os Diamantes sao Eternos</td>
<td>X</td>
<td>X</td>
<td>1971</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\I133DF797C2BCA215.15F.jpg alt="os diamantes sao eternos" height=110 width=95></td>
</tr>
<tr>
<td>Os Dias do Fim</td>
<td>End of Days</td>
<td>Os Dias do Fim</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>117</td>
<td>Acção</td>
<td><img src=Images\5601887408108.15F.jpg alt="os dias do fim" height=110 width=95></td>
</tr>
<tr>
<td>Os Fura Casamentos</td>
<td>Wedding Crashers</td>
<td>Os Fura Casamentos</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>119</td>
<td>0</td>
<td><img src=Images\5602193328739.15F.jpg alt="os fura casamentos" height=110 width=95></td>
</tr>
<tr>
<td>Os Incorruptíveis Contra a Droga II</td>
<td>French Connection II</td>
<td>Os Incorruptiveis Contra a Droga II</td>
<td>X</td>
<td>X</td>
<td>1975</td>
<td>114</td>
<td>0</td>
<td><img src=Images\5600304163590.15F.jpg alt="os incorruptiveis contra a droga ii" height=110 width=95></td>
</tr>
<tr>
<td>Os Intocáveis</td>
<td>The Untouchables</td>
<td>Os Intocaveis</td>
<td>X</td>
<td>X</td>
<td>1987</td>
<td>115</td>
<td>Acção</td>
<td><img src=Images\5601887418091.15F.jpg alt="os intocaveis" height=110 width=95></td>
</tr>
<tr>
<td>Os Irmãos Dalton</td>
<td>Les Dalton</td>
<td>Os Irmaos Dalton</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>86</td>
<td>Comédia</td>
<td><img src=Images\5608652027939.15F.jpg alt="os irmaos dalton" height=110 width=95></td>
</tr>
<tr>
<td>Os Irmãos Grimm</td>
<td>The Brothers Grimm</td>
<td>Os Irmaos Grimm</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>107</td>
<td>0</td>
<td><img src=Images\5600304169554.15F.jpg alt="os irmaos grimm" height=110 width=95></td>
</tr>
<tr>
<td>Os Melhores Momentos de John Cleese</td>
<td>0</td>
<td>Os Melhores Momentos de John Cleese</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M62.15F.jpg alt="os melhores momentos de john cleese" height=110 width=95></td>
</tr>
<tr>
<td>Os Mensageiros</td>
<td>The Messengers</td>
<td>Os Mensageiros</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>86</td>
<td>Horror</td>
<td><img src=Images\5608652031479.15F.jpg alt="os mensageiros" height=110 width=95></td>
</tr>
<tr>
<td>Os mercenários</td>
<td>The Expendables</td>
<td>Os mercenarios</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>103</td>
<td>Acção</td>
<td><img src=Images\5601887564354.15F.jpg alt="os mercenarios" height=110 width=95></td>
</tr>
<tr>
<td>Os Mercenários 2</td>
<td>The Espendables 2</td>
<td>Os Mercenarios 2</td>
<td>X</td>
<td>X</td>
<td>2012</td>
<td>98</td>
<td>Acção</td>
<td><img src=Images\5601887585182.15F.jpg alt="os mercenarios 2" height=110 width=95></td>
</tr>
<tr>
<td>Os Miúdos Estão Bem</td>
<td>The Kids Are All Right</td>
<td>Os Miudos Estao Bem</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>102</td>
<td>Comédia</td>
<td><img src=Images\5600304218139.15F.jpg alt="os miudos estao bem" height=110 width=95></td>
</tr>
<tr>
<td>Os noves</td>
<td>The Nines</td>
<td>Os noves</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\5600304195935.15F.jpg alt="os noves" height=110 width=95></td>
</tr>
<tr>
<td>Os Olhos da Serpente</td>
<td>Snake Eyes</td>
<td>Os Olhos da Serpente</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5601887400805.15F.jpg alt="os olhos da serpente" height=110 width=95></td>
</tr>
<tr>
<td>Os oportunistas</td>
<td>0</td>
<td>Os oportunistas</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>90</td>
<td>Suspense/Thriller</td>
<td><img src=Images\687797319791F.jpg alt="os oportunistas" height=110 width=95></td>
</tr>
<tr>
<td>Os Outros</td>
<td>The Others</td>
<td>Os Outros</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>100</td>
<td>Horror</td>
<td><img src=Images\5602193336208.15F.jpg alt="os outros" height=110 width=95></td>
</tr>
<tr>
<td>Os Pássaros</td>
<td>The Birds</td>
<td>Os Passaros</td>
<td>X</td>
<td>X</td>
<td>1963</td>
<td>119</td>
<td>0</td>
<td><img src=Images\0044007847428.15F.jpg alt="os passaros" height=110 width=95></td>
</tr>
<tr>
<td>Os Poderosos</td>
<td>The Mighty</td>
<td>Os Poderosos</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5601887442140.15F.jpg alt="os poderosos" height=110 width=95></td>
</tr>
<tr>
<td>Os Polícias Do Mundo</td>
<td>Buffalo Soldiers</td>
<td>Os Policias Do Mundo</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5608652021609.15F.jpg alt="os policias do mundo" height=110 width=95></td>
</tr>
<tr>
<td>Os Profissionais</td>
<td>0</td>
<td>Os Profissionais</td>
<td>X</td>
<td>X</td>
<td>1966</td>
<td>112</td>
<td>0</td>
<td><img src=Images\5601887445929.15F.jpg alt="os profissionais" height=110 width=95></td>
</tr>
<tr>
<td>Os Profissionais do Jogo</td>
<td>Shade</td>
<td>Os Profissionais do Jogo</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>104</td>
<td>Drama</td>
<td><img src=Images\5602193320740.15F.jpg alt="os profissionais do jogo" height=110 width=95></td>
</tr>
<tr>
<td>Os Reis da Rua</td>
<td>Street Kings</td>
<td>Os Reis da Rua</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>109</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304206877.15F.jpg alt="os reis da rua" height=110 width=95></td>
</tr>
<tr>
<td>Os Robinsons</td>
<td>Meet the Robinsons</td>
<td>Os Robinsons</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>91</td>
<td>Animação</td>
<td><img src=Images\5601887494491.15F.jpg alt="os robinsons" height=110 width=95></td>
</tr>
<tr>
<td>Os Smurfs</td>
<td>The Smurfs</td>
<td>Os Smurfs</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>99</td>
<td>Animação</td>
<td><img src=Images\5602193405379.15F.jpg alt="os smurfs" height=110 width=95></td>
</tr>
<tr>
<td>Os Tenenbaums - Uma Comédia Genial</td>
<td>The Royal Tenenbaums</td>
<td>Os Tenenbaums - Uma Comedia Genial</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>109</td>
<td>0</td>
<td><img src=Images\5601887440184.15F.jpg alt="os tenenbaums - uma comedia genial" height=110 width=95></td>
</tr>
<tr>
<td>Os Trapaceiros</td>
<td>0</td>
<td>Os Trapaceiros</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5602193317351.15F.jpg alt="os trapaceiros" height=110 width=95></td>
</tr>
<tr>
<td>Os Três da Vida Airada</td>
<td>0</td>
<td>Os Tres da Vida Airada</td>
<td>X</td>
<td>X</td>
<td>1952</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\I9EA654A4EF0270D3.15F.jpg alt="os tres da vida airada" height=110 width=95></td>
</tr>
<tr>
<td>Os três porquinhos</td>
<td>Three Little Pigs</td>
<td>Os tres porquinhos</td>
<td>X</td>
<td>X</td>
<td>1933</td>
<td>62</td>
<td>Animação</td>
<td><img src=Images\786936789270F.jpg alt="os tres porquinhos" height=110 width=95></td>
</tr>
<tr>
<td>Os Últimos Dias</td>
<td>The Last Days</td>
<td>Os Ultimos Dias</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>87</td>
<td>Documentário</td>
<td><img src=Images\5608652014519.15F.jpg alt="os ultimos dias" height=110 width=95></td>
</tr>
<tr>
<td>Os Visitantes</td>
<td>Les Visiteurs</td>
<td>Os Visitantes</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>102</td>
<td>0</td>
<td><img src=Images\5602193326230.15F.jpg alt="os visitantes" height=110 width=95></td>
</tr>
<tr>
<td>Pacha e o Imperador</td>
<td>The Emperor's New Groove</td>
<td>Pacha e o Imperador</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>75</td>
<td>Animação</td>
<td><img src=Images\5601887428755.15F.jpg alt="pacha e o imperador" height=110 width=95></td>
</tr>
<tr>
<td>Pânico em Hollywood</td>
<td>What Just Happened</td>
<td>Panico em Hollywood</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5601887553099.15F.jpg alt="panico em hollywood" height=110 width=95></td>
</tr>
<tr>
<td>Pantera Cor-De-Rosa: A Nova Colecção de Animação</td>
<td>The Pink Panther New Cartoon Collection</td>
<td>Pantera Cor-De-Rosa: A Nova Coleccao de Animacao</td>
<td>X</td>
<td>X</td>
<td>1964</td>
<td>780</td>
<td>Animação</td>
<td><img src=Images\5600304170857.15F.jpg alt="pantera cor-de-rosa: a nova coleccao de animacao" height=110 width=95></td>
</tr>
<tr>
<td>Pantera Cor-De-Rosa: Colecção de Animação</td>
<td>The Pink Panther Cartoon Collection</td>
<td>Pantera Cor-De-Rosa: Coleccao de Animacao</td>
<td>X</td>
<td>X</td>
<td>1964</td>
<td>780</td>
<td>0</td>
<td><img src=Images\5608652026628.15F.jpg alt="pantera cor-de-rosa: coleccao de animacao" height=110 width=95></td>
</tr>
<tr>
<td>Papillon</td>
<td>0</td>
<td>Papillon</td>
<td>X</td>
<td>X</td>
<td>1973</td>
<td>145</td>
<td>Aventura</td>
<td><img src=Images\5608652014700.15F.jpg alt="papillon" height=110 width=95></td>
</tr>
<tr>
<td>Papuça e Dentuça</td>
<td>The Fox and the Hound</td>
<td>Papuca e Dentuca</td>
<td>X</td>
<td>X</td>
<td>1981</td>
<td>79</td>
<td>0</td>
<td><img src=Images\5601887424528.15F.jpg alt="papuca e dentuca" height=110 width=95></td>
</tr>
<tr>
<td>Papyrus 1</td>
<td>0</td>
<td>Papyrus 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M68.15F.jpg alt="papyrus 1" height=110 width=95></td>
</tr>
<tr>
<td>Para Sempre, Talvez...</td>
<td>Definitely, Maybe</td>
<td>Para Sempre, Talvez...</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>102</td>
<td>Comédia</td>
<td><img src=Images\5600402408609.15F.jpg alt="para sempre, talvez..." height=110 width=95></td>
</tr>
<tr>
<td>Para Tudo Há Uma Primeira Vez</td>
<td>Mini's First Time</td>
<td>Para Tudo Ha Uma Primeira Vez</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>88</td>
<td>Comédia</td>
<td><img src=Images\5600304189224.15F.jpg alt="para tudo ha uma primeira vez" height=110 width=95></td>
</tr>
<tr>
<td>Parceiros no crime</td>
<td>Thick as thieves</td>
<td>Parceiros no crime</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887560226.15F.jpg alt="parceiros no crime" height=110 width=95></td>
</tr>
<tr>
<td>Paris</td>
<td>0</td>
<td>Paris</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M70.15F.jpg alt="paris" height=110 width=95></td>
</tr>
<tr>
<td>Paris, Texas</td>
<td>0</td>
<td>Paris, Texas</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>139</td>
<td>Drama</td>
<td><img src=Images\IE258D26FFE75A0A9.15F.jpg alt="paris, texas" height=110 width=95></td>
</tr>
<tr>
<td>Parkland</td>
<td>0</td>
<td>Parkland</td>
<td>X</td>
<td>X</td>
<td>2013</td>
<td>94</td>
<td>Crime</td>
<td><img src=Images\687797142795F.jpg alt="parkland" height=110 width=95></td>
</tr>
<tr>
<td>Parnassus o homem que queria enganar o diabo</td>
<td>The Imaginarium of Doctor Parnassus</td>
<td>Parnassus o homem que queria enganar o diabo</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>123</td>
<td>Aventura</td>
<td><img src=Images\5602193352161.15F.jpg alt="parnassus o homem que queria enganar o diabo" height=110 width=95></td>
</tr>
<tr>
<td>Parque Jurássico</td>
<td>Jurassic Park</td>
<td>Parque Jurassico</td>
<td></td>
<td>X</td>
<td>1993</td>
<td>122</td>
<td>Ficção Científica</td>
<td><img src=Images\5601887413058.15F.jpg alt="parque jurassico" height=110 width=95></td>
</tr>
<tr>
<td>Parque Jurássico III</td>
<td>Jurassic Park III</td>
<td>Parque Jurassico III</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>93</td>
<td>Ficção Científica</td>
<td><img src=Images\3259190235496.15F.jpg alt="parque jurassico iii" height=110 width=95></td>
</tr>
<tr>
<td>Passageiros</td>
<td>Passengers</td>
<td>Passageiros</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>92</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652036092.15F.jpg alt="passageiros" height=110 width=95></td>
</tr>
<tr>
<td>Patton</td>
<td>0</td>
<td>Patton</td>
<td>X</td>
<td>X</td>
<td>1970</td>
<td>164</td>
<td>0</td>
<td><img src=Images\5600304167444.15F.jpg alt="patton" height=110 width=95></td>
</tr>
<tr>
<td>Peacock</td>
<td>0</td>
<td>Peacock</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>87</td>
<td>Drama</td>
<td><img src=Images\5600304215572.15F.jpg alt="peacock" height=110 width=95></td>
</tr>
<tr>
<td>Pearl Harbor</td>
<td>0</td>
<td>Pearl Harbor</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>176</td>
<td>Drama</td>
<td><img src=Images\5601887427239.15F.jpg alt="pearl harbor" height=110 width=95></td>
</tr>
<tr>
<td>Pecado Capital</td>
<td>Derailed</td>
<td>Pecado Capital</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887484263.15F.jpg alt="pecado capital" height=110 width=95></td>
</tr>
<tr>
<td>Pecadores e santos</td>
<td>Sinners and Saints</td>
<td>Pecadores e santos</td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5600351701189.15F.jpg alt="pecadores e santos" height=110 width=95></td>
</tr>
<tr>
<td>Pecados intimos</td>
<td>Little Children</td>
<td>Pecados intimos</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>131</td>
<td>Drama</td>
<td><img src=Images\5602193336635.15F.jpg alt="pecados intimos" height=110 width=95></td>
</tr>
<tr>
<td>Peões em Jogo</td>
<td>Lions for Lambs</td>
<td>Peoes em Jogo</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>88</td>
<td>Drama</td>
<td><img src=Images\5600304195041.15F.jpg alt="peoes em jogo" height=110 width=95></td>
</tr>
<tr>
<td>Pequenos & grandes Monstros</td>
<td>0</td>
<td>Pequenos & grandes Monstros</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M73.15F.jpg alt="pequenos & grandes monstros" height=110 width=95></td>
</tr>
<tr>
<td>Pequenos Grandes Elefantes</td>
<td>0</td>
<td>Pequenos Grandes Elefantes</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M72.15F.jpg alt="pequenos grandes elefantes" height=110 width=95></td>
</tr>
<tr>
<td>Perdidos e Achados</td>
<td>Diminished Capacity</td>
<td>Perdidos e Achados</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>85</td>
<td>Comédia</td>
<td><img src=Images\5606320008624.15F.jpg alt="perdidos e achados" height=110 width=95></td>
</tr>
<tr>
<td>Perdidos na Tempestade</td>
<td>Storm Warning</td>
<td>Perdidos na Tempestade</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>82</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5600304198523.15F.jpg alt="perdidos na tempestade" height=110 width=95></td>
</tr>
<tr>
<td>Perigo De Contágio</td>
<td>The Contaminated Man</td>
<td>Perigo De Contagio</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5608652006798.15F.jpg alt="perigo de contagio" height=110 width=95></td>
</tr>
<tr>
<td>Perigosa Sedução</td>
<td>Sea of Love</td>
<td>Perigosa Seducao</td>
<td></td>
<td>X</td>
<td>1989</td>
<td>108</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5050582068832.15F.jpg alt="perigosa seducao" height=110 width=95></td>
</tr>
<tr>
<td>Perseguição Diabólica</td>
<td>Chain Reaction</td>
<td>Perseguicao Diabolica</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>102</td>
<td>Acção</td>
<td><img src=Images\5600304163507.15F.jpg alt="perseguicao diabolica" height=110 width=95></td>
</tr>
<tr>
<td>Perseguição em Directo</td>
<td>The Caveman's Valentine</td>
<td>Perseguicao em Directo</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>101</td>
<td>Drama</td>
<td><img src=Images\5602193309752.15F.jpg alt="perseguicao em directo" height=110 width=95></td>
</tr>
<tr>
<td>Perseguido Pelo Passado</td>
<td>Carlito's Way</td>
<td>Perseguido Pelo Passado</td>
<td></td>
<td>X</td>
<td>1993</td>
<td>138</td>
<td>Drama</td>
<td><img src=Images\IAE8451BF4A9764F5.15F.jpg alt="perseguido pelo passado" height=110 width=95></td>
</tr>
<tr>
<td>Perseguindo Amy</td>
<td>Chasing Amy</td>
<td>Perseguindo Amy</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>113</td>
<td>Comédia</td>
<td><img src=Images\5600304161114.15F.jpg alt="perseguindo amy" height=110 width=95></td>
</tr>
<tr>
<td>Perto Demais</td>
<td>Closer</td>
<td>Perto Demais</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>100</td>
<td>Drama</td>
<td><img src=Images\8414533028837.15F.jpg alt="perto demais" height=110 width=95></td>
</tr>
<tr>
<td>Pigi e os seus amigos</td>
<td>0</td>
<td>Pigi e os seus amigos</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M75.15F.jpg alt="pigi e os seus amigos" height=110 width=95></td>
</tr>
<tr>
<td>Piglet - O Filme</td>
<td>Piglet's Big Movie</td>
<td>Piglet - O Filme</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>75</td>
<td>Animação</td>
<td><img src=Images\5601887456123.15F.jpg alt="piglet - o filme" height=110 width=95></td>
</tr>
<tr>
<td>Pinóquio</td>
<td>0</td>
<td>Pinoquio</td>
<td>X</td>
<td></td>
<td>1940</td>
<td>86</td>
<td>Animação</td>
<td><img src=Images\5601887530731.15F.jpg alt="pinoquio" height=110 width=95></td>
</tr>
<tr>
<td>Piratas das Caraíbas - A Maldição do Pérola Negra</td>
<td>Pirates of the Caribbean: The Curse of the Black Pearl</td>
<td>Piratas das Caraibas - A Maldicao do Perola Negra</td>
<td>X</td>
<td></td>
<td>2003</td>
<td>138</td>
<td>Aventura</td>
<td><img src=Images\5601887457878.15F.jpg alt="piratas das caraibas - a maldicao do perola negra" height=110 width=95></td>
</tr>
<tr>
<td>Piratas das Caraíbas: Nos Confins do Mundo</td>
<td>Pirates of the Caribbean: At World's End</td>
<td>Piratas das Caraibas: Nos Confins do Mundo</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>162</td>
<td>Aventura</td>
<td><img src=Images\5601887495887.15F.jpg alt="piratas das caraibas: nos confins do mundo" height=110 width=95></td>
</tr>
<tr>
<td>Piratas das Caraíbas: O Cofre do Homem Morto</td>
<td>Pirates of the Caribbean: Dead Man's Chest</td>
<td>Piratas das Caraibas: O Cofre do Homem Morto</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>145</td>
<td>Acção</td>
<td><img src=Images\5601887487165.15F.jpg alt="piratas das caraibas: o cofre do homem morto" height=110 width=95></td>
</tr>
<tr>
<td>Planeta Terra - Volume 1 - A Máquina Viva</td>
<td>0</td>
<td>Planeta Terra - Volume 1 - A Maquina Viva</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M78.15F.jpg alt="planeta terra - volume 1 - a maquina viva" height=110 width=95></td>
</tr>
<tr>
<td>Pluto Nash - O Homem da Lua</td>
<td>The Adventures of Pluto Nash</td>
<td>Pluto Nash - O Homem da Lua</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\7321977233103.15F.jpg alt="pluto nash - o homem da lua" height=110 width=95></td>
</tr>
<tr>
<td>Poirot: Série 4</td>
<td>0</td>
<td>Poirot: Serie 4</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>504</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193319799.15F.jpg alt="poirot: serie 4" height=110 width=95></td>
</tr>
<tr>
<td>Por Quem os Sinos Dobram</td>
<td>For Whom The Bell Tolls</td>
<td>Por Quem os Sinos Dobram</td>
<td></td>
<td>X</td>
<td>1943</td>
<td>159</td>
<td>Drama</td>
<td><img src=Images\0044007857427.15F.jpg alt="por quem os sinos dobram" height=110 width=95></td>
</tr>
<tr>
<td>Por Um Fio</td>
<td>Bringing Out the Dead</td>
<td>Por Um Fio</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>116</td>
<td>0</td>
<td><img src=Images\5601887410675.15F.jpg alt="por um fio" height=110 width=95></td>
</tr>
<tr>
<td>Porky's</td>
<td>0</td>
<td>Porky's</td>
<td>X</td>
<td>X</td>
<td>1981</td>
<td>95</td>
<td>Comédia</td>
<td><img src=Images\5608652007481.15F.jpg alt="porky's" height=110 width=95></td>
</tr>
<tr>
<td>Porque sim</td>
<td>Because I Said So</td>
<td>Porque sim</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>97</td>
<td>Romance</td>
<td><img src=Images\5608652031400.15F.jpg alt="porque sim" height=110 width=95></td>
</tr>
<tr>
<td>Precocemente Apaixonado</td>
<td>Tadpole</td>
<td>Precocemente Apaixonado</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>0</td>
<td>Comédia</td>
<td><img src=Images\5600304160322.15F.jpg alt="precocemente apaixonado" height=110 width=95></td>
</tr>
<tr>
<td>Premonição</td>
<td>Premonition</td>
<td>Premonicao</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>92</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887494699.15F.jpg alt="premonicao" height=110 width=95></td>
</tr>
<tr>
<td>Procurado</td>
<td>Wanted</td>
<td>Procurado</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>105</td>
<td>Acção</td>
<td><img src=Images\5050582593273.15F.jpg alt="procurado" height=110 width=95></td>
</tr>
<tr>
<td>Profissão de Risco</td>
<td>Blow</td>
<td>Profissao de Risco</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\5601887430567.15F.jpg alt="profissao de risco" height=110 width=95></td>
</tr>
<tr>
<td>Promessas Perigosas</td>
<td>Eastern Promises</td>
<td>Promessas Perigosas</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>96</td>
<td>Drama</td>
<td><img src=Images\5602193340939.15F.jpg alt="promessas perigosas" height=110 width=95></td>
</tr>
<tr>
<td>Pucca - Funny Love Stories</td>
<td>0</td>
<td>Pucca - Funny Love Stories</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>69</td>
<td>Animação</td>
<td><img src=Images\5601073804219.15F.jpg alt="pucca - funny love stories" height=110 width=95></td>
</tr>
<tr>
<td>Pular a Cerca</td>
<td>Over The Hedge</td>
<td>Pular a Cerca</td>
<td>X</td>
<td></td>
<td>2006</td>
<td>80</td>
<td>Animação</td>
<td><img src=Images\5601887491155.15F.jpg alt="pular a cerca" height=110 width=95></td>
</tr>
<tr>
<td>Pulp Fiction</td>
<td>0</td>
<td>Pulp Fiction</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>148</td>
<td>0</td>
<td><img src=Images\5600304160902.15F.jpg alt="pulp fiction" height=110 width=95></td>
</tr>
<tr>
<td>Quantum of Solace</td>
<td>0</td>
<td>Quantum of Solace</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>106</td>
<td>Acção</td>
<td><img src=Images\5600304208550.15F.jpg alt="quantum of solace" height=110 width=95></td>
</tr>
<tr>
<td>Quarteto Fantástico e o Surfista Prateado</td>
<td>Fantastic Four: Rise Of The Silver Surfer</td>
<td>Quarteto Fantastico e o Surfista Prateado</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>89</td>
<td>0</td>
<td><img src=Images\5600304189293.15F.jpg alt="quarteto fantastico e o surfista prateado" height=110 width=95></td>
</tr>
<tr>
<td>Quarto com Vista Sobre a Cidade</td>
<td>A Room With a View</td>
<td>Quarto com Vista Sobre a Cidade</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>112</td>
<td>0</td>
<td><img src=Images\5601887458615.15F.jpg alt="quarto com vista sobre a cidade" height=110 width=95></td>
</tr>
<tr>
<td>Quatro Amigas e um Par de Calças</td>
<td>The Sisterhood of the Traveling Pants</td>
<td>Quatro Amigas e um Par de Calcas</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>119</td>
<td>0</td>
<td><img src=Images\7321977593344.15F.jpg alt="quatro amigas e um par de calcas" height=110 width=95></td>
</tr>
<tr>
<td>Quatro Casamentos e Um Funeral</td>
<td>Four Weddings and a Funeral</td>
<td>Quatro Casamentos e Um Funeral</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>112</td>
<td>Comédia</td>
<td><img src=Images\5608652010436.15F.jpg alt="quatro casamentos e um funeral" height=110 width=95></td>
</tr>
<tr>
<td>Quem Se Importa</td>
<td>Who cares</td>
<td>Quem Se Importa</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>95</td>
<td>Documentário</td>
<td><img src=Images\M118F.jpg alt="quem se importa" height=110 width=95></td>
</tr>
<tr>
<td>Querido Diário</td>
<td><NAME>ario</td>
<td>Querido Diario</td>
<td></td>
<td>X</td>
<td>1994</td>
<td>96</td>
<td>0</td>
<td><img src=Images\5606699501153.15F.jpg alt="querido diario" height=110 width=95></td>
</tr>
<tr>
<td>Quills - As penas do desejo</td>
<td>Quills</td>
<td>Quills - As penas do desejo</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5600304165525.15F.jpg alt="quills - as penas do desejo" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Little Fish</td>
<td>Raia Miuda</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>109</td>
<td>Crime</td>
<td><img src=Images\ID3752707FB415905.15F.jpg alt="raia miuda" height=110 width=95></td>
</tr>
<tr>
<td>Rain Man - Encontro de Irmãos</td>
<td>Rain Man</td>
<td>Rain Man - Encontro de Irmaos</td>
<td></td>
<td>X</td>
<td>1988</td>
<td>128</td>
<td>Drama</td>
<td><img src=Images\5600304170710.15F.jpg alt="rain man - encontro de irmaos" height=110 width=95></td>
</tr>
<tr>
<td>Rambo - A Fúria do heroi</td>
<td>Rambo</td>
<td>Rambo - A Furia do heroi</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>87</td>
<td>Acção</td>
<td><img src=Images\5602193345040.15F.jpg alt="rambo - a furia do heroi" height=110 width=95></td>
</tr>
<tr>
<td>Rangers</td>
<td>Texas Rangers</td>
<td>Rangers</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>Western</td>
<td><img src=Images\5608652010221.15F.jpg alt="rangers" height=110 width=95></td>
</tr>
<tr>
<td>Rango</td>
<td>0</td>
<td>Rango</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>103</td>
<td>Animação</td>
<td><img src=Images\5601887570928.15F.jpg alt="rango" height=110 width=95></td>
</tr>
<tr>
<td>Rapariga com Brinco de Pérola</td>
<td>Girl With a Pearl Earring</td>
<td>Rapariga com Brinco de Perola</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>96</td>
<td>Drama</td>
<td><img src=Images\5602193334006.15F.jpg alt="rapariga com brinco de perola" height=110 width=95></td>
</tr>
<tr>
<td>Rápidos e Mortais</td>
<td>Highwaymen</td>
<td>Rapidos e Mortais</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>77</td>
<td>Acção</td>
<td><img src=Images\5608652024303.15F.jpg alt="rapidos e mortais" height=110 width=95></td>
</tr>
<tr>
<td>Ratatui</td>
<td>Ratatouille</td>
<td>Ratatui</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>110</td>
<td>Animação</td>
<td><img src=Images\5601887495894.15F.jpg alt="ratatui" height=110 width=95></td>
</tr>
<tr>
<td>Ray</td>
<td>0</td>
<td>Ray</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>146</td>
<td>Drama</td>
<td><img src=Images\5050582332162.15F.jpg alt="ray" height=110 width=95></td>
</tr>
<tr>
<td>Reencontrar o passado</td>
<td>Flashbacks of a Fool</td>
<td>Reencontrar o passado</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5600304207980.15F.jpg alt="reencontrar o passado" height=110 width=95></td>
</tr>
<tr>
<td>Refém</td>
<td>No Good Deed</td>
<td>Refem</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>94</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887462070.15F.jpg alt="refem" height=110 width=95></td>
</tr>
<tr>
<td>Regressa para mim</td>
<td>Return to Me</td>
<td>Regressa para mim</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>111</td>
<td>0</td>
<td><img src=Images\9338683001160.2F.jpg alt="regressa para mim" height=110 width=95></td>
</tr>
<tr>
<td>Regresso ao Futuro</td>
<td>Back to the Future</td>
<td>Regresso ao Futuro</td>
<td></td>
<td>X</td>
<td>1985</td>
<td>111</td>
<td>Aventura</td>
<td><img src=Images\3259190349292.15F.jpg alt="regresso ao futuro" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>King Arthur</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>136</td>
<td>Acção</td>
<td><img src=Images\5601887467082.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Reinaldo a rena louca</td>
<td>0</td>
<td>Reinaldo a rena louca</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M87.15F.jpg alt="reinaldo a rena louca" height=110 width=95></td>
</tr>
<tr>
<td>Relatório Kinsey</td>
<td>Kinsey</td>
<td>Relatorio Kinsey</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5608652026901.15F.jpg alt="relatorio kinsey" height=110 width=95></td>
</tr>
<tr>
<td>Relatório Minoritário</td>
<td>Minority Report</td>
<td>Relatorio Minoritario</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>142</td>
<td>Acção</td>
<td><img src=Images\5608652013000.15F.jpg alt="relatorio minoritario" height=110 width=95></td>
</tr>
<tr>
<td>Relatos de um Crime</td>
<td>A Murder of Crows</td>
<td>Relatos de um Crime</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>100</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193321488.15F.jpg alt="relatos de um crime" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Double Whammy</td>
<td>Remedio Santo</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>103</td>
<td>Comédia</td>
<td><img src=Images\I09CB93730464094A.15F.jpg alt="remedio santo" height=110 width=95></td>
</tr>
<tr>
<td>Revolutionary Road</td>
<td>0</td>
<td>Revolutionary Road</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5601887535309.15F.jpg alt="revolutionary road" height=110 width=95></td>
</tr>
<tr>
<td>Ribatejo</td>
<td>0</td>
<td>Ribatejo</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M88.15F.jpg alt="ribatejo" height=110 width=95></td>
</tr>
<tr>
<td>Rio</td>
<td>0</td>
<td>Rio</td>
<td>X</td>
<td>X</td>
<td>2011</td>
<td>92</td>
<td>Animação</td>
<td><img src=Images\5602193500050.15F.jpg alt="rio" height=110 width=95></td>
</tr>
<tr>
<td>Rise - A predadora de vampiros</td>
<td>Rise</td>
<td>Rise - A predadora de vampiros</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>93</td>
<td>Acção</td>
<td><img src=Images\5608652031813.15F.jpg alt="rise - a predadora de vampiros" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>133</td>
<td>Drama</td>
<td><img src=Images\5601887401895.15F.jpg alt="rob roy" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td><NAME></td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>1973</td>
<td>80</td>
<td>0</td>
<td><img src=Images\5601887440221.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td></td>
<td>X</td>
<td>2010</td>
<td>149</td>
<td>Acção</td>
<td><img src=Images\5600402400597.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Robôs</td>
<td>Robots</td>
<td>Robos</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>86</td>
<td>Animação</td>
<td><img src=Images\5600304162456.15F.jpg alt="robos" height=110 width=95></td>
</tr>
<tr>
<td>Romance perigoso</td>
<td>Out of Sight</td>
<td>Romance perigoso</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>118</td>
<td>Comédia</td>
<td><img src=Images\3259190354616.15F.jpg alt="romance perigoso" height=110 width=95></td>
</tr>
<tr>
<td>Ronin</td>
<td>0</td>
<td>Ronin</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>120</td>
<td>Acção</td>
<td><img src=Images\5608652006217.15F.jpg alt="ronin" height=110 width=95></td>
</tr>
<tr>
<td>Rosa de Alfama</td>
<td>0</td>
<td>Rosa de Alfama</td>
<td>X</td>
<td>X</td>
<td>1953</td>
<td>82</td>
<td>Drama</td>
<td><img src=Images\IE2A52B9994813BA5.15F.jpg alt="rosa de alfama" height=110 width=95></td>
</tr>
<tr>
<td>Ruth Rendell Mysteries</td>
<td>0</td>
<td>Ruth Rendell Mysteries</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>463</td>
<td>0</td>
<td><img src=Images\054961907199F.jpg alt="ruth rendell mysteries" height=110 width=95></td>
</tr>
<tr>
<td>S.W.A.T. - Força de Intervenção</td>
<td>S.W.A.T.</td>
<td>S.W.A.T. - Forca de Intervencao</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>112</td>
<td>Acção</td>
<td><img src=Images\8414533024990.15F.jpg alt="s.w.a.t. - forca de intervencao" height=110 width=95></td>
</tr>
<tr>
<td>S1mone</td>
<td>0</td>
<td>S1mone</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>113</td>
<td>0</td>
<td><img src=Images\3512391907365.8F.jpg alt="s1mone" height=110 width=95></td>
</tr>
<tr>
<td>Sabotagem</td>
<td>Sabotage</td>
<td>Sabotagem</td>
<td>X</td>
<td>X</td>
<td>1936</td>
<td>81</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I21D510F7F2B11BA5.15F.jpg alt="sabotagem" height=110 width=95></td>
</tr>
<tr>
<td>Sabrina a Feiticeira</td>
<td>0</td>
<td>Sabrina a Feiticeira</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M89.15F.jpg alt="sabrina a feiticeira" height=110 width=95></td>
</tr>
<tr>
<td>Sahara</td>
<td>0</td>
<td>Sahara</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>119</td>
<td>Acção</td>
<td><img src=Images\5601887474790.15F.jpg alt="sahara" height=110 width=95></td>
</tr>
<tr>
<td>Sala de Pânico</td>
<td>Panic Room</td>
<td>Sala de Panico</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>107</td>
<td>Drama</td>
<td><img src=Images\5601887438808.15F.jpg alt="sala de panico" height=110 width=95></td>
</tr>
<tr>
<td>Salazar - A Vida Privada</td>
<td>0</td>
<td>Salazar - A Vida Privada</td>
<td>X</td>
<td>X</td>
<td>2009</td>
<td>110</td>
<td>0</td>
<td><img src=Images\5606320014007.15F.jpg alt="salazar - a vida privada" height=110 width=95></td>
</tr>
<tr>
<td>Saw: Enigma Mortal</td>
<td>Saw</td>
<td>Saw: Enigma Mortal</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5608652028004.15F.jpg alt="saw: enigma mortal" height=110 width=95></td>
</tr>
<tr>
<td>Scary Movie 2 - Um Susto de Filme</td>
<td>Scary Movie 2</td>
<td>Scary Movie 2 - Um Susto de Filme</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>79</td>
<td>Comédia</td>
<td><img src=Images\5608652027182.15F.jpg alt="scary movie 2 - um susto de filme" height=110 width=95></td>
</tr>
<tr>
<td>Scary Movie 3 - Outro Susto de Filme</td>
<td>Scary Movie 3</td>
<td>Scary Movie 3 - Outro Susto de Filme</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>81</td>
<td>Comédia</td>
<td><img src=Images\5608652023887.15F.jpg alt="scary movie 3 - outro susto de filme" height=110 width=95></td>
</tr>
<tr>
<td>Scooby-Doo</td>
<td>0</td>
<td>Scooby-Doo</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>86</td>
<td>Acção</td>
<td><img src=Images\7321976234309.15F.jpg alt="scooby-doo" height=110 width=95></td>
</tr>
<tr>
<td>Scoop</td>
<td>0</td>
<td>Scoop</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5601887493579.15F.jpg alt="scoop" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 1</td>
<td>0</td>
<td>Seculo XX - Volume 1</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M101.15F.jpg alt="seculo xx - volume 1" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 2</td>
<td>0</td>
<td>Seculo XX - Volume 2</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M90.15F.jpg alt="seculo xx - volume 2" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 3</td>
<td>0</td>
<td>Seculo XX - Volume 3</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M91.15F.jpg alt="seculo xx - volume 3" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 4</td>
<td>0</td>
<td>Seculo XX - Volume 4</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M92.15F.jpg alt="seculo xx - volume 4" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 5</td>
<td>0</td>
<td>Seculo XX - Volume 5</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M93.15F.jpg alt="seculo xx - volume 5" height=110 width=95></td>
</tr>
<tr>
<td>Século XX - Volume 6</td>
<td>0</td>
<td>Seculo XX - Volume 6</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M94.15F.jpg alt="seculo xx - volume 6" height=110 width=95></td>
</tr>
<tr>
<td>Seis Graus de Separação</td>
<td>Six Degrees of Separation</td>
<td>Seis Graus de Separacao</td>
<td></td>
<td>X</td>
<td>1993</td>
<td>112</td>
<td>Comédia</td>
<td><img src=Images\5608652018654.15F.jpg alt="seis graus de separacao" height=110 width=95></td>
</tr>
<tr>
<td>Sem Rumo e Sem Remos</td>
<td>Without a Paddle</td>
<td>Sem Rumo e Sem Remos</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>95</td>
<td>Aventura</td>
<td><img src=Images\5601887469956.15F.jpg alt="sem rumo e sem remos" height=110 width=95></td>
</tr>
<tr>
<td>Semi-Pro</td>
<td>0</td>
<td>Semi-Pro</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\5602193343442.15F.jpg alt="semi-pro" height=110 width=95></td>
</tr>
<tr>
<td>Sempre</td>
<td>Always</td>
<td>Sempre</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>117</td>
<td>Fantasia</td>
<td><img src=Images\5601887418176.15F.jpg alt="sempre" height=110 width=95></td>
</tr>
<tr>
<td>Senhor da Guerra</td>
<td>Lord of War</td>
<td>Senhor da Guerra</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>116</td>
<td>0</td>
<td><img src=Images\5600304167611.15F.jpg alt="senhor da guerra" height=110 width=95></td>
</tr>
<tr>
<td>Separados de Fresco</td>
<td>The Break-Up</td>
<td>Separados de Fresco</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>85</td>
<td>0</td>
<td><img src=Images\5050582466041.15F.jpg alt="separados de fresco" height=110 width=95></td>
</tr>
<tr>
<td>Serenata à Chuva</td>
<td>Singin' in the Rain</td>
<td>Serenata a Chuva</td>
<td>X</td>
<td>X</td>
<td>1952</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5601887403561.15F.jpg alt="serenata a chuva" height=110 width=95></td>
</tr>
<tr>
<td>Serpentes a Bordo</td>
<td>Snakes on a Plane</td>
<td>Serpentes a Bordo</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>101</td>
<td>Acção</td>
<td><img src=Images\5602193346146.15F.jpg alt="serpentes a bordo" height=110 width=95></td>
</tr>
<tr>
<td>Sete Anos no Tibete</td>
<td>Seven Years in Tibet</td>
<td>Sete Anos no Tibete</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>130</td>
<td>Aventura</td>
<td><img src=Images\5601887430727.15F.jpg alt="sete anos no tibete" height=110 width=95></td>
</tr>
<tr>
<td>Sete vidas</td>
<td>Seven Pounds</td>
<td>Sete vidas</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>118</td>
<td>Drama</td>
<td><img src=Images\8414533060257.15F.jpg alt="sete vidas" height=110 width=95></td>
</tr>
<tr>
<td>Seven - 7 pecados mortais</td>
<td>Se7en</td>
<td>Seven - 7 pecados mortais</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>125</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193336192.15F.jpg alt="seven - 7 pecados mortais" height=110 width=95></td>
</tr>
<tr>
<td>Sexo Até à Morte</td>
<td>Sex and Death 101</td>
<td>Sexo Ate a Morte</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5600304205610.15F.jpg alt="sexo ate a morte" height=110 width=95></td>
</tr>
<tr>
<td>Sexo e pequeno almoço</td>
<td>Sex and Breakfast</td>
<td>Sexo e pequeno almoco</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>82</td>
<td>Comédia</td>
<td><img src=Images\5606320000529.15F.jpg alt="sexo e pequeno almoco" height=110 width=95></td>
</tr>
<tr>
<td>Shaft</td>
<td>0</td>
<td>Shaft</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>95</td>
<td>Acção</td>
<td><img src=Images\5601887417339.15F.jpg alt="shaft" height=110 width=95></td>
</tr>
<tr>
<td>Shattered Glass: Verdade ou Mentira</td>
<td>Shattered Glass</td>
<td>Shattered Glass: Verdade ou Mentira</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>90</td>
<td>Drama</td>
<td><img src=Images\5608652023429.15F.jpg alt="shattered glass: verdade ou mentira" height=110 width=95></td>
</tr>
<tr>
<td>Sherlock Holmes Vol. 1: As Aventuras de Sherlock Holmes</td>
<td>The Adventures of Sherlock Holmes</td>
<td>Sherlock Holmes Vol. 1: As Aventuras de Sherlock Holmes</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>626</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193314961.15F.jpg alt="sherlock holmes vol. 1: as aventuras de sherlock holmes" height=110 width=95></td>
</tr>
<tr>
<td>Sherlock Holmes: Episódios Duplos</td>
<td>0</td>
<td><NAME>: Episodios Duplos</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>670</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5602193322003.15F.jpg alt="sherlock holmes: episodios duplos" height=110 width=95></td>
</tr>
<tr>
<td><NAME>: Noite tenebrosa</td>
<td>Terror By Night</td>
<td><NAME>: Noite tenebrosa</td>
<td>X</td>
<td>X</td>
<td>1946</td>
<td>60</td>
<td>0</td>
<td><img src=Images\9318500013934.2F.jpg alt="sherlock holmes: noite tenebrosa" height=110 width=95></td>
</tr>
<tr>
<td><NAME>: O Carbúnculo azul</td>
<td>0</td>
<td><NAME>: O Carbunculo azul</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M56.15F.jpg alt="sherlock holmes: o carbunculo azul" height=110 width=95></td>
</tr>
<tr>
<td>Shine - Simplesmente Genial</td>
<td>Shine</td>
<td>Shine - Simplesmente Genial</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>102</td>
<td>Drama</td>
<td><img src=Images\5602193343732.15F.jpg alt="shine - simplesmente genial" height=110 width=95></td>
</tr>
<tr>
<td>Shoot 'Em Up - Atirar a Matar</td>
<td>Shoot 'Em Up</td>
<td>Shoot 'Em Up - Atirar a Matar</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>83</td>
<td>0</td>
<td><img src=Images\5602193340922.15F.jpg alt="shoot 'em up - atirar a matar" height=110 width=95></td>
</tr>
<tr>
<td>Shrek</td>
<td>0</td>
<td>Shrek</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>133</td>
<td>Animação</td>
<td><img src=Images\0667068824421.15F.jpg alt="shrek" height=110 width=95></td>
</tr>
<tr>
<td>SHREK - PARA SEMPRE</td>
<td>Shrek Forever After</td>
<td>SHREK - PARA SEMPRE</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>89</td>
<td>Animação</td>
<td><img src=Images\5601887564521.15F.jpg alt="shrek - para sempre" height=110 width=95></td>
</tr>
<tr>
<td>Shrek 2</td>
<td>0</td>
<td>Shrek 2</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>89</td>
<td>0</td>
<td><img src=Images\5050583014654.15F.jpg alt="shrek 2" height=110 width=95></td>
</tr>
<tr>
<td>Shrek o Terceiro</td>
<td>Shrek the Third</td>
<td>Shrek o Terceiro</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>89</td>
<td>Animação</td>
<td><img src=Images\5601887497706.15F.jpg alt="shrek o terceiro" height=110 width=95></td>
</tr>
<tr>
<td>Silverado</td>
<td>0</td>
<td>Silverado</td>
<td>X</td>
<td>X</td>
<td>1985</td>
<td>127</td>
<td>Western</td>
<td><img src=Images\8414533032599.15F.jpg alt="silverado" height=110 width=95></td>
</tr>
<tr>
<td>Sin City - A Cidade do Pecado</td>
<td>Sin City</td>
<td>Sin City - A Cidade do Pecado</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5608652027434.15F.jpg alt="sin city - a cidade do pecado" height=110 width=95></td>
</tr>
<tr>
<td>Sinais De Fogo</td>
<td>0</td>
<td>Sinais De Fogo</td>
<td>X</td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\5602227300830.15F.jpg alt="sinais de fogo" height=110 width=95></td>
</tr>
<tr>
<td>Sinbad - A Lenda dos Sete Mares</td>
<td>Sinbad: Legend of the Seven Seas</td>
<td>Sinbad - A Lenda dos Sete Mares</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>82</td>
<td>Animação</td>
<td><img src=Images\5050583003153.15F.jpg alt="sinbad - a lenda dos sete mares" height=110 width=95></td>
</tr>
<tr>
<td>Sky Captain e o Mundo de Amanhã</td>
<td>Sky Captain and the World of Tomorrow</td>
<td>Sky Captain e o Mundo de Amanha</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>106</td>
<td>Acção</td>
<td><img src=Images\5600304160018.15F.jpg alt="sky captain e o mundo de amanha" height=110 width=95></td>
</tr>
<tr>
<td>Sleepers - Sentimento de Revolta</td>
<td>Sleepers</td>
<td>Sleepers - Sentimento de Revolta</td>
<td>X</td>
<td>X</td>
<td>1996</td>
<td>141</td>
<td>Drama</td>
<td><img src=Images\0044007864623.15F.jpg alt="sleepers - sentimento de revolta" height=110 width=95></td>
</tr>
<tr>
<td>Só os tolos de apaixonam</td>
<td>Fools Rush In</td>
<td>So os tolos de apaixonam</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>109</td>
<td>Comédia</td>
<td><img src=Images\7892770000181.23F.jpg alt="so os tolos de apaixonam" height=110 width=95></td>
</tr>
<tr>
<td>Só se Vive Duas Vezes</td>
<td>You Only Live Twice</td>
<td>So se Vive Duas Vezes</td>
<td>X</td>
<td>X</td>
<td>1967</td>
<td>117</td>
<td>Acção</td>
<td><img src=Images\I9F0D3940F3226BEB.15F.jpg alt="so se vive duas vezes" height=110 width=95></td>
</tr>
<tr>
<td>Sob o Sol da Toscana</td>
<td>Under the Tuscan Sun</td>
<td>Sob o Sol da Toscana</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>108</td>
<td>Romance</td>
<td><img src=Images\5601887462773.15F.jpg alt="sob o sol da toscana" height=110 width=95></td>
</tr>
<tr>
<td>Sob Suspeita</td>
<td>Under Suspicion</td>
<td>Sob Suspeita</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>107</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5605290082917.15F.jpg alt="sob suspeita" height=110 width=95></td>
</tr>
<tr>
<td>Socorro sou um Peixe</td>
<td>0</td>
<td>Socorro sou um Peixe</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>77</td>
<td>0</td>
<td><img src=Images\I2988FC82D7881665.15F.jpg alt="socorro sou um peixe" height=110 width=95></td>
</tr>
<tr>
<td>Socorro, Conheci os meus pais</td>
<td>Relative Strangers</td>
<td>Socorro, Conheci os meus pais</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>90</td>
<td>0</td>
<td><img src=Images\7897744410126.23F.jpg alt="socorro, conheci os meus pais" height=110 width=95></td>
</tr>
<tr>
<td>Sol Nascente</td>
<td>Rising Sun</td>
<td>Sol Nascente</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>124</td>
<td>0</td>
<td><img src=Images\5608652002134.15F.jpg alt="sol nascente" height=110 width=95></td>
</tr>
<tr>
<td>Solaris</td>
<td>0</td>
<td>Solaris</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5608652019101.15F.jpg alt="solaris" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td>Sonhar E Facil</td>
<td>X</td>
<td>X</td>
<td>1951</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\IA0B7448813D2C45C.15F.jpg alt="sonhar e facil" height=110 width=95></td>
</tr>
<tr>
<td>Sonhos Desfeitos</td>
<td>Moonlight Mile</td>
<td>Sonhos Desfeitos</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>120</td>
<td>0</td>
<td><img src=Images\5602193317535.15F.jpg alt="sonhos desfeitos" height=110 width=95></td>
</tr>
<tr>
<td>Sonhos e Pesadelos</td>
<td>Nightmares & Dreamscapes: From the Stories of Stephen King</td>
<td>Sonhos e Pesadelos</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>376</td>
<td>Horror</td>
<td><img src=Images\012569823686F.jpg alt="sonhos e pesadelos" height=110 width=95></td>
</tr>
<tr>
<td>Sonic</td>
<td>0</td>
<td>Sonic</td>
<td>X</td>
<td>X</td>
<td>1993</td>
<td>484</td>
<td>Televisão</td>
<td><img src=Images\826663105049F.jpg alt="sonic" height=110 width=95></td>
</tr>
<tr>
<td>Sorte e Destino</td>
<td>Game 6</td>
<td>Sorte e Destino</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5606320000086.15F.jpg alt="sorte e destino" height=110 width=95></td>
</tr>
<tr>
<td>Spartacus</td>
<td>0</td>
<td>Spartacus</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>166</td>
<td>Drama</td>
<td><img src=Images\5050582268799.15F.jpg alt="spartacus" height=110 width=95></td>
</tr>
<tr>
<td>Spartan - O Rapto</td>
<td>Spartan</td>
<td>Spartan - O Rapto</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>102</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887467013.15F.jpg alt="spartan - o rapto" height=110 width=95></td>
</tr>
<tr>
<td>Spy Kids - O Filme</td>
<td>Spy Kids</td>
<td>Spy Kids - O Filme</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5608652021203.15F.jpg alt="spy kids - o filme" height=110 width=95></td>
</tr>
<tr>
<td>Spy Kids 2: A Ilha dos Sonhos Perdidos</td>
<td>Spy Kids 2: The Island of Lost Dreams</td>
<td>Spy Kids 2: A Ilha dos Sonhos Perdidos</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>96</td>
<td>Família</td>
<td><img src=Images\5608652017671.15F.jpg alt="spy kids 2: a ilha dos sonhos perdidos" height=110 width=95></td>
</tr>
<tr>
<td>Spy Kids 3-D: Game Over</td>
<td>Spy Kids 3: Game Over</td>
<td>Spy Kids 3-D: Game Over</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>81</td>
<td>Família</td>
<td><img src=Images\5608652024082.15F.jpg alt="spy kids 3-d: game over" height=110 width=95></td>
</tr>
<tr>
<td>Star Wars: Episódio I: A Ameaça Fantasma</td>
<td>Star Wars: Episode I: The Phantom Menace</td>
<td>Star Wars: Episodio I: A Ameaca Fantasma</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>131</td>
<td>Acção</td>
<td><img src=Images\5608652008402.15F.jpg alt="star wars: episodio i: a ameaca fantasma" height=110 width=95></td>
</tr>
<tr>
<td>Star Wars: Episódio II: Attack of the Clones</td>
<td>Star Wars: Episode II: Attack of the Clones</td>
<td>Star Wars: Episodio II: Attack of the Clones</td>
<td></td>
<td>X</td>
<td>2002</td>
<td>137</td>
<td>Aventura</td>
<td><img src=Images\5039036010597.4F.jpg alt="star wars: episodio ii: attack of the clones" height=110 width=95></td>
</tr>
<tr>
<td>Star Wars: Episódio III: A Vingança dos Sith</td>
<td>Star Wars: Episode III: Revenge of the Sith</td>
<td>Star Wars: Episodio III: A Vinganca dos Sith</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>134</td>
<td>Ficção Científica</td>
<td><img src=Images\5600304163156.15F.jpg alt="star wars: episodio iii: a vinganca dos sith" height=110 width=95></td>
</tr>
<tr>
<td>State and Main</td>
<td>0</td>
<td>State and Main</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>102</td>
<td>0</td>
<td><img src=Images\5606699504093.15F.jpg alt="state and main" height=110 width=95></td>
</tr>
<tr>
<td>Stay: Entre a Vida e a Morte</td>
<td>Stay</td>
<td>Stay: Entre a Vida e a Morte</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>95</td>
<td>Horror</td>
<td><img src=Images\5600304164078.15F.jpg alt="stay: entre a vida e a morte" height=110 width=95></td>
</tr>
<tr>
<td>Stitch! O Filme</td>
<td>Stitch! The Movie</td>
<td>Stitch! O Filme</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>58</td>
<td>Animação</td>
<td><img src=Images\5601887465354.15F.jpg alt="stitch! o filme" height=110 width=95></td>
</tr>
<tr>
<td>Street Racer - Velocidade Marginal</td>
<td>Street Racer</td>
<td>Street Racer - Velocidade Marginal</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>82</td>
<td>Acção</td>
<td><img src=Images\5608652036252.15F.jpg alt="street racer - velocidade marginal" height=110 width=95></td>
</tr>
<tr>
<td>Submarino U-571</td>
<td>U-571</td>
<td>Submarino U-571</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>111</td>
<td>Acção</td>
<td><img src=Images\5601887418497.15F.jpg alt="submarino u-571" height=110 width=95></td>
</tr>
<tr>
<td>Super Homem: O Regresso</td>
<td>Superman Returns</td>
<td>Super Homem: O Regresso</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>148</td>
<td>0</td>
<td><img src=Images\7321976723513.15F.jpg alt="super homem: o regresso" height=110 width=95></td>
</tr>
<tr>
<td>Supremacia</td>
<td>The Bourne Supremacy</td>
<td>Supremacia</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>104</td>
<td>Acção</td>
<td><img src=Images\5050582277753.15F.jpg alt="supremacia" height=110 width=95></td>
</tr>
<tr>
<td>Suspeita</td>
<td>Suspicion</td>
<td>Suspeita</td>
<td></td>
<td>X</td>
<td>1941</td>
<td>100</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5605189005584.15F.jpg alt="suspeita" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>0</td>
<td><NAME></td>
<td>X</td>
<td>X</td>
<td>2010</td>
<td>114</td>
<td>Comédia</td>
<td><img src=Images\5600320221779.15F.jpg alt="<NAME>" height=110 width=95></td>
</tr>
<tr>
<td>Tangled - Trama de Sentidos</td>
<td>Tangled</td>
<td>Tangled - Trama de Sentidos</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>94</td>
<td>Drama</td>
<td><img src=Images\0607727027602.15F.jpg alt="tangled - trama de sentidos" height=110 width=95></td>
</tr>
<tr>
<td>Tarzan</td>
<td>0</td>
<td>Tarzan</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>88</td>
<td>0</td>
<td><img src=Images\5601887409440.15F.jpg alt="tarzan" height=110 width=95></td>
</tr>
<tr>
<td>Tarzan 2</td>
<td>0</td>
<td>Tarzan 2</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>71</td>
<td>Animação</td>
<td><img src=Images\5601887474196.15F.jpg alt="tarzan 2" height=110 width=95></td>
</tr>
<tr>
<td>Táxi de Nova Iorque</td>
<td>Taxi</td>
<td>Taxi de Nova Iorque</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5608652026505.15F.jpg alt="taxi de nova iorque" height=110 width=95></td>
</tr>
<tr>
<td>Tempo de Valentes</td>
<td>Tiempo de Valientes</td>
<td>Tempo de Valentes</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>112</td>
<td>0</td>
<td><img src=Images\7791537677430.32F.jpg alt="tempo de valentes" height=110 width=95></td>
</tr>
<tr>
<td>Tempo Limite</td>
<td>Out of Time</td>
<td>Tempo Limite</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>101</td>
<td>Crime</td>
<td><img src=Images\5602193342605.15F.jpg alt="tempo limite" height=110 width=95></td>
</tr>
<tr>
<td>Tentação</td>
<td>0</td>
<td>Tentacao</td>
<td>X</td>
<td>X</td>
<td>1994</td>
<td>115</td>
<td>Drama</td>
<td><img src=Images\I97673C80D2BB9D3A.15F.jpg alt="tentacao" height=110 width=95></td>
</tr>
<tr>
<td>Terapia De Choque</td>
<td>Anger Management</td>
<td>Terapia De Choque</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>100</td>
<td>Comédia</td>
<td><img src=Images\5601887458493.15F.jpg alt="terapia de choque" height=110 width=95></td>
</tr>
<tr>
<td>Terapia do Amor</td>
<td>Prime</td>
<td>Terapia do Amor</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>101</td>
<td>Comédia</td>
<td><img src=Images\5602193341394.15F.jpg alt="terapia do amor" height=110 width=95></td>
</tr>
<tr>
<td>Terminal de Aeroporto</td>
<td>The Terminal</td>
<td>Terminal de Aeroporto</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>124</td>
<td>Drama</td>
<td><img src=Images\5601887493562.15F.jpg alt="terminal de aeroporto" height=110 width=95></td>
</tr>
<tr>
<td>Terra da abundância</td>
<td>Land of Plenty</td>
<td>Terra da abundancia</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>122</td>
<td>Drama</td>
<td><img src=Images\5608652025997.15F.jpg alt="terra da abundancia" height=110 width=95></td>
</tr>
<tr>
<td>Terra de Bravos</td>
<td>Home of the Brave</td>
<td>Terra de Bravos</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>103</td>
<td>Guerra</td>
<td><img src=Images\5602193345859.15F.jpg alt="terra de bravos" height=110 width=95></td>
</tr>
<tr>
<td>Terra de Idiotas</td>
<td>Idiocracy</td>
<td>Terra de Idiotas</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>83</td>
<td>0</td>
<td><img src=Images\5600304174961.15F.jpg alt="terra de idiotas" height=110 width=95></td>
</tr>
<tr>
<td>Terra de Paixões</td>
<td>Nouvelle-France</td>
<td>Terra de Paixoes</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>137</td>
<td>Aventura</td>
<td><img src=Images\5608652029032.15F.jpg alt="terra de paixoes" height=110 width=95></td>
</tr>
<tr>
<td>Terra dos sonhos</td>
<td>Imagine That</td>
<td>Terra dos sonhos</td>
<td></td>
<td>X</td>
<td>2009</td>
<td>107</td>
<td>Comédia</td>
<td><img src=Images\5601887539574.15F.jpg alt="terra dos sonhos" height=110 width=95></td>
</tr>
<tr>
<td>Terra Mágica</td>
<td>Neverwas</td>
<td>Terra Magica</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>98</td>
<td>0</td>
<td><img src=Images\5608652030670.15F.jpg alt="terra magica" height=110 width=95></td>
</tr>
<tr>
<td>Terra Sangrenta</td>
<td>The Killing Fields</td>
<td>Terra Sangrenta</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>136</td>
<td>0</td>
<td><img src=Images\5601887458622.15F.jpg alt="terra sangrenta" height=110 width=95></td>
</tr>
<tr>
<td>Terror no Afeganistão</td>
<td>The Objective</td>
<td>Terror no Afeganistao</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>86</td>
<td>Horror</td>
<td><img src=Images\5600304203258.15F.jpg alt="terror no afeganistao" height=110 width=95></td>
</tr>
<tr>
<td>The Departed: Entre Inimigos</td>
<td>The Departed</td>
<td>The Departed: Entre Inimigos</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>151</td>
<td>Drama</td>
<td><img src=Images\7321976736742.15F.jpg alt="the departed: entre inimigos" height=110 width=95></td>
</tr>
<tr>
<td>The Escapist - A Fuga</td>
<td>The Escapist</td>
<td>The Escapist - A Fuga</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>97</td>
<td>Acção</td>
<td><img src=Images\5608652038553.15F.jpg alt="the escapist - a fuga" height=110 width=95></td>
</tr>
<tr>
<td>The Fighter - Último Round</td>
<td>The Fighter</td>
<td>The Fighter - Ultimo Round</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>111</td>
<td>Drama</td>
<td><img src=Images\5606320017237.15F.jpg alt="the fighter - ultimo round" height=110 width=95></td>
</tr>
<tr>
<td>The Incredibles - Os Super Heróis</td>
<td>The Incredibles</td>
<td>The Incredibles - Os Super Herois</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>111</td>
<td>Família</td>
<td><img src=Images\5601887465668.15F.jpg alt="the incredibles - os super herois" height=110 width=95></td>
</tr>
<tr>
<td>The Punisher - O Vingador</td>
<td>The Punisher</td>
<td>The Punisher - O Vingador</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>118</td>
<td>Acção</td>
<td><img src=Images\8414533026956.15F.jpg alt="the punisher - o vingador" height=110 width=95></td>
</tr>
<tr>
<td>The Shipping News</td>
<td>0</td>
<td>The Shipping News</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>111</td>
<td>0</td>
<td><img src=Images\5608652014205.15F.jpg alt="the shipping news" height=110 width=95></td>
</tr>
<tr>
<td>Thelma & Louise</td>
<td>0</td>
<td>Thelma & Louise</td>
<td>X</td>
<td>X</td>
<td>1991</td>
<td>129</td>
<td>Acção</td>
<td><img src=Images\VC09R1D1PPB000001F.jpg alt="thelma & louise" height=110 width=95></td>
</tr>
<tr>
<td>Tigerland - O Teste Final</td>
<td>Tigerland</td>
<td>Tigerland - O Teste Final</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>97</td>
<td>0</td>
<td><img src=Images\5608652010290.15F.jpg alt="tigerland - o teste final" height=110 width=95></td>
</tr>
<tr>
<td>Tirar Vidas</td>
<td>Taking lives</td>
<td>Tirar Vidas</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\7321977284075.15F.jpg alt="tirar vidas" height=110 width=95></td>
</tr>
<tr>
<td>Todos Ao Monte</td>
<td>Yours, Mine & Ours</td>
<td>Todos Ao Monte</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>84</td>
<td>0</td>
<td><img src=Images\8414533036221.15F.jpg alt="todos ao monte" height=110 width=95></td>
</tr>
<tr>
<td>Tornado</td>
<td>Twister</td>
<td>Tornado</td>
<td></td>
<td>X</td>
<td>1996</td>
<td>108</td>
<td>0</td>
<td><img src=Images\3259190695528.15F.jpg alt="tornado" height=110 width=95></td>
</tr>
<tr>
<td>Total Recall - Desafio Total</td>
<td>Total Recall</td>
<td>Total Recall - Desafio Total</td>
<td>X</td>
<td>X</td>
<td>1990</td>
<td>108</td>
<td>Ficção Científica</td>
<td><img src=Images\I2B564B3BFE40C2E8.15F.jpg alt="total recall - desafio total" height=110 width=95></td>
</tr>
<tr>
<td>Touching The Void - Uma História de Sobrevivência</td>
<td>Touching The Void</td>
<td>Touching The Void - Uma Historia de Sobrevivencia</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>106</td>
<td>Documentário</td>
<td><img src=Images\5606118002926.15F.jpg alt="touching the void - uma historia de sobrevivencia" height=110 width=95></td>
</tr>
<tr>
<td>Toy Story (1/2)</td>
<td>0</td>
<td>Toy Story (1/2)</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>176</td>
<td>Animação</td>
<td><img src=Images\5601887412761.15F.jpg alt="toy story (1/2)" height=110 width=95></td>
</tr>
<tr>
<td>Traffic - Ninguém Sai Ileso</td>
<td>Traffic</td>
<td>Traffic - Ninguem Sai Ileso</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>147</td>
<td>Drama</td>
<td><img src=Images\I2FB6872BE6985E73.15F.jpg alt="traffic - ninguem sai ileso" height=110 width=95></td>
</tr>
<tr>
<td>Traidor</td>
<td>Traitor</td>
<td>Traidor</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>114</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887541119.15F.jpg alt="traidor" height=110 width=95></td>
</tr>
<tr>
<td>Transcendence: A Nova Inteligência</td>
<td>Transcendence</td>
<td>Transcendence: A Nova Inteligencia</td>
<td>X</td>
<td>X</td>
<td>2014</td>
<td>114</td>
<td>Drama</td>
<td><img src=Images\5602193361781.15F.jpg alt="transcendence: a nova inteligencia" height=110 width=95></td>
</tr>
<tr>
<td><NAME></td>
<td>Coach Carter</td>
<td>Treinador Carter</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>131</td>
<td>0</td>
<td><img src=Images\5601887475698.15F.jpg alt="treinador carter" height=110 width=95></td>
</tr>
<tr>
<td>Três Homens e três Bebés</td>
<td>My Baby's Daddy</td>
<td>Tres Homens e tres Bebes</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>90</td>
<td>0</td>
<td><img src=Images\5600304160384.15F.jpg alt="tres homens e tres bebes" height=110 width=95></td>
</tr>
<tr>
<td>Treze Dias</td>
<td>Thirteen Days</td>
<td>Treze Dias</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>140</td>
<td>Drama</td>
<td><img src=Images\I834FA4545447A856.15F.jpg alt="treze dias" height=110 width=95></td>
</tr>
<tr>
<td>Triângulo de Paixão</td>
<td>Book of Love</td>
<td>Triangulo de Paixao</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>83</td>
<td>Comédia</td>
<td><img src=Images\5606320000536.15F.jpg alt="triangulo de paixao" height=110 width=95></td>
</tr>
<tr>
<td>Tróia</td>
<td>Troy</td>
<td>Troia</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>156</td>
<td>0</td>
<td><img src=Images\7321976284113.15F.jpg alt="troia" height=110 width=95></td>
</tr>
<tr>
<td>Trollz: A Magia dos 5</td>
<td>Trollz : Magic Of The Five</td>
<td>Trollz: A Magia dos 5</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>66</td>
<td>Animação</td>
<td><img src=Images\5608652029803.15F.jpg alt="trollz: a magia dos 5" height=110 width=95></td>
</tr>
<tr>
<td>Trollz: As Raparigas Brilhantes</td>
<td>Trollz: You Glow Girls</td>
<td>Trollz: As Raparigas Brilhantes</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>66</td>
<td>Animação</td>
<td><img src=Images\5608652030908.15F.jpg alt="trollz: as raparigas brilhantes" height=110 width=95></td>
</tr>
<tr>
<td>Trollz: Melhores Amigas para Sempre</td>
<td>Trollz : Best Friends For Life</td>
<td>Trollz: Melhores Amigas para Sempre</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>66</td>
<td>Animação</td>
<td><img src=Images\5608652029575.15F.jpg alt="trollz: melhores amigas para sempre" height=110 width=95></td>
</tr>
<tr>
<td>Tubarão</td>
<td>Jaws</td>
<td>Tubarao</td>
<td>X</td>
<td>X</td>
<td>1975</td>
<td>121</td>
<td>Aventura</td>
<td><img src=Images\5050582166460.15F.jpg alt="tubarao" height=110 width=95></td>
</tr>
<tr>
<td>Tubarão II</td>
<td>Jaws 2</td>
<td>Tubarao II</td>
<td>X</td>
<td>X</td>
<td>1978</td>
<td>111</td>
<td>Suspense/Thriller</td>
<td><img src=Images\044007829127.15F.jpg alt="tubarao ii" height=110 width=95></td>
</tr>
<tr>
<td>Tudo o que sonhei</td>
<td>Last Holiday</td>
<td>Tudo o que sonhei</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>111</td>
<td>Comédia</td>
<td><img src=Images\7890552042145.23F.jpg alt="tudo o que sonhei" height=110 width=95></td>
</tr>
<tr>
<td>Tudo Sobre A Minha Mãe</td>
<td>Todo Sobre mi Madre</td>
<td>Tudo Sobre A Minha Mae</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>105</td>
<td>Drama</td>
<td><img src=Images\I26EABDA9630209CD.15F.jpg alt="tudo sobre a minha mae" height=110 width=95></td>
</tr>
<tr>
<td>Twisted - Homicídios Ocultos</td>
<td>Twisted</td>
<td>Twisted - Homicidios Ocultos</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>93</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887465637.15F.jpg alt="twisted - homicidios ocultos" height=110 width=95></td>
</tr>
<tr>
<td>Um Amor em África</td>
<td>In My Country</td>
<td>Um Amor em Africa</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>99</td>
<td>Drama</td>
<td><img src=Images\5608652027786.15F.jpg alt="um amor em africa" height=110 width=95></td>
</tr>
<tr>
<td>Um Ano Especial</td>
<td>A Good Year</td>
<td>Um Ano Especial</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>112</td>
<td>Comédia</td>
<td><img src=Images\5600304174619.15F.jpg alt="um ano especial" height=110 width=95></td>
</tr>
<tr>
<td>Um azar do caraças</td>
<td>Knocked Up</td>
<td>Um azar do caracas</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>127</td>
<td>Comédia</td>
<td><img src=Images\5050582544596.15F.jpg alt="um azar do caracas" height=110 width=95></td>
</tr>
<tr>
<td>Um Casamento Atribulado</td>
<td>The Anniversary Party</td>
<td>Um Casamento Atribulado</td>
<td></td>
<td>X</td>
<td>2001</td>
<td>115</td>
<td>Comédia</td>
<td><img src=Images\5602193308120.15F.jpg alt="um casamento atribulado" height=110 width=95></td>
</tr>
<tr>
<td>Um Conto de Natal</td>
<td>A Christmas Carol</td>
<td>Um Conto de Natal</td>
<td>X</td>
<td>X</td>
<td>1984</td>
<td>101</td>
<td>Família</td>
<td><img src=Images\024543617150.3F.jpg alt="um conto de natal" height=110 width=95></td>
</tr>
<tr>
<td>Um Coração Poderoso</td>
<td>A Mighty Heart</td>
<td>Um Coracao Poderoso</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887499663.15F.jpg alt="um coracao poderoso" height=110 width=95></td>
</tr>
<tr>
<td>Um Dia de Doidos</td>
<td>Freaky Friday</td>
<td>Um Dia de Doidos</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>93</td>
<td>0</td>
<td><img src=Images\5601887461042.15F.jpg alt="um dia de doidos" height=110 width=95></td>
</tr>
<tr>
<td>Um Domingo Qualquer</td>
<td>Any Given Sunday</td>
<td>Um Domingo Qualquer</td>
<td>X</td>
<td>X</td>
<td>1999</td>
<td>151</td>
<td>Drama</td>
<td><img src=Images\5601887410439.15F.jpg alt="um domingo qualquer" height=110 width=95></td>
</tr>
<tr>
<td>Um Golpe Em Itália</td>
<td>The Italian Job</td>
<td>Um Golpe Em Italia</td>
<td>X</td>
<td>X</td>
<td>2003</td>
<td>106</td>
<td>0</td>
<td><img src=Images\5601887458394.15F.jpg alt="um golpe em italia" height=110 width=95></td>
</tr>
<tr>
<td>Um Homem de Sonho</td>
<td>The Wedding Date</td>
<td>Um Homem de Sonho</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>85</td>
<td>0</td>
<td><img src=Images\5608652027915.15F.jpg alt="um homem de sonho" height=110 width=95></td>
</tr>
<tr>
<td>Um Milagre de Natal</td>
<td>Noel</td>
<td>Um Milagre de Natal</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\I39CCBE822D21BF34.15F.jpg alt="um milagre de natal" height=110 width=95></td>
</tr>
<tr>
<td>Um Milionário em Apuros</td>
<td>King's Ransom</td>
<td>Um Milionario em Apuros</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>94</td>
<td>0</td>
<td><img src=Images\5602193330701.15F.jpg alt="um milionario em apuros" height=110 width=95></td>
</tr>
<tr>
<td>Um Negócio Arriscado</td>
<td>Prime Gig</td>
<td>Um Negocio Arriscado</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>98</td>
<td>0</td>
<td><img src=Images\065935140030F.jpg alt="um negocio arriscado" height=110 width=95></td>
</tr>
<tr>
<td>Um Nome na Lista</td>
<td>Fade to Black</td>
<td>Um Nome na Lista</td>
<td></td>
<td>X</td>
<td>2006</td>
<td>110</td>
<td>Suspense/Thriller</td>
<td><img src=Images\I8CFC7AB30912B836.15F.jpg alt="um nome na lista" height=110 width=95></td>
</tr>
<tr>
<td>Um padrasto para esquecer</td>
<td>Mr. Woodcock</td>
<td>Um padrasto para esquecer</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>Comédia</td>
<td><img src=Images\5601887532261.15F.jpg alt="um padrasto para esquecer" height=110 width=95></td>
</tr>
<tr>
<td>Um Pai à Maneira</td>
<td>Big Daddy</td>
<td>Um Pai a Maneira</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>89</td>
<td>Comédia</td>
<td><img src=Images\5601887408139.15F.jpg alt="um pai a maneira" height=110 width=95></td>
</tr>
<tr>
<td>Um peixe chamado Wanda</td>
<td>A Fish Called Wanda</td>
<td>Um peixe chamado Wanda</td>
<td></td>
<td>X</td>
<td>1988</td>
<td>108</td>
<td>Comédia</td>
<td><img src=Images\5600304173131.15F.jpg alt="um peixe chamado wanda" height=110 width=95></td>
</tr>
<tr>
<td>Um Perfeito Estranho</td>
<td>Perfect Stranger</td>
<td>Um Perfeito Estranho</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>104</td>
<td>Suspense/Thriller</td>
<td><img src=Images\5601887495450.15F.jpg alt="um perfeito estranho" height=110 width=95></td>
</tr>
<tr>
<td>Um Perigo de Mulher</td>
<td>One Night at McCool's</td>
<td>Um Perigo de Mulher</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>93</td>
<td>Comédia</td>
<td><img src=Images\5602193307185.15F.jpg alt="um perigo de mulher" height=110 width=95></td>
</tr>
<tr>
<td>Um romance do outro mundo</td>
<td>Curtain Call</td>
<td>Um romance do outro mundo</td>
<td></td>
<td>X</td>
<td>1998</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\014381880427F.jpg alt="um romance do outro mundo" height=110 width=95></td>
</tr>
<tr>
<td>Uma Boa Companhia</td>
<td>In Good Company</td>
<td>Uma Boa Companhia</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>106</td>
<td>0</td>
<td><img src=Images\5608652027663.15F.jpg alt="uma boa companhia" height=110 width=95></td>
</tr>
<tr>
<td>Uma Boa Mulher</td>
<td>A Good Woman</td>
<td>Uma Boa Mulher</td>
<td></td>
<td>X</td>
<td>2004</td>
<td>93</td>
<td>Romance</td>
<td><img src=Images\5608652027809.15F.jpg alt="uma boa mulher" height=110 width=95></td>
</tr>
<tr>
<td>Uma Casa na Bruma</td>
<td>House of Sand and Fog</td>
<td>Uma Casa na Bruma</td>
<td></td>
<td>X</td>
<td>2003</td>
<td>126</td>
<td>0</td>
<td><img src=Images\5602193319034.15F.jpg alt="uma casa na bruma" height=110 width=95></td>
</tr>
<tr>
<td>Uma Família dos Diabos</td>
<td>Keeping Mum</td>
<td>Uma Familia dos Diabos</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>99</td>
<td>Comédia</td>
<td><img src=Images\5601887485444.15F.jpg alt="uma familia dos diabos" height=110 width=95></td>
</tr>
<tr>
<td>Uma História de Encantar</td>
<td>Enchanted</td>
<td>Uma Historia de Encantar</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5601887521050.15F.jpg alt="uma historia de encantar" height=110 width=95></td>
</tr>
<tr>
<td>Uma História de Violência</td>
<td>A History of Violence</td>
<td>Uma Historia de Violencia</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>92</td>
<td>Acção</td>
<td><img src=Images\5602193332255.15F.jpg alt="uma historia de violencia" height=110 width=95></td>
</tr>
<tr>
<td>Uma Ponte Longe Demais</td>
<td>A Bridge Too Far</td>
<td>Uma Ponte Longe Demais</td>
<td></td>
<td>X</td>
<td>1977</td>
<td>120</td>
<td>Acção</td>
<td><img src=Images\5608652005098.15F.jpg alt="uma ponte longe demais" height=110 width=95></td>
</tr>
<tr>
<td>Uma Questão de Honra</td>
<td>A Few Good Men</td>
<td>Uma Questao de Honra</td>
<td></td>
<td>X</td>
<td>1992</td>
<td>132</td>
<td>Drama</td>
<td><img src=Images\5606376259100.15F.jpg alt="uma questao de honra" height=110 width=95></td>
</tr>
<tr>
<td>Uma Rapariga em Cem</td>
<td>0</td>
<td>Uma Rapariga em Cem</td>
<td></td>
<td>X</td>
<td>2000</td>
<td>91</td>
<td>0</td>
<td><img src=Images\5608652008884.15F.jpg alt="uma rapariga em cem" height=110 width=95></td>
</tr>
<tr>
<td>Uma Segunda Juventude</td>
<td>Youth Without Youth</td>
<td>Uma Segunda Juventude</td>
<td>X</td>
<td>X</td>
<td>2007</td>
<td>119</td>
<td>Drama</td>
<td><img src=Images\5608652034210.15F.jpg alt="uma segunda juventude" height=110 width=95></td>
</tr>
<tr>
<td>Uma Sogra de Fugir</td>
<td>Monster-In-Law</td>
<td>Uma Sogra de Fugir</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>97</td>
<td>Romance</td>
<td><img src=Images\5602193327848.15F.jpg alt="uma sogra de fugir" height=110 width=95></td>
</tr>
<tr>
<td>Uma Verdade Inconveniente: Alerta Global</td>
<td>An Inconvenient Truth</td>
<td>Uma Verdade Inconveniente: Alerta Global</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>93</td>
<td>Documentário</td>
<td><img src=Images\5601887490370.15F.jpg alt="uma verdade inconveniente: alerta global" height=110 width=95></td>
</tr>
<tr>
<td>Uma Vida A Dois</td>
<td>The Story Of Us</td>
<td>Uma Vida A Dois</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>92</td>
<td>Drama</td>
<td><img src=Images\5601887409884.15F.jpg alt="uma vida a dois" height=110 width=95></td>
</tr>
<tr>
<td>Uma Vida de Insecto</td>
<td>A Bug's Life</td>
<td>Uma Vida de Insecto</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>91</td>
<td>Animação</td>
<td><img src=Images\5601887401024.15F.jpg alt="uma vida de insecto" height=110 width=95></td>
</tr>
<tr>
<td>Uma Vida Inacabada</td>
<td>An Unfinished Life</td>
<td>Uma Vida Inacabada</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>103</td>
<td>0</td>
<td><img src=Images\5602193329651.15F.jpg alt="uma vida inacabada" height=110 width=95></td>
</tr>
<tr>
<td>Uma vida normal</td>
<td>0</td>
<td>Uma vida normal</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M100.15F.jpg alt="uma vida normal" height=110 width=95></td>
</tr>
<tr>
<td>Underground - Era Uma Vez Um País</td>
<td>Podzemlje - bila jednom jedna zemlje</td>
<td>Underground - Era Uma Vez Um Pais</td>
<td></td>
<td>X</td>
<td>1995</td>
<td>170</td>
<td>Drama</td>
<td><img src=Images\I1FF8C4512BD83D90.15F.jpg alt="underground - era uma vez um pais" height=110 width=95></td>
</tr>
<tr>
<td>Underworld: Evolução</td>
<td>Underworld: Evolution</td>
<td>Underworld: Evolucao</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>102</td>
<td>Acção</td>
<td><img src=Images\5608652029216.15F.jpg alt="underworld: evolucao" height=110 width=95></td>
</tr>
<tr>
<td>Universidade Marshall</td>
<td>0</td>
<td>Universidade Marshall</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>131</td>
<td>Drama</td>
<td><img src=Images\085391117599F.jpg alt="universidade marshall" height=110 width=95></td>
</tr>
<tr>
<td>Vai chamar mãe a outra!</td>
<td>0</td>
<td>Vai chamar mae a outra!</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M116.15F.jpg alt="vai chamar mae a outra!" height=110 width=95></td>
</tr>
<tr>
<td>Valiant - Os Bravos do Pombal</td>
<td>Valiant</td>
<td>Valiant - Os Bravos do Pombal</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>72</td>
<td>Animação</td>
<td><img src=Images\5608652027533.15F.jpg alt="valiant - os bravos do pombal" height=110 width=95></td>
</tr>
<tr>
<td>Valmont</td>
<td>0</td>
<td>Valmont</td>
<td>X</td>
<td>X</td>
<td>1989</td>
<td>131</td>
<td>Drama</td>
<td><img src=Images\5608652022385.15F.jpg alt="valmont" height=110 width=95></td>
</tr>
<tr>
<td>Verão Escaldante</td>
<td>Summer of Sam</td>
<td>Verao Escaldante</td>
<td></td>
<td>X</td>
<td>1999</td>
<td>135</td>
<td>Drama</td>
<td><img src=Images\IEFB3F99A8B7D57D6.15F.jpg alt="verao escaldante" height=110 width=95></td>
</tr>
<tr>
<td>Verdade inquietante</td>
<td>Slow Burn</td>
<td>Verdade inquietante</td>
<td></td>
<td>X</td>
<td>2005</td>
<td>93</td>
<td>Drama</td>
<td><img src=Images\5600304179621.15F.jpg alt="verdade inquietante" height=110 width=95></td>
</tr>
<tr>
<td>Vestida para casar</td>
<td>27 Dresses</td>
<td>Vestida para casar</td>
<td></td>
<td>X</td>
<td>2008</td>
<td>106</td>
<td>Comédia</td>
<td><img src=Images\3344428032791.8F.jpg alt="vestida para casar" height=110 width=95></td>
</tr>
<tr>
<td>Vestida para matar</td>
<td>Dressed to Kill</td>
<td>Vestida para matar</td>
<td>X</td>
<td>X</td>
<td>1980</td>
<td>100</td>
<td>Horror</td>
<td><img src=Images\5600304176903.15F.jpg alt="vestida para matar" height=110 width=95></td>
</tr>
<tr>
<td>Viciados</td>
<td>Intervention</td>
<td>Viciados</td>
<td></td>
<td>X</td>
<td>2007</td>
<td>87</td>
<td>Drama</td>
<td><img src=Images\5606320000949.15F.jpg alt="viciados" height=110 width=95></td>
</tr>
<tr>
<td>Vidocq</td>
<td>0</td>
<td>Vidocq</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>100</td>
<td>0</td>
<td><img src=Images\5608652013819.15F.jpg alt="vidocq" height=110 width=95></td>
</tr>
<tr>
<td>Vigaristas à Solta</td>
<td>Trial and Error</td>
<td>Vigaristas a Solta</td>
<td></td>
<td>X</td>
<td>1997</td>
<td>94</td>
<td>Comédia</td>
<td><img src=Images\5602193306065.15F.jpg alt="vigaristas a solta" height=110 width=95></td>
</tr>
<tr>
<td>Vigaristas de Bairro</td>
<td>Small Time Crooks</td>
<td>Vigaristas de Bairro</td>
<td>X</td>
<td>X</td>
<td>2000</td>
<td>91</td>
<td>Comédia</td>
<td><img src=Images\5601887436941.15F.jpg alt="vigaristas de bairro" height=110 width=95></td>
</tr>
<tr>
<td>Vigilância</td>
<td>Surveillance</td>
<td>Vigilancia</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>93</td>
<td>Crime</td>
<td><img src=Images\5600304207409.15F.jpg alt="vigilancia" height=110 width=95></td>
</tr>
<tr>
<td>Vingadores Supremos - Vol.1</td>
<td>Ultimate Avengers - Vol 1</td>
<td>Vingadores Supremos - Vol.1</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>68</td>
<td>Animação</td>
<td><img src=Images\5608652029964.15F.jpg alt="vingadores supremos - vol.1" height=110 width=95></td>
</tr>
<tr>
<td>Violetas Púrpura</td>
<td>0</td>
<td>Violetas Purpura</td>
<td></td>
<td>X</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><img src=Images\M117.15F.jpg alt="violetas purpura" height=110 width=95></td>
</tr>
<tr>
<td>Viram-se Gregos Para Casar</td>
<td>My Big Fat Greek Wedding</td>
<td>Viram-se Gregos Para Casar</td>
<td>X</td>
<td>X</td>
<td>2002</td>
<td>108</td>
<td>Comédia</td>
<td><img src=Images\5608652016186.15F.jpg alt="viram-se gregos para casar" height=110 width=95></td>
</tr>
<tr>
<td>Virtude Fácil</td>
<td>Easy Virtue</td>
<td>Virtude Facil</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>97</td>
<td>Comédia</td>
<td><img src=Images\5606320002387.15F.jpg alt="virtude facil" height=110 width=95></td>
</tr>
<tr>
<td>Vive e Deixa Morrer</td>
<td>Live and Let Die</td>
<td>Vive e Deixa Morrer</td>
<td>X</td>
<td>X</td>
<td>1973</td>
<td>116</td>
<td>Acção</td>
<td><img src=Images\IE74A1396A2EA53BE.15F.jpg alt="vive e deixa morrer" height=110 width=95></td>
</tr>
<tr>
<td>Você Tem Uma Mensagem</td>
<td>You've Got Mail</td>
<td>Voce Tem Uma Mensagem</td>
<td>X</td>
<td>X</td>
<td>1998</td>
<td>115</td>
<td>Comédia</td>
<td><img src=Images\7321976000065.15F.jpg alt="voce tem uma mensagem" height=110 width=95></td>
</tr>
<tr>
<td>Volver - Voltar</td>
<td>Volver</td>
<td>Volver - Voltar</td>
<td>X</td>
<td>X</td>
<td>2006</td>
<td>116</td>
<td>Drama</td>
<td><img src=Images\5602193347914.15F.jpg alt="volver - voltar" height=110 width=95></td>
</tr>
<tr>
<td>Vôo da Fénix</td>
<td>Flight of the Phoenix</td>
<td>Voo da Fenix</td>
<td>X</td>
<td>X</td>
<td>2004</td>
<td>108</td>
<td>Aventura</td>
<td><img src=Images\5600304168441.15F.jpg alt="voo da fenix" height=110 width=95></td>
</tr>
<tr>
<td>Vulcão</td>
<td>Volcano</td>
<td>Vulcao</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>100</td>
<td>Acção</td>
<td><img src=Images\5600304163514.15F.jpg alt="vulcao" height=110 width=95></td>
</tr>
<tr>
<td>W.</td>
<td>0</td>
<td>W.</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>124</td>
<td>Drama</td>
<td><img src=Images\5600304201742.15F.jpg alt="w." height=110 width=95></td>
</tr>
<tr>
<td>Wall Street</td>
<td>0</td>
<td>Wall Street</td>
<td></td>
<td>X</td>
<td>1987</td>
<td>120</td>
<td>Drama</td>
<td><img src=Images\5608652005593.15F.jpg alt="wall street" height=110 width=95></td>
</tr>
<tr>
<td>Wall Street: O dinheiro nunca dorme</td>
<td>Wall Street: Money Never Sleeps</td>
<td>Wall Street: O dinheiro nunca dorme</td>
<td></td>
<td>X</td>
<td>2010</td>
<td>113</td>
<td>Drama</td>
<td><img src=Images\5600304217781.15F.jpg alt="wall street: o dinheiro nunca dorme" height=110 width=95></td>
</tr>
<tr>
<td>Wall-E</td>
<td>0</td>
<td>Wall-E</td>
<td>X</td>
<td>X</td>
<td>2008</td>
<td>95</td>
<td>Animação</td>
<td><img src=Images\5601887526895.15F.jpg alt="wall-e" height=110 width=95></td>
</tr>
<tr>
<td>Warm Springs</td>
<td>0</td>
<td>Warm Springs</td>
<td>X</td>
<td>X</td>
<td>2005</td>
<td>120</td>
<td>Drama</td>
<td><img src=Images\026359275227F.jpg alt="warm springs" height=110 width=95></td>
</tr>
<tr>
<td>Wasabi - Duros de Roer</td>
<td>Wasabi</td>
<td>Wasabi - Duros de Roer</td>
<td>X</td>
<td>X</td>
<td>2001</td>
<td>90</td>
<td>Acção</td>
<td><img src=Images\5601887441372.15F.jpg alt="wasabi - duros de roer" height=110 width=95></td>
</tr>
<tr>
<td>Wilde</td>
<td>0</td>
<td>Wilde</td>
<td>X</td>
<td>X</td>
<td>1997</td>
<td>112</td>
<td>Drama</td>
<td><img src=Images\5608652031127.15F.jpg alt="wilde" height=110 width=95></td>
</tr>
<tr>
<td><NAME> en la vuelta al mundo en 80 días</td>
<td><NAME>: La vuelta al mundo en 80 días, el largometraje</td>
<td><NAME> en la vuelta al mundo en 80 dias</td>
<td>X</td>
<td>X</td>
<td>1995</td>
<td>75</td>
<td>0</td>
<td><img src=Images\8421394506152.10F.jpg alt="willy fog en la vuelta al mundo en 80 dias" height=110 width=95></td>
</tr>
<tr>
<td>Wimbledon: Encontro Perfeito</td>
<td>Wimbledon</td>
<td>Wimbledon: Encontro Perfeito</td>
<td>X</td>
<td></td>
<td>2004</td>
<td>94</td>
<td>0</<file_sep>/exJAvas/EmployeeTableModel.java
package net.codejava.swing;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import net.codejava.model.Employee;
public class EmployeeTableModel extends AbstractTableModel
{
private final List<Employee> employeeList;
private final String[] columnNames = new String[] {
"Id", "Name", "Hourly Rate", "Part Time"
};
private final Class[] columnClass = new Class[] {
Integer.class, String.class, Double.class, Boolean.class
};
public EmployeeTableModel(List<Employee> employeeList)
{
this.employeeList = employeeList;
}
@Override
public String getColumnName(int column)
{
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public int getRowCount()
{
return employeeList.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
Employee row = employeeList.get(rowIndex);
if(0 == columnIndex) {
return row.getId();
}
else if(1 == columnIndex) {
return row.getName();
}
else if(2 == columnIndex) {
return row.getHourlyRate();
}
else if(3 == columnIndex) {
return row.isPartTime();
}
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
Employee row = employeeList.get(rowIndex);
if(0 == columnIndex) {
row.setId((Integer) aValue);
}
else if(1 == columnIndex) {
row.setName((String) aValue);
}
else if(2 == columnIndex) {
row.setHourlyRate((Double) aValue);
}
else if(3 == columnIndex) {
row.setPartTime((Boolean) aValue);
}
}
}
<file_sep>/README.md
# DVD DB
Português:
DVD DB é um programa de catalogação de filmes desenvolvido em Java.
Para utilizar o programa deve dar premissão ao ficheiro DVD_DB.jar de execução e abrir ou correr no terminal:
> java -jar DVD_DB.jar
Falta implementar a edição, ver as capas e exportar para HTML
<file_sep>/exJAvas/Employee.java
package net.codejava.model;
public class Employee
{
private int id;
private String name;
private double hourlyRate;
private boolean partTime;
public Employee(int id, String name, double hourlyRate, boolean partTime)
{
this.id = id;
this.name = name;
this.hourlyRate = hourlyRate;
this.partTime = partTime;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setHourlyRate(double hourlyRate)
{
this.hourlyRate = hourlyRate;
}
public boolean isPartTime()
{
return partTime;
}
public void setPartTime(boolean partTime)
{
this.partTime = partTime;
}
}
| 8dc1a72517439a7a637bd505f3c6d6f92a304af0 | [
"Markdown",
"Java",
"HTML"
] | 6 | Java | hugolardosa/DVD_DB | 0658f852b3ac75eb037e5e96b254ff5fd516aea7 | 1c327d01acf5c36770b94477186a3f1a53352749 |
refs/heads/master | <repo_name>vaszev/crud<file_sep>/Entity/SoftDeleteInterface.php
<?php
namespace Vaszev\CrudBundle\Entity;
/**
* Interface to support soft delete.
*/
interface SoftDeleteInterface {
/**
* Gets the deleted property.
* @return \DateTime
*/
public function getDeleted();
/**
* Sets the deleted property.
* @param mixed $deleted
*/
public function setDeleted(\DateTime $deleted = null);
}
<file_sep>/Filter/NotDeletedFilter.php
<?php
namespace Vaszev\CrudBundle\Filter;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
class NotDeletedFilter extends SQLFilter {
/**
* Gets the SQL query part to add to a query.
* @return string The constraint SQL if there is available, empty string otherwise.
*/
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) {
$filter = $targetEntity->reflClass->implementsInterface('Vaszev\CrudBundle\Entity\SoftDeleteInterface') ? $targetTableAlias . '.deleted IS NULL' : '';
return $filter;
}
}
<file_sep>/README.md
#CRUD
##Modified Symfony3 CRUD generator
Many thanks to <NAME> for his CrudGeneratorBundle (https://github.com/jordillonch/CrudGeneratorBundle) that I've could modify. This bundle has a nice backend view for your entities. You can filtering, paginating, ordering, soft-deleting your data.
###how to **install**:
https://packagist.org/packages/vaszev/crud-bundle
via **composer**:
```
$ composer install "vaszev/crud-bundle":"~2.0"
```
in your **AppKernel.php**:
```php
new Lexik\Bundle\FormFilterBundle\LexikFormFilterBundle(),
new Vaszev\CrudBundle\VaszevCrudBundle(),
```
###soft-delete
Implementing the *soft-delete* interface, you have to extend your entity. The *Base* superclass will add the following fields to your entity: *id*, *deleted*, *created*, *edited*.
```php
class Document extends Base {}
```
Now, you have to enable the filter in your config.yml file:
```yaml
orm:
filters:
not_deleted:
class: Vaszev\CrudBundle\Filter\NotDeletedFilter
enabled: true
```
###backend header-footer
Let's create the following files:
**app\Resources\views\vaszevCrudMenu.html.twig** (contains your custom styles and the backend menu too)
```twig
{% block stylesheets_sub %}{% endblock %}
{% block menu %}{% endblock %}
```
**app\Resources\views\vaszevCrudFooter.html.twig** (your personal/company informations goes here)
```twig
<footer></footer>
```
###final steps
Don't forget to update your schema.
```
$ php app/console doctrine:schema:update --force
```
You're ready to go
```
$ php app/console vaszev:generate:crud
```
<file_sep>/Command/CrudCommand.php
<?php
namespace Vaszev\CrudBundle\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCrudCommand;
use Vaszev\CrudBundle\Generator\VaszevCrudGenerator;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
class CrudCommand extends GenerateDoctrineCrudCommand {
protected $generator;
protected $formGenerator;
protected function configure() {
parent::configure();
$this->setName('vaszev:generate:crud');
$this->setDescription('Modified Symfony3 CRUD generator.');
}
protected function createGenerator($bundle = null) {
$rootDir = $this->getContainer()->getParameter('kernel.root_dir');
return new VaszevCrudGenerator($this->getContainer()->get('filesystem'), $rootDir);
}
protected function getSkeletonDirs(BundleInterface $bundle = null) {
$skeletonDirs = array();
if (isset($bundle) && is_dir($dir = $bundle->getPath() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
if (is_dir($dir = $this->getContainer()->get('kernel')->getRootdir() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
$skeletonDirs[] = $this->getContainer()->get('kernel')->locateResource('@VaszevCrudBundle/Resources/skeleton');
$skeletonDirs[] = $this->getContainer()->get('kernel')->locateResource('@VaszevCrudBundle/Resources');
return $skeletonDirs;
}
protected function interact(InputInterface $input, OutputInterface $output) {
if (method_exists($this, 'getDialogHelper')) {
$dialog = $this->getDialogHelper();
} else {
$dialog = $this->getQuestionHelper();
}
$dialog->writeSection($output, 'VaszevCrudBundle');
parent::interact($input, $output);
}
}
<file_sep>/VaszevCrudBundle.php
<?php
namespace Vaszev\CrudBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class VaszevCrudBundle extends Bundle {
}
<file_sep>/Entity/Base.php
<?php
namespace Vaszev\CrudBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\ORM\Mapping\MappedSuperclass;
//use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* @MappedSuperclass
* @HasLifecycleCallbacks
*/
class Base implements SoftDeleteInterface {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $deleted;
/**
* @ORM\Column(type="datetime")
*/
protected $created;
/**
* @ORM\Column(type="datetime")
*/
protected $edited;
public function __construct() {
if ($this->isNew()) {
$this->created = $this->edited = new \DateTime ();
}
}
/**
* Get the entity id
* @return int
*/
public function getId() {
return ( int )$this->id;
}
/**
* Get the time of deletion
* @return \DateTime|null
*/
public function getDeleted() {
return $this->deleted;
}
/**
* Get the time of creation
* @return \DateTime
*/
public function getCreated() {
return $this->created;
}
/**
* Get the time of edition
* @return \DateTime
*/
public function getEdited() {
return $this->edited;
}
/**
* Check if the entity is new
* @return bool
*/
public function isNew() {
return (empty ($this->id));
}
/**
* Set the time of deletion
* @param \DateTime $deleted
*/
public function setDeleted(\DateTime $deleted = null) {
$this->deleted = $deleted;
return $this;
}
/**
* Set the time of creation
* @param \DateTime $created
*/
public function setCreated(\DateTime $created) {
$this->created = $created;
return $this;
}
/**
* Set the time of edition
* @param \DateTime $edited
*/
public function setEdited(\DateTime $edited) {
$this->edited = $edited;
return $this;
}
/**
* Set the time of edition
* @param \DateTime $edited
* @ORM\PreUpdate
*/
public function updateEdited() {
$this->edited = new \DateTime ();
}
/**
* Bind data
* @param array $array
*/
public function bind($array) {
$ref = new \ReflectionClass ($this);
$pros = $ref->getDefaultProperties();
foreach (array_intersect_key($array, $pros) as $key => $value) {
if (is_string($value)) {
$value = trim($value);
}
$method = "set" . ucfirst($key);
$ref->hasMethod($method) ? $this->{$method} ($value) : $this->{$key} = $value;
}
return $this;
}
}
| 018453404353c084781480a56f60506f2b56fb70 | [
"Markdown",
"PHP"
] | 6 | PHP | vaszev/crud | 7c931bdd5b8796d913cbe7f98247467c88d917eb | 0e4f9659c1c6e339d00976eaf5196a65104fef64 |
refs/heads/master | <file_sep>package mosfeqanik01.braintrainer;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button goButton;
ArrayList<String> answers = new ArrayList<String>();
TextView SumTextView;
int locationOfCorrectAnswer;
TextView resulTextView;
int Score;
int numberOfQuestions;
TextView scoreTextView;
Random rand = new Random();
Button button1;
Button button2;
Button button3;
Button button4;
TextView timerTextView;
Button playButton;
ConstraintLayout gameLayout;
public void chooseAnswer(View view){
if (Integer.toString(locationOfCorrectAnswer).equals(view.getTag().toString())){
resulTextView.setText("Correct");
Score++;
}else{
resulTextView.setText("Wrong");
}
numberOfQuestions++;
scoreTextView.setText(Score + "/" + numberOfQuestions);
newQuestion();
}
public void newQuestion(){
int a = rand.nextInt(21);
int b = rand.nextInt(21);
locationOfCorrectAnswer = rand.nextInt(4) ;
SumTextView.setText(a + " + " + b);
answers.clear();
for (int i=0;i<4;i++){
if (i == locationOfCorrectAnswer){
answers.add(String.valueOf(a+b));
}else{
int wrongAnswer = rand.nextInt(41);
while (wrongAnswer == (a+b)){
wrongAnswer = rand.nextInt(41);
}
answers.add(String.valueOf(wrongAnswer));
}
}
button1.setText(answers.get(0));
button2.setText(answers.get(1));
button3.setText(answers.get(2));
button4.setText(answers.get(3));
}
public void start(View view){
goButton.setVisibility(View.INVISIBLE);
gameLayout.setVisibility(View.VISIBLE);
playAgain(findViewById(R.id.scoreTextView));
}
public void playAgain(View view){
Score=0;
numberOfQuestions=0;
timerTextView.setText("30s");
scoreTextView.setText(Score + "/" + numberOfQuestions);
playButton.setVisibility(View.INVISIBLE);
resulTextView.setText("");
newQuestion();
new CountDownTimer(30100,1000){
@Override
public void onTick(long millisUntilFinished) {
timerTextView.setText((millisUntilFinished/1000) +"s");
}
@Override
public void onFinish() {
resulTextView.setText("Done");
playButton.setVisibility(View.VISIBLE);
}
}.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
goButton= findViewById(R.id.goButton);
SumTextView= findViewById(R.id.SumTextView);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
button4 = findViewById(R.id.button4);
resulTextView = findViewById(R.id.resulTextView);
scoreTextView = findViewById(R.id.scoreTextView);
playButton = findViewById(R.id.playButton);
gameLayout =findViewById(R.id.gameLayout);
newQuestion();
timerTextView =findViewById(R.id.timerTextView);
goButton.setVisibility(View.VISIBLE);
gameLayout.setVisibility(View.INVISIBLE);
}
}
| 860a57a1e2416aa74317a5a89b0fefd4712f6fc1 | [
"Java"
] | 1 | Java | mosfeqanik/BrainTrainer | 64115d3ac8e49c14fd1feba963a7c35fd4178a12 | efbc8f4cd4d92f0965ad5e0cb71ca216c4e722ca |
refs/heads/master | <file_sep>
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
app_name="newsletter"
urlpatterns = [
]<file_sep>from django.db.models import Q
from django.shortcuts import render
from .models import Product
from django.shortcuts import get_object_or_404
# Create your views here.
def product_detail_view(request,id):
product = get_object_or_404(Product,id=id)
context = {
"product": product
}
template_name = "product_detail_view.html"
return render(request,template_name,context)
def product_list_view(request):
product = Product.objects.all()
query = request.GET.get('q')
if query:
product = Product.objects.filter(
Q (title__icontains=query)
)
context = {
"product":product
}
template_name = "product_list_view.html"
return render(request, template_name, context)
<file_sep>from django.shortcuts import render , get_object_or_404 , redirect
from .models import Post
from .forms import Form_post
from django.core.exceptions import ValidationError
from django.contrib.auth.decorators import login_required
# Create your views here.
def Post_detail(request,id):
post = get_object_or_404(Post,id=id)
context={"post":post}
template= "post_single.html"
return render(request,template,context)
def Post_list(request):
post = Post.objects.all()
context={
"post":post
}
template_name = "post_list.html"
return render(request,template_name,context)
def Post_create(request):
form = Form_post()
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request,template_name="post_create.html",context={"form":form})
def post_delete(request,id):
post = get_object_or_404(Post,id=id)
if request.method == "POST":
post.delete()
return redirect("home")
return render(request,template_name="post_delete.html",context={})
def post_edit(request,id):
post = get_object_or_404(Post,id=id)
form = Form_post(request.POST or None,instance=post)
if request.method =="POST" and form.is_valid():
form.save()
return redirect("home")
return render(request,template_name="post_edit.html",context={'form':form,"post":post})
<file_sep>from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default=1)
title = models.CharField(max_length=100,unique=True)
subject = models.CharField(max_length=100)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
updated = models.DateTimeField(auto_now_add=False,auto_now=True)
slug = models.SlugField()
active = models.BooleanField(default=True)
def __str__(self):
return self.title
class Postimage(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE)
image = models.ImageField()
<file_sep>from django.shortcuts import render,get_object_or_404 ,redirect
from .models import Poll,Choice
from .forms import Form_poll,Form_choice
from django.contrib import messages
# Create your views here.
### poll list
def Poll_list(request):
poll = Poll.objects.all()
context = {
"poll": poll
}
template_name= "poll_list.html"
return render(request,template_name,context)
### poll _detail
def Poll_single(request, id):
poll = get_object_or_404(Poll, id=id)
return render(request, template_name="poll_single.html",context={"poll":poll})
### poll create form
def Poll_create(request):
form = Form_poll(request.POST)
if request.method =="POST":
if form.is_valid():
form.save()
return render(request,template_name="poll_create.html",context={"form":form})
###poll edite form
def Poll_edit(request,id):
poll = get_object_or_404(Poll,id=id)
form =Form_poll(request.POST or None,instance=poll)
if request.method =="POST" and form.is_valid():
form.save()
return redirect("home")
return render(request,template_name="poll_edit.html",context={"form":form,"poll":poll})
###poll delete form
def Poll_delete(request,id):
poll = get_object_or_404(Poll,id=id)
if request.method =="POST":
poll.delete()
return redirect("home")
return render(request,template_name="confrom_delete.html",context={"poll":poll,})
def Choice_create(request,id):
poll = get_object_or_404(Poll,id=id)
form = Form_choice(request.POST)
if request.method=="POST" and form.is_valid():
new_choice = form.save(commit=False)
new_choice.poll = poll
new_choice.save()
return redirect("home")
return render(request,template_name="choice_create.html",context={"form":form})
def choice_delete(request,id):
choice = get_object_or_404(Choice,id=id)
if request.method =="POST":
choice.delete()
return redirect("home")
return render(request,template_name="choice_delete.html",context={"choice":choice})
def Choice_edit(request,id):
choice = get_object_or_404(Choice,id=id)
poll = get_object_or_404(Poll,id=choice.poll.id)
form = Form_choice(request.POST or None, instance=choice)
if request.method=="POST":
if form.is_valid():
form.save()
return redirect("home")
return render(request,template_name="choice_edit.html",context={"poll":poll,"form":form,"choice":choice , "edit_mode":True})
<file_sep>from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect,render,get_object_or_404
from . forms import User_register_form,UserForm,UserProfileForm,ChangePasswordForm
from django.core.exceptions import ValidationError
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.template.loader import get_template
from django.conf import settings
# Create your views here.
def contact(request):
if request.method == "POST":
name = request.POST.get('name')
family_name = request.POST.get("family name")
email = request.POST.get("email")
print(request.POST)
#email ourselves the submitted
subject = "Email from us"
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [settings.DEFAULT_FROM_EMAIL]
# OPTION 1
# contact_message = "{0},from {1} with email {2}".format(family_name,name,email)
# Option 2
context = {
'user':name,
'family_name':family_name,
'email': email
}
contact_message = get_template('contact_message.txt').render(context)
send_mail(subject,contact_message,from_email,to_email,fail_silently=True)
return redirect("home")
return render(request,template_name="contact_form.html",context={})
def login_user(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=<PASSWORD>)
if user is not None:
login(request, user)
return redirect("home")
messages.success(request,"login success Finito")
else:
return redirect("account:login")
return render(request,template_name="login.html",context={})
def logout_user(requset):
logout(requset)
return redirect("home")
def register_user(request):
if request.method == "POST":
form = User_register_form(request.POST)
print(form)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["<PASSWORD>"]
email = form.cleaned_data["email"]
user = User.objects.create_user(username=username, email=email, password=password)
return redirect('home')
else:
form = User_register_form()
return render(request, template_name="register_user.html", context={"form":form})
def ViewProfile(request):
context = {}
template_name = "viewprofile.html"
return render(request,template_name,context)
def EditProfile (request,username):
user = User.objects.get(username=username)
userprofile = UserProfileForm(request.POST or None, instance=request.user)
user_form = UserForm(request.POST or None, instance=request.user)
if request.method == "POST":
if user_form.is_valid() and userprofile.is_valid():
user_form.save()
userprofile.save()
return redirect("home")
return render(request,template_name = "edit_profile.html",context={"userform":user_form,"userprofile":userprofile})
@login_required
def change_password(request,username):
user = User.objects.get(username=username)
if request.method == "POST":
form = ChangePasswordForm(user or None, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request,user)
return render("home")
else:
raise ValidationError("no not")
else:
form = ChangePasswordForm(user)
return render(request,template_name="change_password.html",context={"form":form})<file_sep>from django import forms
from .models import Poll,Choice
class Form_poll(forms.ModelForm):
class Meta:
model = Poll
fields = [
"text"
]
class Form_choice(forms.ModelForm):
class Meta:
model = Choice
fields =[
"answer"
]<file_sep>
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
from django.contrib.auth.views import password_reset,password_reset_done
app_name="account"
urlpatterns = [
path('login/',views.login_user, name="login"),
path('logout/',views.logout_user,name="logout"),
path('register/',views.register_user,name="register"),
path('profile/',views.ViewProfile,name = "profile"),
re_path(r'^profile/change/(?P<username>[a-zA-Z0-9]+)$',views.EditProfile,name='edit_profile'),
re_path(r'^profile/change-password/(?P<username>[a-zA-Z0-9]+)/$', views.change_password, name='change_password'),
path('contact/',views.contact,name="contact"),
re_path(r'^reset-password/$',password_reset,name='rest_password'),
re_path(r'^reset-password/done/$',password_reset_done,name='password_reset_done'),
]
<file_sep>from django.shortcuts import render
def home(requset):
context = {}
template_name= "home.html"
return render(requset,template_name,context)<file_sep>
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
app_name="polls"
urlpatterns = [
path('poll-list/',views.Poll_list,name="poll_list"),
re_path(r'^poll-list/(?P<id>\d+)/$',views.Poll_single,name="poll_single"),
path('poll-list/create',views.Poll_create,name="poll_create"),
re_path(r'^poll-list/delete/(?P<id>\d+)/$',views.Poll_delete,name="poll_delete"),
re_path(r'^choice/choice-edit/(?P<id>\d+)/$',views.Choice_edit,name="choice_edit"),
re_path(r'^choice/choice-create/(?P<id>\d+)/$',views.Choice_create,name="choice_create"),
re_path(r'^choice/choice-delete/(?P<id>\d+)/$',views.choice_delete,name="choice_delete"),
re_path(r'^poll-list/edit/(?P<id>\d+)/$',views.Poll_edit,name="poll_edit")
]<file_sep>{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-8">
{% if product.productimage_set.count > 0 %}
{% for img in product.productimage_set.all %}
<img class="img-thumbnail" style="width:600px; height:600px;" src="{{img.image.url}}"/>
{% endfor %}
{% endif %}
</div>
<div class="col-md-4">
{{product.title}}
<p>{{product.price}}</p>
{% if product.varation_set.count > 1 %}
<select class="form-control">
{% for varation in product.varation_set.all %}
<option value="{{varation.id}}">{{varation}}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
</div>
{% endblock %}<file_sep>from django.urls import path,include,re_path
from . import views
app_name ="products"
urlpatterns = [
re_path(r'^list-product/(?P<id>\d+)/$',views.product_detail_view,name="product_detail_view"),
path ('list-product/',views.product_list_view,name="prodtuc_list_view")
]<file_sep>from django.db import models
# Create your models here.
class Car (models.Model):
title = models.CharField(max_length=120)
year = models.IntegerField(default=None)
def __str__(self):
return self.title
class Brand (models.Model):
title = models.CharField(max_length=120)
def __str__(self):
return self.title
class Product (models.Model):
brand = models.ManyToManyField(Brand)
car = models.ForeignKey(Car,on_delete=models.CASCADE)
title = models.CharField(max_length=120)
description = models.TextField(max_length=500)
price = models.DecimalField(max_digits=20,decimal_places=2,default=None)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
class Varation(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
title = models.CharField(max_length=120)
price = models.DecimalField(max_digits=20,decimal_places=2)
sale_price = models.DecimalField(max_digits=20, decimal_places=2,blank=True,null=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
def get_sale_price(self):
if self.sale_price is not None:
return self.sale_price
else:
return self.price
class Productimage(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
image = models.ImageField()
def __str__(self):
return self.product.title<file_sep># Generated by Django 2.0.5 on 2018-07-24 15:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=120)),
],
),
migrations.CreateModel(
name='Car',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=120)),
('year', models.IntegerField(default=None)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=120)),
('description', models.TextField(max_length=500)),
('price', models.DecimalField(decimal_places=2, default=None, max_digits=20)),
('active', models.BooleanField(default=True)),
('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Brand')),
('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Car')),
],
),
migrations.CreateModel(
name='Varation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=120)),
('price', models.DecimalField(decimal_places=2, max_digits=20)),
('sale_price', models.DecimalField(blank=True, decimal_places=2, max_digits=20, null=True)),
('active', models.BooleanField(default=True)),
('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Brand')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Product')),
],
),
]
<file_sep>
from django.urls import path,include,re_path
from . import views
app_name="blog"
urlpatterns = [
path('post-list',views.Post_list,name="post_list"),
path('post-create',views.Post_create,name="post_create"),
re_path(r'^delete/(?P<id>\d+)/$',views.post_delete,name="post_delete"),
re_path(r'^(?P<id>\d+)/$',views.Post_detail,name="post-single"),
re_path(r'^edit/(?P<id>\d+)/$',views.post_edit,name="post_edit")
]
<file_sep>from django.contrib import admin
from .models import Car,Brand,Product,Varation,Productimage
# Register your models here.
class ProductCustomise(admin.ModelAdmin):
list_display = ["title","car"]
admin.site.register(Car)
admin.site.register(Brand)
admin.site.register(Product,ProductCustomise)
admin.site.register(Varation)
admin.site.register(Productimage)
<file_sep>from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Poll(models.Model):
text = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
slug= models.SlugField()
def user_can_vote(self,user):
user_vote = user.vote_set.all()
qs = user_vote.filter(Poll=self)
if qs.exists():
return False
else:
return True
def __str__(self):
return self.text
class Choice(models.Model):
poll= models.ForeignKey(Poll,on_delete=models.CASCADE)
answer = models.TextField(max_length=200)
def __str__(self):
return self.answer
class Vote(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
choice = models.ForeignKey(Choice,on_delete=models.CASCADE)
poll = models.ForeignKey(Poll,on_delete=models.CASCADE)
class Imagepoll(models.Model):
poll = models.ForeignKey(Poll,on_delete=models.CASCADE)
image = models.ImageField()
<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class UserProfile(models.Model):
STUDENT = 1
TEACHER = 2
SUPERVISOR = 3
Role_choice = (
(STUDENT,'Student'),
(TEACHER , 'Teacher'),
(SUPERVISOR , "Supervisor"),
)
user = models.OneToOneField(User,on_delete=models.CASCADE )
name = models.CharField(max_length=120)
family_name = models.CharField(max_length=120)
country = models.CharField(max_length=120)
city = models.CharField(max_length=120)
phone_number = models.IntegerField(default=0)
description = models.TextField(max_length=500)
role = models.PositiveSmallIntegerField(choices=Role_choice,blank=True,null=True)
image = models.ImageField(blank=True)
def __str__(self):
return self.user.username
@receiver(post_save,sender=User)
def CreateProfileUser(sender,instance,created,**kwargs):
if created:
UserProfile.objects.create(user=instance)
<file_sep>from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from .models import UserProfile
class User_register_form(forms.Form):
username = forms.CharField(label="username",max_length=100,min_length=8,widget=forms.TextInput(attrs={"class":"form-control"}))
password1 = forms.CharField( label="Password",
max_length=100,
min_length=5,
widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2 = forms.CharField( label="conformation password",
max_length=100,
min_length=5,
widget=forms.PasswordInput(attrs={'class':'form-control'}))
email = forms.EmailField(widget=forms.TextInput(attrs={"class":"form-control"}))
def clean_username(self):
username = self.cleaned_data["username"].lower()
r = User.objects.filter(username=username)
if r.count():
raise ValidationError("Username already exist")
return username
def clean_email(self):
email= self.cleaned_data["email"].lower()
r= User.objects.filter(email=email)
if r.count():
raise ValidationError("Email already exist")
return email
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise ValidationError("password not match")
return password2
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ["city","country"]
class UserForm (forms.ModelForm):
class Meta:
model = User
fields = ["username","last_name"]
class ChangePasswordForm(forms.ModelForm):
old_password = forms.CharField(label="old_password",strip=False,widget=forms.PasswordInput(attrs={'autofocus':True}))
new_password = forms.CharField(label='new_password',widget=forms.PasswordInput(attrs={"class":"form-control"}))
new_password2 = forms.CharField(label="<PASSWORD>",widget=forms.PasswordInput(attrs={'class':'form-control'}))
def clean_password(self):
new1 = self.cleaned_data.get('new_password')
new2 = self.cleaned_data.get('new_password2')
if new1 and new2 and new1 != new2:
raise ValidationError("Password dosen't match")
return new2
def clean_old_password(self):
old_password = self.cleaned_data.get("old_password")
if not self.user.check_password(old_password):
raise ValidationError("password not valid")
return old_password<file_sep># Generated by Django 2.0.5 on 2018-07-21 19:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Imagepoll',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='')),
('poll', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Poll')),
],
),
]
| 4cb53a29959d0029fd377367e5f41b0f51437e9f | [
"Python",
"HTML"
] | 20 | Python | riddick1368/blogcp | 119e45b03b72daf7ab982baa4f9465159c2917b9 | 9edd8fa225a14686a29193d6c20b1c20dc095cd8 |
refs/heads/master | <file_sep>#include <Time.h>
#include <TimeLib.h>
#include "Adafruit_NeoPixel.h"
#define PIN 6
#define NUMPIXELS 16
#define PULL_PY 1 //these numbers are the ordering for the Neopixel LEDs on each pylon in serial order along the DI/DO daisy chain.
#define PUSH_PY 0
#define SHORT_PY 4
#define RECESSED 3 //might be 2
#define ROT 2
#define IRLEDb 40
#define IRLEDr 42
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(9, 6, NEO_GRB + NEO_KHZ800);
byte inc;
// VARIABLES DEFINED!
// ouputPeriod sets the number of loops through before outputing state via serial
// (kept track of with timesThrough
// scoreR and scoreB are the running red and blue score
// ownersPins for each numbered pin, tells who owns it. 0= no one owns, >0 Blue, <0 Red
// analogPin is the A# pin for the IR sensor's value
// bump_owner_score = what to add to the team with the most pylons currently owned at the end.
// duration_of_game = how many seconds total per game
int num_pylons, outputPeriod = 200, scoreB, scoreR, ownersPins[8], valueofPins[8], timesThrough, outi, scoreRlast, scoreBlast, bump_owner_score, pylons_owned;
int timedifference, sec_old = 0, seconds, output, startTime_seconds, lightPin = 11, analogPin = 5, output2, seconds2, temp_time, total_elapsed_time, initialization_full_time;
int duration_of_game = 121, flag = 0;
float val = 0.0;
void setup() { // variable initialization
num_pylons = 5; // number of indepedent pylons
scoreR = 0;
scoreB = 0;
scoreRlast = scoreR;
scoreBlast = scoreB;
timesThrough = 0; // keeps track of times through the loop
// temporary line for testing
digitalWrite(2, LOW);
for (int i = 1; i < 8; i++) {
ownersPins[i] = 0; // 0= no one owns, >0 Blue, <0 Red
valueofPins[i] = 0;
}
valueofPins[1] = 0; // here is the value map for the pins...see below for the relation to idexing and the pin values.
valueofPins[2] = 1;
valueofPins[3] = 4;
valueofPins[4] = 2;
valueofPins[5] = 3;
bump_owner_score = 2; // bump up score of the team with most ownership at end by this amount
pixels.begin(); // This initializes the NeoPixel library.
for (int i = 0; i <= 9; i++) {
pixels.setPixelColor(i, 255, 0, 0);
pixels.show();
}
delay(300);
for (int i = 0; i <= 9; i++) {
pixels.setPixelColor(i, 0, 255, 0);
pixels.show();
}
delay(300);
for (int i = 0; i <= 9; i++) {
pixels.setPixelColor(i, 0, 0, 255);
pixels.show();
}
delay(300);
for (int i = 0; i < 10; i++) {
pixels.setPixelColor(i, 0, 200, 0);
pixels.show();
delay(10);
}
pinMode(2, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(51, OUTPUT);
pinMode(53, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(10, INPUT_PULLUP);
pinMode(22, INPUT_PULLUP);
pinMode(30, INPUT_PULLUP);
pinMode(31, INPUT_PULLUP);
pinMode(24, INPUT_PULLUP);
pinMode(25, INPUT_PULLUP);
pinMode(26, INPUT_PULLUP);
pinMode(28, INPUT_PULLUP);
pinMode(IRLEDb, OUTPUT);
pinMode(IRLEDr, OUTPUT);
Serial.begin(9600);
time_t startTime = now();
startTime_seconds = second(startTime);
temp_time = startTime_seconds;
initialization_full_time = minute(startTime) * 60 + temp_time;
digitalWrite(13, HIGH);
boolean waiting = true;
digitalWrite(IRLEDb, HIGH);
digitalWrite(IRLEDr, HIGH);
digitalWrite(2, LOW); // our signal ground return
while (waiting) // for generating the start sequence from the main computer. Not in use now.
{
//if (Serial.available()) {
if (digitalRead(53) == LOW) { //sending this line low starts the run sequence.
waiting = false;
digitalWrite(IRLEDb, LOW);
digitalWrite(IRLEDr, LOW);
}
else {
pixels.setPixelColor(6, pixels.Color(255, 0, 0));
pixels.setPixelColor(7, pixels.Color(255, 0, 0));
pixels.setPixelColor(8, pixels.Color(255, 0, 0));
pixels.setPixelColor(5, pixels.Color(255, 0, 0));
pixels.show();
// Serial.write(Serial.read());
}
// }
}
pixels.setPixelColor(5, pixels.Color(255, 0, 255));
pixels.setPixelColor(6, pixels.Color(255, 0, 255));
pixels.setPixelColor(7, pixels.Color(255, 0, 255));
pixels.setPixelColor(8, pixels.Color(255, 0, 255));
pixels.show();
delay(600);
pixels.setPixelColor(5, pixels.Color(0, 0, 0));
pixels.setPixelColor(6, pixels.Color(0, 0, 0));
pixels.setPixelColor(7, pixels.Color(0, 0, 0));
pixels.setPixelColor(8, pixels.Color(0, 0, 0));
pixels.show();
delay(600);
pixels.setPixelColor(5, pixels.Color(255, 0, 255));
pixels.setPixelColor(6, pixels.Color(255, 0, 255));
pixels.setPixelColor(7, pixels.Color(255, 0, 255));
pixels.setPixelColor(8, pixels.Color(255, 0, 255));
pixels.show();
}
// The main game section
//
//
// once every "outperiod" times through the loop polling the pylons the code outputs the
// score into the serial line.
//
// here's the hardware mapping:
//
// index RED BLUE value of pin
// 2 pullpy 3 4 1
// 1 pushpy 10 22 0
// 5 shortpy 30 31 3
// 4 recessed 24 25 2
// 3 rotation 26 28 4
// light A5 (but you light it up with line 51)
//
// indicator light for light pylon
//
void loop() {
// Update the Pylon Colors to show current ownership of pylon
for (int i = 1; i <= num_pylons; i++) { // ownersPins[i]= 0 no one owns, >0 Blue, <0 Red
outi = i - 1; // have to map the ownersPins order with the pylon neopixel address
if (ownersPins[i] < 0) {
pixels.setPixelColor(outi, pixels.Color(255, 0, 0));
pixels.show();
}
if (ownersPins[i] > 0) {
pixels.setPixelColor(outi, pixels.Color(0, 0, 255));
pixels.show();
}
if (ownersPins[i] == 0) {
pixels.setPixelColor(outi, pixels.Color(0, 255, 0));
pixels.show();
}
}
// Output Score, episodically, only when the score actually changes (so the python doesn't choke on the buffer fillings!)
// TIME section...to send updates to the score board each second we need to keep track of time
time_t t = now();
seconds = second(t);
output = seconds - sec_old;
if (output == -59) { //correct for the minute boundary
output = 1;
}
if (output == 1) {
//if((scoreR!=scoreRlast)||(scoreB!=scoreBlast)){
Serial.print(scoreB);
Serial.print(' ');
Serial.println(scoreR);
// }
scoreRlast = scoreR;
scoreBlast = scoreB;
timesThrough = 0;
output = 0;
}
timesThrough++;
sec_old = seconds;
// pylon polling sections
if (digitalRead(3) == HIGH) //PULLPY pair
{
if (ownersPins[2] >= 0) { // only increment score if the ownership changes.
ownersPins[2] = -1;
scoreR = scoreR + valueofPins[2];
}
}
if (digitalRead(4) == HIGH)
{
if (ownersPins[2] <= 0) {
ownersPins[2] = +1;
scoreB = scoreB + valueofPins[2];
}
}
if (digitalRead(10) == LOW) //PUSHPY pair
{
if (ownersPins[1] >= 0) { // only increment score if the ownership changes.
ownersPins[1] = -1;
scoreR = scoreR + valueofPins[1];
delay(200); // to avoid "crashes" when both sides hit at same time
}
}
if (digitalRead(22) == LOW)
{
if (ownersPins[1] <= 0) {
ownersPins[1] = +1;
scoreB = scoreB + valueofPins[1];
delay(200); // to avoid "crashes" when both sides hit at same time
}
}
//Serial.println(analogRead(A0));
//delay(10);
if (digitalRead(30) == LOW) // SHORTPY
{
if (ownersPins[5] >= 0) { // only increment score if the ownership changes.
ownersPins[5] = -1;
scoreR = scoreR + valueofPins[5];
}
}
if (digitalRead(31) == LOW)
{
if (ownersPins[5] <= 0) {
ownersPins[5] = +1;
scoreB = scoreB + valueofPins[5];
}
}
if (digitalRead(24) == LOW) // RECESSED
{
if (ownersPins[4] >= 0) { // only increment score if the ownership changes.
ownersPins[4] = -1;
scoreR = scoreR + valueofPins[4];
}
}
if (digitalRead(25) == LOW)
{
if (ownersPins[4] <= 0) {
ownersPins[4] = +1;
scoreB = scoreB + valueofPins[4];
}
}
if (digitalRead(26) == LOW) // ROTATION
{
if (ownersPins[3] >= 0) { // only increment score if the ownership changes.
ownersPins[3] = -1;
scoreR = scoreR + valueofPins[3];
}
}
if (digitalRead(28) == LOW)
{
if (ownersPins[3] <= 0) {
ownersPins[3] = +1;
scoreB = scoreB + valueofPins[3];
}
}
// The light pylon, not quite working correctly yet! Its a common pylon, they have to drive under it when its light matches them!
digitalWrite(51, HIGH); // turnon the IR LED
val = analogRead(analogPin); // read the input pin
// Serial.println(val); // debug value
//digitalWrite(11,HIGH); // color LED indicator light RED lines for testing....
//digitalWrite(12,HIGH); // color LED : BLUE
//digitalWrite(13,HIGH); // color LED : GREEN
time_t t2 = now();
seconds2 = second(t2);
output2 = seconds2 - temp_time;
if (output2 < 0) {
output2 = output2 + 60;
}
if (output2 > 20) {
output2 = 0;
temp_time = seconds2; // then toggle the output lines!
digitalWrite(lightPin, LOW);
if (lightPin == 11) {
lightPin = 12;
}
else if (lightPin == 12) {
lightPin = 11;
}
}
digitalWrite(lightPin, HIGH);
// section to test for the end of the game!
total_elapsed_time = minute(t2) * 60 + second(t2) - initialization_full_time;
if ((total_elapsed_time == duration_of_game) && (flag == 0)) { //check time to stop game
for (int i = 1; i <= num_pylons; i++) { // check who owned the most pylons
pylons_owned = pylons_owned + ownersPins[i];
}
if (pylons_owned < 0) { // add "bump_owner_score" to score of team owning most pylons
scoreR = scoreR + bump_owner_score;
}
if (pylons_owned > 0) {
scoreB = scoreB + bump_owner_score;
}
flag = 1;
}
if (total_elapsed_time > duration_of_game) {
scoreR = scoreRlast;
scoreB = scoreBlast;
if (scoreR > scoreB) { // put the minarets color to match the winning team's color!
pixels.setPixelColor(6, pixels.Color(255, 0, 0));
pixels.setPixelColor(7, pixels.Color(255, 0, 0));
pixels.setPixelColor(8, pixels.Color(255, 0, 0));
pixels.setPixelColor(5, pixels.Color(255, 0, 0));
pixels.show();
}
if (scoreB > scoreR) {
pixels.setPixelColor(6, pixels.Color(0, 0, 255));
pixels.setPixelColor(7, pixels.Color(0, 0, 255));
pixels.setPixelColor(8, pixels.Color(0, 0, 255));
pixels.setPixelColor(5, pixels.Color(0, 0, 255));
pixels.show();
}
if (scoreR == scoreB) { // no winnner, just make the minarets green!
pixels.setPixelColor(6, pixels.Color(0, 255, 0));
pixels.setPixelColor(7, pixels.Color(0, 255, 0));
pixels.setPixelColor(8, pixels.Color(0, 255, 0));
pixels.setPixelColor(5, pixels.Color(0, 255, 0));
pixels.show();
}
}
/*if (analogRead(A1) > 500)q
{
Serial.write((int)'B');
Serial.write(12);
Serial.println();
}
if (analogRead(A0) > 500)
{
Serial.write((int)'B');
Serial.write(12);
Serial.println();
}
if (Serial.available()) {
inc = Serial.read();
switch (inc) {
case '3':
digitalWrite(50, HIGH);
digitalWrite(52, LOW);
digitalWrite(51, HIGH);
digitalWrite(53, LOW);
Serial.println('3');
break;
case '4':
digitalWrite(50, LOW);
digitalWrite(52, HIGH);
digitalWrite(53, HIGH);
digitalWrite(51, LOW);
Serial.println('4');
break;
case '5':
digitalWrite(51, LOW);
digitalWrite(53, LOW);
digitalWrite(52, LOW);
digitalWrite(54, LOW);
Serial.println('5');
break;
case 80:
pixels.setPixelColor(6, pixels.Color(0, 0, 255));
pixels.setPixelColor(7, pixels.Color(0, 0, 255));
pixels.setPixelColor(8, pixels.Color(0, 0, 255));
pixels.setPixelColor(5, pixels.Color(0, 0, 255));
pixels.show();
break;
case 90:
pixels.setPixelColor(6, pixels.Color(255, 0, 0));
pixels.setPixelColor(7, pixels.Color(255, 0, 0));
pixels.setPixelColor(8, pixels.Color(255, 0, 0));
pixels.setPixelColor(5, pixels.Color(255, 0, 0));
break;
default:
break;
}*/
delay(1);
}
<file_sep>import sys
import serial
import time
from threading import Thread
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui
from PyQt4.QtGui import QFont
# Create an PyQT4 application object.
a = QApplication(sys.argv)
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
p=w.palette()
p.setColor(w.backgroundRole(), QColor('black'));
w.setPalette(p);
# Set window size.
w.resize(1024, 600)
# Set window title
w.setWindowTitle("Canfield STEM Camp RoboCup 2017")
# Create widget
#label = QLabel(w)
#pixmap = QPixmap('/home/nick/Desktop/logo.png')
#label.setPixmap(pixmap)
#w.resize(pixmap.width(),pixmap.height())
lcdNumber = QLCDNumber(w)
lcdNumber.setGeometry(QRect(300, 500, 191, 81))
lcdNumber.setObjectName("lcdNumber")
lcdNumber1 = QLCDNumber(w)
lcdNumber1.setGeometry(QRect(24, 500, 191, 81))
lcdNumber1.setObjectName("lcdNumber1")
lcdMainClock = QLCDNumber(w)
lcdMainClock.setGeometry(QRect(512, 180, 191, 81))
lcdMainClock.setObjectName("MainClock")
font = QtGui.QFont("Times", 30, QFont.Bold)
font.setBold(True)
lbl = QtGui.QLabel('RED', w)
lbl.move(24,500)
lbl.setStyleSheet("color: red")
lbl.setFont(font)
lbl1 = QtGui.QLabel('BLUE', w)
lbl1.setStyleSheet("color: blue")
lbl1.move(300,500)
lbl1.setFont(font)
lbl2 = QtGui.QLabel('Time:', w)
lbl2.move(520,140)
lbl2.setStyleSheet("color: aqua")
lbl2.setFont(font)
lbl3 = QtGui.QLabel('THE GAMES!!!', w)
lbl3.setStyleSheet("color: aqua")
lbl3.move(450,100)
lbl3.setFont(font)
# Create a button in the window
btn = QPushButton('Start', w)
btn.move(560, 260)
# Create the actions
@pyqtSlot()
def on_click():
t.start()
# connect the signals to the slots
btn.clicked.connect(on_click)
#establish serial comm channel
ser = serial.Serial('/dev/ttyACM0', 9600)
#the countdown method, which is in a thread
def _countdown():
x = 121
for i in xrange(x,0,-1):
time.sleep(.5)
stuff = ser.readline()
stuffArr = stuff.split()
red = stuffArr[0]
blue = stuffArr[1]
lcdNumber.display(red)
lcdNumber1.display(blue)
lcdMainClock.display(i-1)
#the thread for the countdown
t = Thread(target=_countdown)
# Show window
w.show()
sys.exit(a.exec_())
<file_sep># Stem-Camp
4601's Middle School STEM Camp Code
<file_sep>int ch1, ch3, ch2, pwm1, dig1, dig2, dig3, dig4, pwm2, fadeAmount, auton;
int brightness1 = 255;
int brightness2 = 255;
int val = 0;
int flag;
void setup() {
pwm1 = 5;
pwm2 = 6;
dig1 = 7;
dig2 = 8;
dig3 = 9; // directional control of motor B
dig4 = 10;
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(4, INPUT);
pinMode(pwm1, OUTPUT);
pinMode(dig1, OUTPUT);
pinMode(pwm2, OUTPUT);
pinMode(dig2, OUTPUT);
pinMode(dig3, OUTPUT);
pinMode(dig4, OUTPUT);
auton = 0;
val = 0;
}
void loop() {
ch1 = pulseIn(2, HIGH, 25000);
delay(10);
ch3 = pulseIn(4 , HIGH, 25000);
delay(10);
Serial.print(ch1);
Serial.print(",");
Serial.println(ch3);
if (ch3 > 1400) //left
{
analogWrite(pwm1, 255);
digitalWrite(dig1, HIGH);
digitalWrite(dig2, LOW);
analogWrite(pwm2, 255);
digitalWrite(dig3, HIGH);
digitalWrite(dig4, LOW);
flag = 1;
}
if (ch3 < 1300) { //right
analogWrite(pwm1, 255);
digitalWrite(dig1, LOW);
digitalWrite(dig2, HIGH);
analogWrite(pwm2, 255);
digitalWrite(dig3, LOW);
digitalWrite(dig4, HIGH);
flag = 1;
}
else {
flag = 0;
}
if ((ch3 >= 1200) && (ch3 <= 1400 )) { //Stop
analogWrite(pwm1, 255);
digitalWrite(dig1, HIGH);
digitalWrite(dig2, HIGH);
analogWrite(pwm2, 255);
digitalWrite(dig3, HIGH);
digitalWrite(dig4, HIGH);
}
if (ch1 < 1300 && flag == 0) { //back
analogWrite(pwm1, 255);
digitalWrite(dig1, LOW);
digitalWrite(dig2, HIGH);
analogWrite(pwm2, 255);
digitalWrite(dig3, HIGH);
digitalWrite(dig4, LOW);
}
if (ch1 > 1800 && flag == 0) { //forward
analogWrite(pwm1, 255);
digitalWrite(dig1, HIGH);
digitalWrite(dig2, LOW);
analogWrite(pwm2, 255);
digitalWrite(dig3, LOW);
digitalWrite(dig4, HIGH);
}
}
| 61aaf1ee3d99ce58c0a58884d110edc84c1496aa | [
"Markdown",
"Python",
"C++"
] | 4 | C++ | CircuitBirds-FRC4601/Stem-Camp | d0be9ea859fa5ef83944f7e1da6cce74a5cc722a | 628b678ba12ddb84fec343da3b32e2464d8c4a3f |
refs/heads/master | <repo_name>mblwhoi/dla_catalog<file_sep>/sites/all/modules/custom/dla_catalog/feeds/DLACatalogNodeProcessor.inc
<?php
/**
* @file
* Class definition of DLACatalogNodeProcessor.
*/
/**
* Creates nodes from feed items.
*/
class DLACatalogNodeProcessor extends FeedsProcessor {
/**
* Implementation of FeedsProcessor::process().
*/
public function process(FeedsImportBatch $batch, FeedsSource $source) {
// If we don't have term field db info, get it.
if (! isset($batch->term_field_columns)){
$batch->term_field_columns = array();
$term_fields = array('term_id');
foreach ($term_fields as $tf){
$tf_info = term_fields_term_fields_api('storage', term_fields_field_load($tf));
$batch->term_field_columns[$tf] = array_shift(array_keys($tf_info));
}
}
// If we don't have vocabulary ids, get them.
if (! isset($batch->vocabulary_ids) ){
$batch->vocabulary_ids = array();
$batch->fields_vocabularies = array(
'person' => 'Persons',
'cruise' => 'Cruises',
'collection' => 'Collections',
'ship' => 'Ships'
);
foreach ($batch->fields_vocabularies as $k => $v){
$result = db_query("SELECT v.vid from {vocabulary} v WHERE v.name = '%s'", $v);
if ($result){
$o = db_fetch_object($result);
$batch->vocabulary_ids[$k] = $o->vid;
}
}
}
// Keep track of processed items in this pass, set total number of items.
$processed = 0;
if (!$batch->getTotal(FEEDS_PROCESSING)) {
$batch->setTotal(FEEDS_PROCESSING, count($batch->items));
}
// Process each item...
while ($item = $batch->shiftItem()) {
// Get nid from item (if present).
$nid = $item['nid'];
// Build node in memory.
$node = $this->buildNode($nid, 'record', $source->feed_nid);
// Map and save node. If errors occur don't stop but report them.
try {
// Set title.
$node->title = $item['title'];
// Set text fields.
$text_fields = array(
'contributor',
'coverage',
'creator',
'description',
'identifier',
'language',
'publisher',
'relation',
'rights',
'source',
'subject'
);
foreach ($text_fields as $f){
$node->{"field_$f"} = array();
$values = json_decode($item[$f], TRUE);
if (is_array($values)){
foreach ($values as $v){
$node->{"field_$f"}[] = array('value' => $v);
}
}
}
// Set date fields.
$date_fields = array(
'date_created'
);
foreach ($date_fields as $f){
$node->{"field_$f"} = array();
$values = json_decode($item[$f], TRUE);
if (is_array($values)){
foreach ($values as $v){
$drupal_date = dla_catalog_node_processor_convert_ISO_date_to_drupal_dates($v);
if ($drupal_date){
$node->{"field_$f"}[] = $drupal_date;
}
}
}
}
// Set normal taxonomy fields.
$normal_taxonomy_fields = array(
'collection'
);
foreach ($normal_taxonomy_fields as $f){
$node->{"field_$f"} = array();
$values = json_decode($item[$f], TRUE);
if (is_array($values)){
foreach ($values as $v){
// Skip if there is no term name.
if (! $v['name']){
continue;
}
// Get the term's vocabulary id.
$vid = $batch->vocabulary_ids[$f];
// Check if the term already exists.
$result = db_query("SELECT t.tid FROM {term_data} t WHERE t.name = '%s' AND t.vid = '%s'", $v['name'], $vid);
$term = '';
if ($result){
$o = db_fetch_object($result);
$term = taxonomy_get_term($o->tid);
}
// If the term did not exist, create it.
if (! $term){
$term = array(
'name' => $v['name'],
'description' => $v['description'],
'weight' => 0,
);
$term['vid'] = $vid;
// Set parent if we have a parent tid.
$term['parent'] = $parent_tid ? array($parent_tid) : array();
$term['relations'] = array();
$term['synonyms'] = '';
// Save term and get it as an object.
taxonomy_save_term($term);
$term = taxonomy_get_term($term['tid']);
}
// Set the parent tid.
$parent_tid = $term->tid;
// Add the term to the taxonomy field's values.
$node->{"field_$f"}[] = array('value' => $term->tid);
}
}
}
// Set identified taxonomy fields.
$identified_taxonomy_fields = array(
'cruise',
'person',
'ship'
);
foreach ($identified_taxonomy_fields as $f){
$node->{"field_$f"} = array();
$values = json_decode($item[$f], TRUE);
if (is_array($values)){
foreach ($values as $v){
// Skip if there is no term name or identifier.
if (! $v['name'] || ! $v['term_id_value']){
continue;
}
// Get the term's vocabulary id.
$vid = $batch->vocabulary_ids[$f];
// Try to get the term.
$result = db_query("SELECT t.tid FROM {term_data} t INNER JOIN {term_fields_term} tf ON t.tid = tf.tid WHERE t.name = '%s' AND tf.%s = '%s' ", $v['name'], $batch->term_field_columns['term_id'], $v['term_id_value']);
$term = '';
if ($result){
$o = db_fetch_object($result);
$term = taxonomy_get_term($o->tid);
}
// If the term did not exist, create it.
if (! $term){
$term = array(
'name' => $v['name'],
'description' => $v['description'],
'weight' => 0,
);
$term['vid'] = $vid;
$term['parent'] = array();
$term['relations'] = array();
$term['synonyms'] = '';
$term['fields']['term_id'] = array('value' => $v['term_id_value']);
// Create the term and load it as an object.
taxonomy_save_term($term);
$term = taxonomy_get_term($term['tid']);
}
if ($term->tid){
// Add the term to the taxonomy field's values.
$node->{"field_$f"}[] = array('value' => $term->tid);
}
}
}
}
// Set items.
$node->field_items = array();
$values = json_decode($item['items'], TRUE);
if (is_array($values)){
foreach ($values as $v){
$item_node = "";
// Load item node or initialize new node.
$item_node = $this->buildNode($v['nid'], 'item', $source->feed_nid);
// Set item field values.
$item_text_fields = array('item_format', 'item_extent', 'item_description');
foreach ($item_text_fields as $item_f){
$item_node->{"field_" . $item_f} = array();
$item_values = $v[$item_f];
if (is_array($item_values)){
foreach ($item_values as $item_v){
$item_node->{"field_" . $item_f}[] = array('value' => $item_v);
}
}
}
// Save item node.
node_save($item_node);
// Add item node reference to main record node.
$node->field_items[] = array('nid' => $item_node->nid);
}
}
// Save the node.
node_save($node);
if (!empty($nid)) {
$batch->updated++;
}
else {
$batch->created++;
}
}
catch (Exception $e) {
drupal_set_message($e->getMessage(), 'warning');
watchdog('feeds', $e->getMessage(), array(), WATCHDOG_WARNING);
}
$processed++;
if ($processed >= variable_get('feeds_node_batch_size', FEEDS_NODE_BATCH_SIZE)) {
$batch->setProgress(FEEDS_PROCESSING, $batch->created + $batch->updated);
return;
}
}
// Set messages.
if ($batch->created) {
drupal_set_message(format_plural($batch->created, 'Created @number @type node.', 'Created @number @type nodes.', array('@number' => $batch->created, '@type' => 'record')));
}
if ($batch->updated) {
drupal_set_message(format_plural($batch->updated, 'Updated @number @type node.', 'Updated @number @type nodes.', array('@number' => $batch->updated, '@type' => 'record' )));
}
if (! $batch->created && ! $batch->updated){
drupal_set_message(t('There is no new content.'));
}
$batch->setProgress(FEEDS_PROCESSING, FEEDS_BATCH_COMPLETE);
}
/**
* Implementation of FeedsProcessor::clear().
*/
public function clear(FeedsBatch $batch, FeedsSource $source) {
drupal_set_message(t('Nothing has been cleared. Delete nodes from normal node management tools.'));
$batch->setProgress(FEEDS_CLEARING, FEEDS_BATCH_COMPLETE);
}
/**
* Override parent::configForm().
*/
public function configForm(&$form_state) {
$author = user_load(array('uid' => $this->config['author']));
$form['author'] = array(
'#type' => 'textfield',
'#title' => t('Author'),
'#description' => t('Select the author of the nodes to be created - leave empty to assign "anonymous".'),
'#autocomplete_path' => 'user/autocomplete',
'#default_value' => empty($author->name) ? 'anonymous' : check_plain($author->name),
);
return $form;
}
/**
* Override parent::configFormValidate().
*/
public function configFormValidate(&$values) {
if ($author = user_load(array('name' => $values['author']))) {
$values['author'] = $author->uid;
}
else {
$values['author'] = 0;
}
}
/**
* Return available mapping targets.
*/
public function getMappingTargets() {
$targets = array();
return $targets;
}
/**
* Creates a new node object in memory and returns it.
*/
protected function buildNode($nid, $type, $feed_nid) {
$populate = FALSE;
$node = new stdClass();
if (empty($nid)) {
$node->created = FEEDS_REQUEST_TIME;
$node->type = $type;
$node->changed = FEEDS_REQUEST_TIME;
$node->uid = $this->config['author'];
}
else {
$node = node_load($nid, NULL, TRUE);
}
static $included;
if (!$included) {
module_load_include('inc', 'node', 'node.pages');
$included = TRUE;
}
node_object_prepare($node);
// Populate properties that are set by node_object_prepare().
$node->log = 'Created/updated by FeedsNodeProcessor';
return $node;
}
}
<file_sep>/sites/all/modules/custom/dla_catalog/feeds/DLACatalogTermProcessor.inc
<?php
/**
* @file
* Class definition of DLACatalogNodeProcessor.
*/
/**
* Creates nodes from feed items.
*/
class DLACatalogTermProcessor extends FeedsProcessor {
/**
* Implementation of FeedsProcessor::process().
*/
public function process(FeedsImportBatch $batch, FeedsSource $source) {
// Keep track of processed items in this pass, set total number of items.
$processed = 0;
if (!$batch->getTotal(FEEDS_PROCESSING)) {
$batch->setTotal(FEEDS_PROCESSING, count($batch->items));
}
// Process each item...
while ($item = $batch->shiftItem()) {
// Map and save term. If errors occur don't stop but report them.
try {
// Array to hold term data.
$term = array();
// Get tid from item (if present).
$tid = $item['tid'];
// If there was a tid, try to load the term.
if ($tid) {
$term = (array) taxonomy_get_term($tid);
if (! $term){
throw new Exception("No term with tid '$tid' exists, item was skipped.");
}
}
// Set blank defaults.
$term['relations'] = array();
$term['synonyms'] = '';
// Set simple term properties from item.
$simple_term_properties = array('name', 'description', 'weight', 'vid');
foreach ($simple_term_properties as $p){
$term[$p] = $item[$p];
}
// Set parent if present.
$term['parent'] = $item['parent'] ? array($item['parent']) : array();
// Set term field values from item.
$term_fields = array('term_id');
foreach ($term_fields as $f){
$term['fields'][$f] = array('value' => $item[$f]);
}
// Save the term.
taxonomy_save_term($term);
if (! empty($item['tid'])) {
$batch->updated++;
}
else {
$batch->created++;
}
}
catch (Exception $e) {
drupal_set_message($e->getMessage(), 'warning');
watchdog('feeds', $e->getMessage(), array(), WATCHDOG_WARNING);
}
$processed++;
if ($processed >= variable_get('feeds_node_batch_size', FEEDS_NODE_BATCH_SIZE)) {
$batch->setProgress(FEEDS_PROCESSING, $batch->created + $batch->updated);
return;
}
}
// Set messages.
if ($batch->created) {
drupal_set_message(format_plural($batch->created, 'Created @number term.', 'Created @number terms.', array('@number' => $batch->created)));
}
if ($batch->updated) {
drupal_set_message(format_plural($batch->created, 'Updated @number term.', 'Updated @number terms.', array('@number' => $batch->updated)));
}
if (! $batch->created && ! $batch->updated){
drupal_set_message(t('There are no new terms.'));
}
$batch->setProgress(FEEDS_PROCESSING, FEEDS_BATCH_COMPLETE);
}
/**
* Implementation of FeedsProcessor::clear().
*/
public function clear(FeedsBatch $batch, FeedsSource $source) {
drupal_set_message(t('Nothing has been cleared. Delete terms from normal term management tools.'));
$batch->setProgress(FEEDS_CLEARING, FEEDS_BATCH_COMPLETE);
}
/**
* Return available mapping targets.
*/
public function getMappingTargets() {
$targets = array();
return $targets;
}
}
| ae13235f32fda1dbfd7b23586f7328ed93e3ddc5 | [
"PHP"
] | 2 | PHP | mblwhoi/dla_catalog | abf52a692333606dba040753bf36d717ef60e6c4 | 6f20e8189500afa2633970e476d8531f96058797 |
refs/heads/master | <file_sep>---
title: "Plotting Tape2Tape"
author: "<NAME>"
date: "3/28/2018"
output: html_document
---
## Tape 2 Tape Data
Ok today I'm going to be going over a few of the ways you can graph Tape 2 tape
data and show the different types of zone entrys and shot assists on a rink diagram.
For this excercise you will need R installed along with the `tidyverse` package.
`tidyverse` is actually a collection of packages, and you probably won't need
all of them for this excercise, but I just find it's easier to load them all at
once.
This tutorial will be written from the stand point of someone who is pretty new
to R so if you've just started don't worry. However, you have some familiarty
with at least being able to run scripts in R, Rstuido, and some basic syntax
such as `<-` assignment and function notation. Ok lets get to work.
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(lubridate)
```
## The Data
Ok first thing to do is to import the data into a dataframe. You can think of a
dataframe as kind of like an excel spreadsheet as there are rows and columns with
values located at the intersection of each row with each column. I'm going to
do this using the `read_csv` function that is in the `readr` package that will
be loading into the script when we used `library()` on it up above.
`readr` is mainly a packge for reading in character delimited files such as csv
files but also tab delimited files, or my personal favorite `|` delimited files.
In this instance we will be reading in a csv file hence the use of `read_csv`.
The data comes in two files: one contains the actual play by play that has been
tracked and another that has each player along with their skater ids. We'll need
that second file because as you'll see with the play by play file each player
is identified by their id instead of their name. Ok lets get the data in and
get to work.
```{r cars}
file_name <- c('~/HockeyStuff/Tape2TapeData/Tape2Tape/11_10_plays.csv')
players_file_name <- c('~/HockeyStuff/Tape2TapeData/Tape2Tape/11_10_roster.csv')
pbp <- read_csv(file_name)
players <- read_csv(players_file_name)
```
Ok what I've done here is I've stored the path to the files as they would be on
my computer into a variable and then read those variables into my dataframes I've
named `pbp` and `players`. You can just put the file path in the `read_csv` function
itself but is always good coding practice to store it in a variable and then use
that variable throughout the script.
One reason is that it saves you from having
to cut and paste/type a lot, and another is that if you wanted to run the same
script on another set of data all you would have to do is change that one variable
instead of multiple if you were reading it in at multiple points in your script.
And so you can see the output that shows us that the files were read in succesfully.
You don't really need to know what the output is, but its just telling you that
it parsed certain columns with certain specifications such as the `periodTime`
columns was read in as a time format etc. Again not much you need to worry about.
Let's take a look at the data.
```{r pressure, echo=FALSE}
head(pbp)
```
The `head()` function will return the first six rows of any dataframe, and you
can see all the different columns and we'll have a brief break down of each one:
```
period: the period the event took place in
periodTime: the score keepers time for each event
periodTimeRemaining: what the clock would be if you were watching the game
awayPlayer0Id...awayPlayer6Id: the six away players on the ice for event includes goalie
homePlayer0Id...homePlayer0Id: same as away but with home players
event: the main events tracked by Tape2Tape which include Zone Entry, Zone Exit,
Blocked Shot, Shot, Missed Shot, and Goal
eventType: this column further describes the event column. Will describe type of
shot and type of Zone Exit/Entry as either Uncontrolled, Failed, or
Controlled
eventResult: Lost or Recovered. This will only refer to Uncontrolled Zone Exits
and Entries
eventTeam: Tells the team that performed the event in the event column
x0, y0: This is the location of the event on the ice, there will only be a
corresponding x1, y1 value if the event was a zone exit created by a pass
plyer0Id, player1Id: Player0 is the player that performed the event in the event
column. If the event is a pass then player 0 is the passer and
player1 is the player that recieved the pass.
pass0x0, pass0y0...:These columns detail the passes that lead up to the event in
the event column. pass0 is the pass right before the event,
pass1 is the pass before that etc.
```
The `players` dataframe is a lot more straightforward and the columns are
self explanatory so we won't go over them. Ok let's convert all the user Ids
in the play by play dataframe to actual players names to make looking at the
data and subsetting it easier.
```{r}
#convert player ids to actual player names from the player dataframe
convert_ids <- function(column, player_df){
column <- player_df[match(column, player_df$playerId, nomatch = column),
c('fullName')]
}
#converting playerids to playernames
pbp[4:15] <- pbp %>% select(awayPlayer0Id:homePlayer5Id) %>%
sapply(convert_ids, player_df = players)
pbp[,c('player0Id', 'player1Id', 'pass0player0Id', 'pass0player1Id',
'pass1player0Id', 'pass1player1Id', 'pass2player0Id', 'pass2player1Id',
'pass3player0Id', 'pass3player1Id',
'pass4player0Id', 'pass4player1Id')] <-
pbp[,c('player0Id', 'player1Id', 'pass0player0Id', 'pass0player1Id',
'pass1player1Id', 'pass1player1Id', 'pass2player0Id', 'pass2player1Id',
'pass3player0Id', 'pass3player1Id', 'pass4player0Id',
'pass4player1Id')] %>% sapply(convert_ids, player_df = players)
```
Ok let's go over the code a bit here. The first part is a function I created
that gets passed a column and a dataframe. This dataframe is the `players` dataframe
we created earlier. So this function goes along the column we pass to it and matches
the Id to the Id in the `players` dataframe and then returns the value from
the `fullname` column in the `players` dataframe.
Once it does that for
every value in the column its returns those names and we store it in the same
column variable and then we'll overwrite the the columns from the `pbp`
dataframe with names instead of ids.
The next part of the code is us applying
that function to all the columns we need to in the `pbp` dataframe using
`sapply`. `sapply` is similar to a loop as it does a repeated action over
and over again given certain conditions, but behind the scenes things are quite
different. R is built around what's called vectorized operations because
R is slow when dealing with memory allocation and it is that reason that loops
run so slow in R. When you use the `apply` group functions or `plyr` functions
R automatically takes care of all those memory issues making things run faster
even though they actually use for loops inside their own source code.
But back to our `sapply` so all I'm doing is moving over all these columns and
looking up the player name for each player id and copying that to our new column.
This will allow us to break down our graphs to look at certain stats my player
name without having to consult the `players` dataframe anymore. So now that's
done lets get to graphing.
## Creating the Rink
<file_sep>library(tidyverse)
library(lubridate)
################################################################################
##This code written by <NAME> who can be found on twitter #####
##@iyer_prashanth and is a really good follow #####
################################################################################
source('~/graphautomation/RinkFunction.R')
rink <- fun.draw_rink() + coord_fixed()
#convert player ids to actual player names from the player dataframe
convert_ids <- function(column, player_df){
column <- player_df[match(column, player_df$playerId, nomatch = column),
c('fullName')]
}
file_name <- c('~/HockeyStuff/Tape2TapeData/Tape2Tape/11_10_plays.csv')
players_file_name <- c('~/HockeyStuff/Tape2TapeData/Tape2Tape/11_10_roster.csv')
pbp <- read_csv(file_name)
players <- read_csv(players_file_name)
#Fix game time and turn it into integer for seconds
pbp$periodTime <- as.character(pbp$periodTime)
pbp$periodTime <- substr(pbp$periodTime,1,5)
pbp$periodTime <- paste0('00:', pbp$periodTime)
pbp$periodTime <- hms(pbp$periodTime)
pbp$periodTime <- as.numeric(pbp$periodTime)
#convert periodTime to a cumsum of total seconds elapsed
pbp$periodTime <- ifelse(pbp$period == 2, pbp$periodTime + 1200, pbp$periodTime)
pbp$periodTime <- ifelse(pbp$period == 3, pbp$periodTime + 2400, pbp$periodTime)
pbp$periodTime <- ifelse(pbp$period == 4, pbp$periodTime + 3600, pbp$periodTime)
#converting playerids to playernames
pbp[4:15] <- pbp %>% select(awayPlayer0Id:homePlayer5Id) %>%
sapply(convert_ids, player_df = players)
pbp[,c('player0Id', 'player1Id', 'pass0player0Id', 'pass0player1Id',
'pass1player0Id', 'pass1player1Id', 'pass2player0Id', 'pass2player1Id',
'pass3player0Id', 'pass3player1Id',
'pass4player0Id', 'pass4player1Id')] <-
pbp[,c('player0Id', 'player1Id', 'pass0player0Id', 'pass0player1Id',
'pass1player1Id', 'pass1player1Id', 'pass2player0Id', 'pass2player1Id',
'pass3player0Id', 'pass3player1Id', 'pass4player0Id',
'pass4player1Id')] %>% sapply(convert_ids, player_df = players)
team_colors <- c('black', 'darkred', 'black', 'royalblue4', 'red3', 'firebrick1',
'black', 'navy', 'maroon', 'red', 'darkgreen', 'navyblue',
'orange', 'mediumblue', 'slategrey', 'limegreen', 'darkgreen',
'darkorange1', 'yellow2', 'mediumblue', 'steelblue4', 'red2',
'lightseagreen', 'darkorange1', 'dodgerblue4', 'gold', 'gold',
'dodgerblue3', 'navyblue', 'navyblue', 'red1')
names(team_colors) <- c('ANA', 'ARI','BOS', 'BUF', 'CGY', 'CAR', 'CHI', 'CBJ',
'COL', 'DET', 'DAL', 'FLA', 'EDM', 'MTL', 'L.A', 'N.J',
'MIN', 'NYI', 'NSH', 'NYR', 'STL', 'OTT', 'S.J', 'PHI',
'VAN', 'PIT', 'VGK', 'T.B', 'TOR', 'WPG', 'WSH')
pbp_graph <- subset(pbp, pbp$event %in% c('Shot'))
index <- c(1:nrow(pbp))
score <- c(0, 0)
names(score) <- c(unique(pbp$eventTeam)[1], unique(pbp$eventTeam)[2])
for (number in index){
pbp_graph <- pbp[number,]
if (pbp_graph$event == 'Goal') {
score[pbp_graph$eventTeam] <- score[pbp_graph$eventTeam] + 1
}
plot <-rink + geom_point(aes(x = x0, y = y0),
color = team_colors[pbp_graph$eventTeam],
data = pbp_graph,
size = 4) +
geom_segment(aes(x = x0, y = y0, xend = x1, yend = y1
), color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass0x1, y = pass0y1, xend = x0, yend = y0),
color = team_colors[pbp_graph$eventTeam], linetype = 2,
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass1x1, y = pass1y1, xend = pass0x0, yend = pass0y0),
color = team_colors[pbp_graph$eventTeam], linetype = 2,
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass1x0, y = pass1y0, xend = pass2x1, yend = pass2y1),
color = team_colors[pbp_graph$eventTeam], linetype = 2,
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass2x0, y = pass2y0, xend = pass3x1, yend = pass3y1),
color = team_colors[pbp_graph$eventTeam], linetype = 2,
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass3x0, y = pass3y0, xend = pass4x1, yend = pass4y1),
color = team_colors[pbp_graph$eventTeam], linetype = 2,
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass0x0, y = pass0y0, xend = pass0x1, yend = pass0y1),
color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass1x0, y = pass1y0, xend = pass1x1, yend = pass1y1),
color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass2x0, y = pass2y0, xend = pass2x1, yend = pass2y1),
color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass3x0, y = pass3y0, xend = pass3x1, yend = pass3y1),
color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
geom_segment(aes(x = pass4x0, y = pass4y0, xend = pass4x1, yend = pass4y1),
color = team_colors[pbp_graph$eventTeam],
arrow = arrow(length = unit(0.1,"cm")), data = pbp_graph) +
labs(title = paste0(unique(pbp$eventTeam)[1], ' ',
score[[unique(pbp$eventTeam)[1]]],' ',
unique(pbp$eventTeam)[2], ' ',
score[[unique(pbp$eventTeam)[2]]], ' ',
pbp_graph$periodTimeRemaining),
caption = paste0(pbp_graph$eventTeam, ' ',
pbp_graph$event, ' ',
ifelse(!is.na(pbp_graph$eventType),
pbp_graph$eventType, ''),
' ',
ifelse(!is.na(pbp_graph$eventResult),
pbp_graph$eventResult, '')))
ggsave(paste0('00', as.character(number), '.png'), plot = plot, height = 6,
width = 8)
}
| c5ce5d26cc9dd13a2ae4fbde6421072c60da406b | [
"R",
"RMarkdown"
] | 2 | RMarkdown | Schmoegurt/tape2tape | 45c0106f2749033e73fb10188e75edf825d309ec | bb71902b37e4b50784b5591907acfabe10b39200 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
if [ ${#} -lt 1 ]; then
echo usage: ./tip-tester.sh http://host:port
exit 1
fi
SERVER=${1}
if [ ${#} -e 2 ]; then
if [[ ${2} == *'distance'* ]]; then
ENDPOINT='/api/distance'
fi
if [[ ${2} == *'itinerary'* ]]; then
ENDPOINT='/api/itinerary'
fi
if [[ ${2} == *'find'* ]]; then
ENDPOINT='/api/find'
fi
cat $2 | python3 json_tool.py ${SERVER} ${ENDPOINT}
exit 0
fi
echo "testing ${SERVER}"
#rm -rf ./responses/*
echo "config"
python3 json_tool.py ${SERVER} /api/config > ./responses/config_response.json
diff ./expected/config_expect.json ./responses/config_response.json
for FILENAME in $(ls ./requests)
do
if [[ ${FILENAME} == *'distance'* ]]; then
ENDPOINT='/api/distance'
fi
if [[ ${FILENAME} == *'itinerary'* ]]; then
ENDPOINT='/api/itinerary'
fi
if [[ ${FILENAME} == *'find'* ]]; then
ENDPOINT='/api/find'
fi
echo ${FILENAME}
RESP_FILENAME="${FILENAME%.json}_response.json"
EXPECT_FILENAME="${FILENAME%.json}_expect.json"
cat ./requests/${FILENAME} \
| python3 json_tool.py ${SERVER} ${ENDPOINT} \
> ./responses/${RESP_FILENAME}
diff ./expected/${EXPECT_FILENAME} ./responses/${RESP_FILENAME}
done
<file_sep># tripco-tip-tester
usage: ./tip-tester.sh http://host:port
ex: ./tip-tester.sh http://localhost:8088
Some itinerary responses may be different depending on your nearest neighbor / two opt algorithms.
<file_sep>import json
import sys
import urllib
import urllib.request
URL = sys.argv[1]
ENDPOINT = sys.argv[2]
req = None
if ENDPOINT == "/api/config":
req = urllib.request.Request(url=URL+ENDPOINT, method="GET")
else:
req = urllib.request.Request(url=URL+ENDPOINT, data=sys.stdin.buffer.read(), method="POST")
req.add_header('Content-Type', 'application/json')
try:
resp = urllib.request.urlopen(req)
parsed = json.loads(resp.read().decode('utf8'))
print(json.dumps(parsed, indent=4, sort_keys=True))
except urllib.error.HTTPError as err:
print(err.code)
<file_sep>#!/usr/bin/env bash
cat ${3} | python3 json_tool.py ${1} ${2}
| 3958224c1b18b7c4b933a308be65ee7fddb4e467 | [
"Markdown",
"Python",
"Shell"
] | 4 | Shell | millardk/tripco-tip-tester | 8f76b7b7b3e4a83fd9a7a0d1b0fd3f36c82b04e1 | 2479c07e2a50f49ce0d4d1cbe3aeacf8c0edbdf5 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import asyncio
from pyppeteer import launch
import requests
from lxml import etree
import numpy as np
import config
from analyzer import StockAnalyzer
class StockAnalyzerA(StockAnalyzer):
def __init__(self, base_url, query, bonus_url, debt_url):
super(__class__, self).__init__(base_url, query, bonus_url, debt_url)
self.qualified_stocks = []
def extract_bonus(self, stock_code):
res = requests.get(self.bonus_url.format(stock_code), headers=config.headers)
root = etree.HTML(res.content)
years = root.xpath('//*[@id="bonus_table"]/tbody/tr[*]/td[1]/text()')
index = []
recent_ratio = []
for idx, val in enumerate(years):
if "年报" in val:
index.append(idx)
ratio = root.xpath('//*[@id="bonus_table"]/tbody/tr[*]/td[9]/text()')
for idx, val in enumerate(index):
if idx < 5:
recent_ratio.append(ratio[val])
return recent_ratio
async def extract_debts(self, stock_code):
browser = await launch({'headless': True, 'args': ['--disable-dev-shm-usage']})
page = await browser.newPage()
await page.goto(self.debt_url.format(stock_code), {'waitUntil': "networkidle2"}, timeout=60000)
await page.waitForSelector('#cwzbTable')
await page.click('#cwzbTable > div.scroll_container > ul > li:nth-child(2) > a')
all_targets = await page.xpath('//*[@id="cwzbTable"]/div[1]/div[1]/div[4]/table[2]/tbody/tr[11]/td[position()<6]')
for item in all_targets:
self.debt_ratio.append(await (await item.getProperty('textContent')).jsonValue())
await browser.close()
def judgement(self):
# 添加深证市盈率判定
for (k,v) in self.stock_dict.items():
v_list = eval(v)
roe, cashflow_profit, gross_profit = \
np.array(v_list[:5]).astype(np.float), \
np.array(v_list[-5:]).astype(np.float), \
np.array(v_list[5:10]).astype(np.float)
if np.mean(roe) < 20 or roe[0] < 20 or np.mean(cashflow_profit) < 1 or np.mean(gross_profit) < 40 or gross_profit[0] < 40:
continue
bonus_list = [_.strip('%') for _ in self.extract_bonus(k.split()[1])]
if '--' in bonus_list:
continue
print('{}\nROE: {}\ncashflow_profit: {}\ngross_profit: {}'.format(k, roe, cashflow_profit, gross_profit).encode("utf-8"))
bonus_data = np.array(bonus_list).astype(np.float)
print('bonus_ratio: ', bonus_data)
if np.mean(bonus_data) < 25 and (bonus_data > 25).sum() != bonus_data.size:
continue
# TODO: 派息年数不足五年?
loop = asyncio.get_event_loop()
loop.run_until_complete(self.extract_debts(k.split()[-1]))
self.debt_ratio = [_.strip('%') for _ in self.debt_ratio]
debt_data = np.array(self.debt_ratio).astype(np.float)
if np.mean(debt_data) < 60 and debt_data[0] < 60:
self.qualified_stocks.append(k)
# TODO: 增加延时
print('debt_ratio: ', debt_data, '\n')
self.debt_ratio.clear()
class StockAnalyzerHK(StockAnalyzer):
def __init__(self, base_url, query, bonus_url, debt_url):
super(__class__, self).__init__(base_url, query, bonus_url, debt_url)
self.bonus_list = []
self.qualified_stocks = []
async def extract_bonus(self, stock_code):
# exepath = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
details = []
# TODO: 派息比率过高的问题?
# TODO: 只在开头打开一次browser 异步效果?
# browser = await launch({'executablePath': exepath, 'headless': True})
browser = await launch({'headless': True, 'args': ['--disable-dev-shm-usage']})
page = await browser.newPage()
try:
await page.goto(self.bonus_url.format(stock_code), {'waitUntil': "networkidle2"})
# await page.waitForSelector('#highcharts-0')
# await page.waitFor(10000)
except Exception as e:
print('extract_bonus_HK error: ', e)
finally:
for i in range(6):
await page.hover('#highcharts-0 > svg > g.highcharts-series-group > g:nth-child(3) > rect:nth-child({})'.format(i+1))
# 显示框有3~4行,选取倒数第2行
rows = await page.xpath('//*[@id="highcharts-0"]/div[1]/span/span[@*]')
details.append(rows[-2])
for detail in details:
self.bonus_list.append((await (await detail.getProperty('textContent')).jsonValue()).split()[2])
# 删除最后一列空白条形图中的数据
self.bonus_list = list(filter(lambda x: '%' in x, self.bonus_list))
self.bonus_list = [_.strip('%') for _ in self.bonus_list]
self.bonus_list.reverse()
await browser.close()
def combination_filter(self):
pass
def judgement(self):
# TODO: 派息比率低的好公司? choice 派息比率超过100?
for (k,v) in self.stock_dict.items():
v_list = eval(v)
roe, cashflow_profit, gross_profit, debt_ratio = \
np.array(v_list[:5]).astype(np.float), \
np.array(v_list[-6:-11:-1]).astype(np.float), \
np.array(v_list[5:10]).astype(np.float), \
np.array(v_list[-5:]).astype(np.float)
if np.mean(roe) < 20 or roe[0] < 20 or np.mean(cashflow_profit) < 1 or np.mean(gross_profit) < 40 or \
gross_profit[0] < 40 or np.mean(debt_ratio) >= 60 or debt_ratio[0] >= 60:
continue
loop = asyncio.get_event_loop()
loop.run_until_complete(self.extract_bonus(k.split()[-1]))
# TODO: 需要针对bonus_list个数大于或小于5做处理
bonus_data = np.array(self.bonus_list[:5]).astype(np.float)
if np.mean(bonus_data) >= 30 and (bonus_data >= 30).sum() == bonus_data.size:
self.qualified_stocks.append(k)
self.bonus_list.clear()
print('{}\nROE: {}\ncashflow_profit: {}\ngross_profit: {}\ndebt_ratio: {}\nbonus_ratio: {}\n'.format(k, roe, cashflow_profit, gross_profit, debt_ratio, bonus_data).encode("utf-8"))
class StockAnalyzerUS(StockAnalyzer):
def __init__(self, base_url, query, bonus_url, debt_url):
super(__class__, self).__init__(base_url, query, bonus_url, debt_url)
self.bonus_info = {}
self.bonus_list = []
# 适用于所有market派息比率计算
async def extract_bonus(self, stock_tag):
browser = await launch({'headless': True, 'args': ['--disable-dev-shm-usage']})
page = await browser.newPage()
try:
await page.goto(self.bonus_url.format(config.bonus_general_query.format(config.year-5, config.year-1, stock_tag)), timeout=60000)
await page.waitForNavigation()
except Exception as e:
print('extract_bonus_US error: ', e)
finally:
all_elements = []
get_profit = False
profit = []
all_targets = await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[2]/div/table/tbody/tr[*]/td[4]/div/a')
for i in range(len(all_targets)):
all_elements.append(await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[1]/div/div/div[2]/table/tbody/tr[{}]/td[position()>2]'.format(i+1)))
stock_code = await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[2]/div/table/tbody/tr[{}]/td[3]/div'.format(i+1))
# print(await (await all_targets[i].getProperty('textContent')).jsonValue(), ":", end='')
elements_list = [(await (await item.getProperty('textContent')).jsonValue()).strip() for item in all_elements[i]]
if not get_profit:
profit = elements_list[1:6]
get_profit = True
while '' in elements_list: elements_list.remove('')
self.bonus_info[str(i) + stock_tag + ' ' + await (await stock_code[0].getProperty('textContent')).jsonValue()] = str(elements_list)
idx = 0
for value in self.bonus_info.values():
dividend = float(eval(value)[0].strip('万亿').replace(',', '')) / 10000 if '万' in eval(value)[0] else float(eval(value)[0].strip('万亿').replace(',', ''))
profit_val = float(profit[idx].strip('万亿').replace(',', '')) / 10000 if '万' in profit[idx] else float(profit[idx].strip('万亿').replace(',', ''))
try:
self.bonus_list.append(dividend / profit_val)
except Exception as e:
pass
idx += 1
self.bonus_info.clear()
await browser.close()
def judgement(self):
# TODO: 派息比率低的好公司? choice 派息比率超过100?
for (k,v) in self.stock_dict.items():
v_list = eval(v)
# TODO: 最后一列有市值会影响结果
roe, cashflow_profit, gross_profit, debt_ratio = \
np.array(v_list[:5]).astype(np.float), \
np.array(v_list[-7:-12:-1]).astype(np.float), \
np.array(v_list[5:10]).astype(np.float), \
np.array(v_list[-6:-1:1]).astype(np.float)
# np.array(v_list[-5:]).astype(np.float)
# np.array(v_list[-6:-1:1]).astype(np.float)
if np.mean(roe) < 20 or roe[0] < 20 or np.mean(cashflow_profit) < 1:
continue
loop = asyncio.get_event_loop()
loop.run_until_complete(self.extract_bonus(k.split()[-1]))
bonus_data = np.array(self.bonus_list).astype(np.float)
if np.mean(bonus_data) >= 0.2 and (bonus_data >= 0.2).sum() == bonus_data.size:
self.qualified_stocks.append(k)
self.bonus_list.clear()
print('{}\nROE: {}\ncashflow_profit: {}\ngross_profit: {}\ndebt_ratio: {}\nbonus_ratio: {}\n'.format(k, roe, cashflow_profit, gross_profit, debt_ratio, bonus_data).encode("utf-8"))
<file_sep>[](https://ci.appveyor.com/project/recursively/quantitative-trading-pub)
[](https://codecov.io/gh/recursively/quantitative_trading_pub)<file_sep># -*- coding: utf-8 -*-
import asyncio
from lxml import etree
import requests
import config
from futu import *
from pyppeteer import launch
import time
class Quote():
def __init__(self):
self.quote = OpenQuoteContext(host='127.0.0.1', port=11111)
def __enter__(self):
return self.quote
def __exit__(self, exc_type, exc_val, exc_tb):
self.quote.close()
class StockAnalyzer():
def __init__(self, base_url, query, bonus_url, debt_url):
self.base_url = base_url
self.query = query
self.bonus_url = bonus_url
self.debt_url = debt_url
self.stock_dict = {}
self.debt_ratio = []
self.qualified_stocks = []
self.gprice = 0
async def iwc_filter(self):
browser = await launch({'headless': True, 'args': ['--disable-dev-shm-usage']})
page = await browser.newPage()
await page.goto(self.base_url.format(self.query), timeout=60000)
await page.waitForNavigation(timeout=60000)
page_count = 1
while page_count < 3:
page_count += 1
all_targets = await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[2]/div/table/tbody/tr[*]/td[4]/div/a')
for i in range(len(all_targets)):
all_elements = (await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[1]/div/div/div[2]/table/tbody/tr[{}]/td[position()>2]'.format(i+1)))
stock_code = await page.xpath('//*[@id="tableWrap"]/div[2]/div/div[2]/div/table/tbody/tr[{}]/td[3]/div'.format(i+1))
# print(await (await all_targets[i].getProperty('textContent')).jsonValue(), ":", end='')
elements_list = [(await (await item.getProperty('textContent')).jsonValue()).strip() for item in all_elements]
while '' in elements_list: elements_list.remove('')
self.stock_dict[await (await all_targets[i].getProperty('textContent')).jsonValue() + ' ' + await (await stock_code[0].getProperty('textContent')).jsonValue()] = str(elements_list)
try:
await page.click('#next')
await page.waitFor(1000)
except Exception as e:
pass
await browser.close()
@staticmethod
def pe_fetch():
res = requests.get(config.pe_url, headers=config.headers)
root = etree.HTML(res.content)
pe_list = root.xpath('/html/body/div[1]/div[2]/div/div[2]/div[1]/div[3]/div[1]/div/div/div[2]/div/div[2]/div[1]/text()')
pe = pe_list[0].split(':')[-1]
return pe
def judgement(self):
raise Exception("judgment not implemented.")
@staticmethod
def treasury_fetch(url, path):
res = requests.get(url, headers=config.headers)
root = etree.HTML(res.content)
treasury_yield = float(root.xpath(path)[0])
return treasury_yield
@staticmethod
def get_stock_info(quote, market, stock_code):
if market == 'SH':
return quote.get_market_snapshot(['SH.{}'.format(stock_code)])[1][
['code', 'last_price', 'pe_ttm_ratio', 'dividend_ttm']].values[0]
if market == 'SZ':
return quote.get_market_snapshot(['SZ.{}'.format(stock_code)])[1][
['code', 'last_price', 'pe_ttm_ratio', 'dividend_ttm']].values[0]
if market == 'HK':
return quote.get_market_snapshot(['HK.{}'.format(stock_code)])[1][
['code', 'last_price', 'pe_ttm_ratio', 'dividend_ttm']].values[0]
def price_calc(self, stocks):
treasury_yield = 0
dashboard = ''
pe = StockAnalyzer.pe_fetch()
if type(self).__name__ == 'StockAnalyzerA':
treasury_yield = StockAnalyzer.treasury_fetch(config.cn_treasury, config.treasury_path)
dashboard = 'Treasury chosen: {:.3f}\nShenzhen Stock Exchange PE ratio: {}'.format(treasury_yield, pe)
if type(self).__name__ == 'StockAnalyzerHK':
cn_treasury = StockAnalyzer.treasury_fetch(config.cn_treasury, config.treasury_path)
us_treasury = StockAnalyzer.treasury_fetch(config.us_treasury, config.treasury_path)
treasury_yield = max(cn_treasury, us_treasury)
dashboard = 'Treasury chosen: {:.3f} | cn_treasury: {:.3f}, us_treasury: {:.3f}'.format(treasury_yield, cn_treasury, us_treasury)
info_list = []
# quote_ctx.get_market_snapshot(['SH.600519', 'SH.600660'])[1][['code', 'last_price', 'pe_ttm_ratio', 'dividend_ttm']].ix[[0]].values[0]
request_count = 0
with Quote() as quote_ctx:
for stock in stocks:
code = stock.split()[-1]
if type(self).__name__ == 'StockAnalyzerA':
try:
if request_count > 9: # 30s内请求10次
print('Delaying 30 seconds to avoid being banned...')
time.sleep(30)
request_count = 0
request_count += 1
info_list = StockAnalyzer.get_stock_info(quote_ctx, 'SH', code)
except Exception as e:
try:
if request_count > 9:
print('Delaying 30 seconds to avoid being banned...')
time.sleep(30)
request_count = 0
request_count += 1
info_list = StockAnalyzer.get_stock_info(quote_ctx, 'SZ', code)
except Exception as e:
pass
elif type(self).__name__ == 'StockAnalyzerHK':
if request_count > 9: # 30s内请求10次
print('Delaying 30 seconds to avoid being banned...')
time.sleep(30)
request_count = 0
request_count += 1
info_list = StockAnalyzer.get_stock_info(quote_ctx, 'HK', code)
self.gprice = min(15 * info_list[1]/info_list[2], 100 * info_list[3]/treasury_yield)
if info_list[1] < self.gprice:
print('{:<15s} Stock code: {} Last price: {:8.2f} Good price: {:8.2f} √'.format(stock, info_list[0], info_list[1], self.gprice))
else:
print('{:<15s} Stock code: {} Last price: {:8.2f} Good price: {:8.2f}'.format(stock, info_list[0], info_list[1], self.gprice))
print(dashboard)
# def start(self):
# loop = asyncio.get_event_loop()
# loop.run_until_complete(self.iwc_filter())
# self.judgement()
# print('Qualified stocks: ')
# for i in self.qualified_stocks:
# print(i)
# self.price_calc(self.qualified_stocks)
<file_sep>import unittest
from unittest.mock import MagicMock, patch
from analyzer import StockAnalyzer
from stock_filter import StockAnalyzerA, StockAnalyzerHK, StockAnalyzerUS
import config
import asyncio
import numpy as np
import time
class StockAnalyzerTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(__class__, self).__init__(*args, **kwargs)
self.stock_code_cn = '600519'
self.stock_code_hk = '00799'
self.stock_code_us = 'DIS'
self.Analyzer_cn = StockAnalyzerA(config.base_url_A, config.query_A, config.bonus_url_A, config.debt_url_A)
self.Analyzer_hk = StockAnalyzerHK(config.base_url_HK, config.query_HK, config.bonus_url_HK, None)
self.Analyzer_us = StockAnalyzerUS(config.base_url_US, config.query_US, config.base_url_US, None)
def test_main_filter(self):
# trial_count = 0
# trial_confirm = True
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(self.Analyzer_cn.iwc_filter())
except Exception as e:
print('test_main_filter error: ', e)
# except Exception as e:
# while trial_count < 3 and trial_confirm is True:
# try:
# loop = asyncio.get_event_loop()
# loop.run_until_complete(self.Analyzer_cn.iwc_filter())
# trial_confirm = False
# except Exception as e:
# trial_count += 1
# print('test_main_filter error: ', e)
self.assertEqual(type(int(self.Analyzer_cn.stock_dict.popitem()[0].split()[-1])), int)
def test_bonus_fetch_cn(self):
bonus_list = self.Analyzer_cn.extract_bonus(self.stock_code_cn)
self.assertEqual(len(bonus_list), 5)
def test_debts_fetch_cn(self):
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(self.Analyzer_cn.extract_debts(self.stock_code_cn))
except Exception as e:
print('test_debts_fetch_cn error: ', e)
self.assertEqual(len(self.Analyzer_cn.debt_ratio), 5)
def test_bonus_fetch_hk(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.Analyzer_hk.extract_bonus(self.stock_code_hk))
bonus_data = np.array(self.Analyzer_hk.bonus_list[:5]).astype(np.float)
self.assertTrue(np.mean(bonus_data) >= 10)
def test_bonut_fetch_us(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.Analyzer_us.extract_bonus(self.stock_code_us))
bonus_data = np.array(self.Analyzer_us.bonus_list).astype(np.float)
self.assertTrue(np.mean(bonus_data) >= 0.2)
def test_treasury_fetch(self):
cn_treasury = StockAnalyzer.treasury_fetch(config.cn_treasury, config.treasury_path)
us_treasury = StockAnalyzer.treasury_fetch(config.us_treasury, config.treasury_path)
self.assertTrue(1 < max(cn_treasury, us_treasury) < 5)
async def side_effect(self, stock_code):
if stock_code == self.stock_code_cn:
self.Analyzer_cn.debt_ratio = config.debt_ratio_sample_cn
if stock_code == self.stock_code_hk:
self.Analyzer_hk.bonus_list = config.bonus_list_sample_hk
if stock_code == self.stock_code_us:
self.Analyzer_us.bonus_list = config.bonus_list_sample_us
def test_judgement_cn(self):
StockAnalyzerA.extract_debts = MagicMock(side_effect=self.side_effect)
self.Analyzer_cn.stock_dict = config.origin_sample_cn
self.Analyzer_cn.judgement()
self.assertEqual(self.Analyzer_cn.qualified_stocks[0].split()[-1], self.stock_code_cn)
def test_judgement_hk(self):
StockAnalyzerHK.extract_bonus = MagicMock(side_effect=self.side_effect)
self.Analyzer_hk.stock_dict = config.origin_sample_hk
self.Analyzer_hk.judgement()
self.assertEqual(self.Analyzer_hk.qualified_stocks[0].split()[-1], self.stock_code_hk)
def test_judgement_us(self):
StockAnalyzerUS.extract_bonus = MagicMock(side_effect=self.side_effect)
self.Analyzer_us.stock_dict = config.origin_sample_us
self.Analyzer_us.judgement()
self.assertEqual(self.Analyzer_us.qualified_stocks[0].split()[-1], self.stock_code_us)
@patch('analyzer.Quote')
def test_price_calculation(self, mock_tmp):
mock_tmp.return_value.__enter__.return_value.name = 'entering'
call_count = 0
def side_effect(quote, market, stock_code):
if market == 'SZ':
print('dealing with SZ market')
nonlocal call_count
if call_count == 5:
call_count += 1
raise Exception('Intentionally raise an Exception to simulate the different market.')
call_count += 1
info_list = ['SH.600519', 962.03, 30.679, 14.539]
return info_list
StockAnalyzer.get_stock_info = MagicMock(side_effect=side_effect)
start = time.perf_counter()
self.Analyzer_cn.price_calc(['stock 000000'] * 15)
self.Analyzer_hk.price_calc(['stock 000000'] * 15)
stop = time.perf_counter()
self.assertEqual(int(self.Analyzer_cn.gprice), 470)
self.assertEqual(int(self.Analyzer_hk.gprice), 470)
self.assertTrue(stop - start >= 59)
def test_pe_fetch(self):
pe = StockAnalyzer.pe_fetch()
self.assertTrue(float(pe) > 0)
if __name__ == '__main__':
unittest.main()
<file_sep>requests
pyppeteer
lxml
numpy
futu-api
coverage<file_sep># -*- coding: utf-8 -*-
import datetime
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
'Upgrade-Insecure-Requests':'1',
'Proxy-Connection':'keep-alive',
'Cache-Control':'max-age=0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Content-Type':'application/x-www-form-urlencoded',
'cookie':'ASPSESSIONIDSSSDDTTA=KABHCBMAFGPOGLLDJAJFOHIL',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6'}
query_list = []
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4ROE%E5%A4%A7%E4%BA%8E15%25')
query_list.append(r'%E6%AF%9B%E5%88%A9%E7%8E%87%E5%A4%A7%E4%BA%8E30%25')
query_list.append(r'%E8%B5%84%E4%BA%A7%E8%B4%9F%E5%80%BA%E7%8E%87%E5%B0%8F%E4%BA%8E60%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E7%BB%8F%E8%90%A5%E6%B4%BB%E5%8A%A8%E7%8E%B0%E9%87%91%E6%B5%81%E9%87%8F%E5%87%80%E9%A2%9D%E9%99%A4%E4%BB%A5%E5%87%80%E5%88%A9%E6%B6%A6%E7%9A%84%E6%AF%94%E7%8E%87%E5%A4%A7%E4%BA%8E80%25')
query_A = r'%EF%BC%8C'.join(query_list)
query_list.clear()
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4ROE%E5%A4%A7%E4%BA%8E15%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E6%AF%9B%E5%88%A9%E7%8E%87%E5%A4%A7%E4%BA%8E30%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E7%BB%8F%E8%90%A5%E6%B4%BB%E5%8A%A8%E5%87%80%E7%8E%B0%E9%87%91%E6%B5%81%E9%87%8F%E9%99%A4%E4%BB%A5%E5%87%80%E5%88%A9%E6%B6%A6%E5%A4%A7%E4%BA%8E80%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E8%B5%84%E4%BA%A7%E8%B4%9F%E5%80%BA%E7%8E%87%E5%B0%8F%E4%BA%8E65%25')
query_HK = r'%EF%BC%8C'.join(query_list)
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4ROE%E5%A4%A7%E4%BA%8E15%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E6%AF%9B%E5%88%A9%E7%8E%87%E5%A4%A7%E4%BA%8E40%25')
query_list.append(r'%E8%BF%9E%E7%BB%AD5%E5%B9%B4%E7%BB%8F%E8%90%A5%E6%B4%BB%E5%8A%A8%E5%87%80%E7%8E%B0%E9%87%91%E6%B5%81%E9%87%8F%E9%99%A4%E4%BB%A5%E5%87%80%E5%88%A9%E6%B6%A6%E5%A4%A7%E4%BA%8E80%25')
query_list.append(r'%E8%B5%84%E4%BA%A7%E8%B4%9F%E5%80%BA%E7%8E%87%E5%B0%8F%E4%BA%8E60%25')
query_list.append(r'%E5%B8%82%E5%80%BC%E5%A4%A7%E4%BA%8E50%E4%BA%BF')
query_US = r'%EF%BC%8C'.join(query_list)
base_url_A = 'http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=index_rewrite&selfsectsn=&querytype=stock&searchfilter=&tid=stockpick&w={}'
bonus_url_A = 'http://basic.10jqka.com.cn/{}/bonus.html'
debt_url_A = 'http://basic.10jqka.com.cn/{}/finance.html'
base_url_HK = 'http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=result_channel&selfsectsn=&querytype=hkstock&searchfilter=&tid=stockpick&w={}'
bonus_url_HK = 'http://www.aastocks.com/sc/stocks/analysis/dividend.aspx?symbol={}'
cn_treasury = 'https://cn.investing.com/rates-bonds/china-10-year-bond-yield'
treasury_path = '//*[@id="last_last"]/text()'
us_treasury = 'https://cn.investing.com/rates-bonds/u.s.-10-year-bond-yield'
base_url_US = 'http://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=result_rewrite&selfsectsn=&querytype=usstock&searchfilter=&tid=stockpick&w={}'
year = datetime.datetime.now().year
bonus_general_query = '{}年到{}年{}年度分红,净利润'
origin_sample_cn = {"贵州茅台 600519": "['34.46', '32.95', '24.44', '26.23', '31.96', '91.14', '89.80', '91.23', '92.23', \
'92.59', '26.55', '28.67', '32.79', '23.25', '16.03', '413.85亿', '221.53亿', '374.51亿', '174.36亿', \
'126.33亿', '352.04亿', '270.79亿', '167.18亿', '155.03亿', '153.50亿', '1.18', '0.82', '2.24', '1.12', '0.82']"}
debt_ratio_sample_cn = ['26.55%', '28.67%', '32.79%', '23.25%', '16.03%']
origin_sample_hk = {"IGG 00799": "['66.94', '68.08', '37.06', '21.78', '35.54', '69.92', '68.27', '67.96', '69.39', '71.25', \
'18.74亿', '13.46亿', '5.77亿', '4.15亿', '5.49亿', '14.82亿', '12.19亿', '5.63亿', '3.22亿', '5.15亿', \
'1.26', '1.10', '1.02', '1.29', '1.07', '29.55', '28.46', '19.63', '13.12', '13.92']"}
bonus_list_sample_hk = ['30', '54', '42', '90', '60']
origin_sample_us = {"迪士尼 DIS": "['27.97', '21.23', '21.39', '18.73', '16.60', '44.94', '45.04', '46.09', '45.94', '45.88', \
'142.95亿', '123.43亿', '131.36亿', '113.85亿', '97.80亿', '125.98亿', '89.80亿', '93.91亿', '83.82亿', \
'75.01亿', '1.13', '1.37', '1.40', '1.36', '1.30', '45.28', '51.82', '48.58', '44.82', '42.74', '2,495.27亿']"}
bonus_list_sample_us = [0.20400063502143195, 0.2802895322939867, 0.2606751144713023, 0.26604628966833693, 0.2599653379549393]
pe_url = 'https://legulegu.com/stockdata/shenzhenPE'
| bfc1cafde5a65174e9accfa3fe24b3d2e685ef76 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | recursively/quantitative_trading_pub | d4cf0dd8eebd78f3541577ed3f38c6574b4c5427 | f6b64f29f31bdc790157b15268788d428081c4fa |
refs/heads/master | <repo_name>Levhav/flarum-ext-mailer<file_sep>/README.md
# post mailer
<file_sep>/bootstrap.php
<?php
use Flarum\Core;
use Flarum\Core\Repository\UserRepository;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\Event\DiscussionWasStarted;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Message;
return function (Dispatcher $events, Mailer $mailer) {
$events->listen(DiscussionWasStarted::class, function (DiscussionWasStarted $event) use ($mailer)
{
$discussion = $event->discussion;
$content = "There's a new discussion on http://community.comet-server.com \n\n\n" .
$discussion->startPost->content;
$mailer->raw($content, function (Message $message) use ($discussion) {
$message->to('<EMAIL>');
$message->subject("[Support] " . $discussion->title);
}
);
});
}; | 315fa0432d34d26cb2819cf0edf5c418be2d8130 | [
"Markdown",
"PHP"
] | 2 | Markdown | Levhav/flarum-ext-mailer | d6fb9bd65b8558d9abc9985c457ac467d0dc920c | 00f50ec21d7f75b03f3d1d3e2e7790fdf5e1777b |
refs/heads/master | <file_sep>#!/bin/bash
# To make use of this script, you will need ImageMagick
mkdir -p thumbs
for i in *.{jpg,JPG}; do
if [ "$i" -nt "thumbs/$i" ]; then
convert "$i" -thumbnail 200 "thumbs/$i";
fi
done;
for i in *.{mp4,MP4}; do
noextension="${i%.*}"
if [ "$i" -nt "thumbs/$noextension.jpg" ]; then
convert $i[10] "thumbs/$noextension.jpg";
fi
done;
<file_sep>#!/bin/bash
SVRROOT=${PWD#/usr/share/www}
echo "<!-- Hidden video div -->"
for filename in *.{mp4,MP4}; do
noextension="${filename%.*}"
echo "
<div style=\"display:none;\" id=\"$noextension\">
<video class=\"lg-video-object lg-html5\" controls preload=\"none\">
<source src=\"$SVRROOT/$filename\" type=\"video/mp4\">
Your browser does not support HTML5 video.
</video>
</div>"
done
echo "<div class=\"row\">"
echo " <div class=\"gallery-wrapper\">"
echo " <ul id=\"lightgallery\" class=\"list-unstyled row\">"
for filename in *.{jpg,JPG}; do
echo "
<li class=\"col-xs-6 col-sm-4 col-md-3 li-gallery\" data-responsive=\"$SVRROOT/$filename 800\" data-src=\"$SVRROOT/$filename\" data-sub-html=\"\">
<a href=\"\">
<img class=\"img-gallery img-responsive\" src=\"$SVRROOT/thumbs/$filename\">
</a>
</li>"
done
for filename in *.{mp4,MP4}; do
noextension="${filename%.*}"
echo "
<li class=\"col-xs-6 col-sm-4 col-md-3 li-gallery\" data-poster=\"$SVRROOT/thumbs/$noextension.jpg\" data-sub-html=\"\" data-html=\"#$noextension\" >
<a href=\"\">
<img class=\"img-gallery img-responsive\" src=\"$SVRROOT/thumbs/$noextension.jpg\" />
</a>
</li>"
done
echo " </ul>"
echo " </div>"
echo "</div>"
<file_sep># Burgers in Space
Website
## Authors
- <NAME>
- <NAME>
## Credits
The website Burgers in Space was created using the Clean Blog template.
You can find links to the creators below:
Start Bootstrap was created by and is maintained by **[David Miller](http://davidmiller.io/)**, Owner of [Blackrock Digital](http://blackrockdigital.io/).
Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [<NAME>](https://twitter.com/mdo) and [<NAME>](https://twitter.com/fat).
For displaying pictures and videos [LightGallery](https://github.com/sachinchoolur/lightGallery/) is used.
| a47e92a3d012016a8baef4fb3810f8805fc83851 | [
"Markdown",
"Shell"
] | 3 | Shell | vdutor/burgers-in-space | 280d76ebd2aa49f07e1ebfbc54301fbcb9f7fc98 | 34f5357fb492adb9effc1804679026631458d092 |
refs/heads/master | <repo_name>soloworldsolo/gcpdeployment<file_sep>/src/main/resources/application.properties
server.port =9090
management.endpoints.web.exposure.include=*
<file_sep>/src/main/java/com/soloworld/poc/nonnullpoc/GcpDeployment.java
package com.soloworld.poc.nonnullpoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GcpDeployment {
public static void main(String[] args) {
SpringApplication.run(GcpDeployment.class, args);
}
}
| 79361f88ac5cfd12e07f6f405f0fc01c9270a32a | [
"Java",
"INI"
] | 2 | INI | soloworldsolo/gcpdeployment | 4d8f6ae0a3c378b67d687fe581f937b389abbc5b | 0d1c0314185c0906dc13cc81a4eae2f82c34608b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class WebForm4 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
LinkButtonResim.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click(); return false;");
try
{
if (IsPostBack != true)
{
int id = Convert.ToInt32(Session["ID"].ToString());
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.resim != null)
{
string strBase64 = Convert.ToBase64String(kisi.resim);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
TextBoxHakkimda.Text = kisi.hakkimda;
TextBoxFace.Text = kisi.facebookURL;
TextBoxMail.Text = kisi.gosterilenMail;
TextBoxTwiter.Text = kisi.twitterURL;
DateTime dt = kisi.dTarihi.Value;
TextBoxDogumTarihi.Text = dt.Month+"/"+dt.Day+"/"+dt.Year;
TextBoxis.Text = kisi.isBilgisi;
DropDownListCinsiyet.Text = kisi.cinsiyet;
var sehir = db.Sehirs.Where(k => k.sehirID == kisi.sehirID).FirstOrDefault();
DropDownListIller.Text = sehir.sehirAd.ToString();
// eğitim doldurma
var durum = db.OkunanBolums.Where(k => k.kullaniciID == id).FirstOrDefault();
if (durum != null)
{
DateTime cikisT = durum.cikisTarihi.Value;
DateTime girisT = durum.girisTarihi.Value;
var okulbilgisi = db.ViewOkuls.Where(k => k.okunanBolumID == durum.okunanBolumID).FirstOrDefault();
DropDownListEgitimSehir.SelectedItem.Text = okulbilgisi.sehirAd;
var unibilgisi = db.Universites.Where(u => u.sehirID == okulbilgisi.sehirID).ToList();
var fakultebilgisi = db.OkulFakultes.Where(f => f.uniID == okulbilgisi.uniID).ToList();
var bolumbilgisi = db.Bolums.Where(b => b.okulID == okulbilgisi.okulID).ToList();
DropDownListEgitimUni.DataSource = unibilgisi;
DropDownListEgitimUni.DataTextField = "uniAd";
DropDownListEgitimUni.DataValueField = "uniID";
DropDownListEgitimUni.DataBind();
DropDownListEgitimUni.SelectedItem.Text = okulbilgisi.uniAd;
DropDownListEgitimFakulte.DataSource = fakultebilgisi;
DropDownListEgitimFakulte.DataTextField = "okulAd";
DropDownListEgitimFakulte.DataValueField = "okulID";
DropDownListEgitimFakulte.DataBind();
DropDownListEgitimFakulte.SelectedItem.Text = okulbilgisi.okulAd;
DropDownListBolum.DataSource = bolumbilgisi;
DropDownListBolum.DataTextField = "bolumAd";
DropDownListBolum.DataValueField = "bolumID";
DropDownListBolum.DataBind();
DropDownListBolum.SelectedItem.Text = okulbilgisi.bolumAd;
TextBoxGirisTarihi.Text = girisT.Month + "/" + girisT.Day + "/" + girisT.Year;
TextBoxCikisTarihi.Text = cikisT.Month + "/" + cikisT.Day + "/" + cikisT.Year;
}
else
{
DropDownListEgitimSehir.SelectedItem.Text = null;
}
//İs bilgilerini doldurma
var isbilgisi=db.KullaniciIsGecmisis.Where(i=>i.kullaniciID==id).FirstOrDefault();
if (isbilgisi!=null)
{
DateTime iscikisT = isbilgisi.isCikisTarihi.Value;
DateTime isgirisT = isbilgisi.isGirisTarihi.Value;
var isbigi = db.ViewisBilgisis.Where(k => k.isID == isbilgisi.isID).FirstOrDefault();
DropDownSirketSehir.Text = isbigi.sehirAd;
var sirketAd = db.Isyeris.Where(u => u.IsyeriID == isbilgisi.IsyeriID).ToList();
var departman = db.Departmen.Where(u => u.IsyeriID == isbigi.IsyeriID).ToList();
DropDownSirket.DataSource = sirketAd;
DropDownSirket.DataTextField = "isyeriAd";
DropDownSirket.DataValueField = "isyeriID";
DropDownSirket.DataBind();
DropDownSirket.SelectedItem.Text = isbigi.IsyeriAd;
DropDownDepartman.DataSource = departman;
DropDownDepartman.DataTextField = "departmanAd";
DropDownDepartman.DataValueField = "departmanID";
DropDownDepartman.DataBind();
DropDownDepartman.SelectedItem.Text = isbigi.departmanAd;
TextBoxPozisyon.Text = isbigi.pozisyon;
TextBoxisBaslangicTarihi.Text = isgirisT.Month + "/" + isgirisT.Day + "/" + isgirisT.Year;
TextBoxisBitisTarihi.Text = iscikisT.Month + "/" + iscikisT.Day + "/" + iscikisT.Year;
}
}
}
catch (Exception)
{
Response.Redirect("login.aspx");
}
}
protected void LinkBtnArkadasEkle_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["ID"].ToString());
//iS BİLGİLERİNİ kAYDETME
var isbilgisi = db.KullaniciIsGecmisis.Where(i => i.kullaniciID == id).FirstOrDefault();
if (isbilgisi==null)
{
try
{
Model.KullaniciIsGecmisi isgecmis = new Model.KullaniciIsGecmisi();
isgecmis.kullaniciID = id;
isgecmis.pozisyon = TextBoxPozisyon.Text;
isgecmis.IsyeriID = Convert.ToInt32(DropDownSirket.SelectedValue);
string[] iscikisTarihi = TextBoxisBitisTarihi.Text.Replace(".", "/").Split('/');
string[] isgirisTarihi = TextBoxisBaslangicTarihi.Text.Replace(".", "/").Split('/');
isgecmis.isCikisTarihi = new DateTime(Convert.ToInt32(iscikisTarihi[2]), Convert.ToInt32(iscikisTarihi[0]), Convert.ToInt32(iscikisTarihi[1]));
isgecmis.isGirisTarihi = new DateTime(Convert.ToInt32(isgirisTarihi[2]), Convert.ToInt32(isgirisTarihi[0]), Convert.ToInt32(isgirisTarihi[1]));
isgecmis.departmanID = Convert.ToInt32(DropDownDepartman.SelectedValue);
db.KullaniciIsGecmisis.Add(isgecmis);
}
catch (Exception)
{
}
}
else
{
try
{
isbilgisi.pozisyon = TextBoxPozisyon.Text;
isbilgisi.IsyeriID = Convert.ToInt32(DropDownSirket.SelectedValue);
string[] iscikisTarihi = TextBoxisBitisTarihi.Text.Replace(".", "/").Split('/');
string[] isgirisTarihi = TextBoxisBaslangicTarihi.Text.Replace(".", "/").Split('/');
isbilgisi.isCikisTarihi = new DateTime(Convert.ToInt32(iscikisTarihi[2]), Convert.ToInt32(iscikisTarihi[0]), Convert.ToInt32(iscikisTarihi[1]));
isbilgisi.isGirisTarihi = new DateTime(Convert.ToInt32(isgirisTarihi[2]), Convert.ToInt32(isgirisTarihi[0]), Convert.ToInt32(isgirisTarihi[1]));
isbilgisi.departmanID = Convert.ToInt32(DropDownDepartman.SelectedValue);
}
catch (Exception)
{
}
}
// Gerekli özellikller
string ad = DropDownListIller.SelectedItem.Text;
var sehir = db.Sehirs.Where(k => k.sehirAd == ad).FirstOrDefault();
string[] dizi = TextBoxDogumTarihi.Text.Replace(".", "/").Split('/');
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
//EGitim Kayıt İşemleri
var durum = db.OkunanBolums.Where(k => k.kullaniciID == id).FirstOrDefault();
if (durum == null)
{
try
{
Model.OkunanBolum okunan = new Model.OkunanBolum();
okunan.bolumID = Convert.ToInt32(DropDownListBolum.SelectedValue);
okunan.kullaniciID = kisi.kullaniciID;
string[] girisTarihi = TextBoxGirisTarihi.Text.Replace(".", "/").Split('/');
string[] cikisTarihi = TextBoxCikisTarihi.Text.Replace(".", "/").Split('/');
okunan.girisTarihi = new DateTime(Convert.ToInt32(girisTarihi[2]), Convert.ToInt32(girisTarihi[0]), Convert.ToInt32(girisTarihi[1]));
okunan.cikisTarihi = new DateTime(Convert.ToInt32(cikisTarihi[2]), Convert.ToInt32(cikisTarihi[0]), Convert.ToInt32(cikisTarihi[1]));
if (CheckBoxMezunDurum.Checked)
{
okunan.mezunDurumu = true;
}
else okunan.mezunDurumu = false;
db.OkunanBolums.Add(okunan);
}
catch (Exception)
{
}
}
else
{
try
{
durum.kullaniciID = kisi.kullaniciID;
string[] girisTarihi = TextBoxGirisTarihi.Text.Replace(".", "/").Split('/');
string[] cikisTarihi = TextBoxCikisTarihi.Text.Replace(".", "/").Split('/');
if (DropDownListBolum.SelectedValue != null)
{
durum.bolumID = Convert.ToInt32(DropDownListBolum.SelectedValue);
durum.girisTarihi = new DateTime(Convert.ToInt32(girisTarihi[2]), Convert.ToInt32(girisTarihi[0]), Convert.ToInt32(girisTarihi[1]));
durum.cikisTarihi = new DateTime(Convert.ToInt32(cikisTarihi[2]), Convert.ToInt32(cikisTarihi[0]), Convert.ToInt32(cikisTarihi[1]));
}
if (CheckBoxMezunDurum.Checked)
{
durum.mezunDurumu = true;
}
else durum.mezunDurumu = false;
}
catch (Exception)
{
}
}
//İletişim Kayıt
if (TextBoxFace.Text != null && TextBoxFace.Text != "")
{
string face = TextBoxFace.Text.Substring(0, 1).ToLower();
if (face == "h")
{
kisi.facebookURL = TextBoxFace.Text;
}
else if (face == "w")
{
kisi.facebookURL = "https://" + TextBoxFace.Text;
}
else if (face == "f")
{
kisi.facebookURL = "https://www." + TextBoxFace.Text;
}
}
if (TextBoxTwiter.Text != null && TextBoxTwiter.Text != "")
{
string twit = TextBoxTwiter.Text.Substring(0, 1).ToLower();
if (twit == "h")
{
kisi.twitterURL = TextBoxTwiter.Text;
}
else if (twit == "w")
{
kisi.twitterURL = "https://" + TextBoxTwiter.Text;
}
else if (twit == "t")
{
kisi.twitterURL = "https://www." + TextBoxTwiter.Text;
}
}
kisi.gosterilenMail = TextBoxMail.Text;
kisi.hakkimda = TextBoxHakkimda.Text;
kisi.isBilgisi = TextBoxis.Text;
kisi.cinsiyet = DropDownListCinsiyet.SelectedItem.Text;
kisi.dTarihi = new DateTime(Convert.ToInt32(dizi[2]), Convert.ToInt32(dizi[0]), Convert.ToInt32(dizi[1]));
kisi.sehirID = sehir.sehirID;
byte[] bytUpfile;
if (FileUpload1.HasFile)
{
try
{
string strTestFilePath = FileUpload1.PostedFile.FileName;
string strTestFileName = Path.GetFileName(strTestFilePath);
Int32 intFileSize = FileUpload1.PostedFile.ContentLength;
string strContentType = FileUpload1.PostedFile.ContentType;
string ext = Path.GetExtension(strTestFileName);
string yol = Path.GetFullPath(strTestFilePath);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
//
Stream strmStream = FileUpload1.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
string strBase64 = Convert.ToBase64String(bytUpfile);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
kisi.resim = bytUpfile;
LabelHata.Text = Convert.ToString(FileUpload1.FileBytes);
LabelHata.Visible = false;
}
else
{
Response.Write("<script>alert('Lütfen Bir Resim Formatı Seçiniz!');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
db.SaveChanges();
Response.Redirect("profil.aspx");
}
protected void LinkButtonResim_Click(object sender, EventArgs e)
{
}
protected void FileUpload1_DataBinding(object sender, EventArgs e)
{
}
protected void FileUpload1_Load(object sender, EventArgs e)
{
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
}
protected void FileUpload1_Init(object sender, EventArgs e)
{
}
protected void FileUpload1_Unload(object sender, EventArgs e)
{
}
protected void DropDownListEgitimSehir_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownListEgitimSehir_TextChanged(object sender, EventArgs e)
{
DropDownListEgitimUni.Items.Clear();
DropDownListEgitimFakulte.Items.Clear();
DropDownListBolum.Items.Clear();
var sehir = db.Sehirs.Where(s => s.sehirAd == DropDownListEgitimSehir.SelectedItem.Text).FirstOrDefault();
int sehID = sehir.sehirID;
var uni = db.Universites.Where(u => u.sehirID == sehID).ToList();
DropDownListEgitimUni.DataSource = uni;
DropDownListEgitimUni.DataTextField = "uniAd";
DropDownListEgitimUni.DataValueField = "uniID";
DropDownListEgitimUni.DataBind();
}
protected void DropDownListEgitimUni_TextChanged(object sender, EventArgs e)
{
DropDownListEgitimFakulte.Items.Clear();
DropDownListBolum.Items.Clear();
int uniID = Convert.ToInt32(DropDownListEgitimUni.SelectedValue);
var fakulte = db.OkulFakultes.Where(u => u.uniID == uniID).ToList();
DropDownListEgitimFakulte.DataSource = fakulte;
DropDownListEgitimFakulte.DataTextField = "okulAd";
DropDownListEgitimFakulte.DataValueField = "okulID";
DropDownListEgitimFakulte.DataBind();
}
protected void DropDownListEgitimFakulte_TextChanged(object sender, EventArgs e)
{
DropDownListBolum.Items.Clear();
int fakID = Convert.ToInt32(DropDownListEgitimFakulte.SelectedValue);
var bolum = db.Bolums.Where(u => u.okulID == fakID).ToList();
DropDownListBolum.DataSource = bolum;
DropDownListBolum.DataTextField = "bolumAd";
DropDownListBolum.DataValueField = "bolumID";
DropDownListBolum.DataBind();
}
protected void DropDownSirketSehir_TextChanged(object sender, EventArgs e)
{
DropDownSirket.Items.Clear();
DropDownDepartman.Items.Clear();
var sehir = db.Sehirs.Where(s => s.sehirAd == DropDownSirketSehir.SelectedItem.Text).FirstOrDefault();
int sehID = sehir.sehirID;
var isYeri = db.Isyeris.Where(u => u.sehırID == sehID).ToList();
DropDownSirket.DataSource = isYeri;
DropDownSirket.DataTextField = "IsyeriAd";
DropDownSirket.DataValueField = "IsyeriID";
DropDownSirket.DataBind();
}
protected void DropDownSirket_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownDepartman.Items.Clear();
var isAd = db.Isyeris.Where(s => s.IsyeriAd == DropDownSirket.SelectedItem.Text).FirstOrDefault();
int isYeriID = isAd.IsyeriID;
var departaman = db.Departmen.Where(u => u.IsyeriID == isYeriID).ToList();
DropDownDepartman.DataSource = departaman;
DropDownDepartman.DataTextField = "departmanAd";
DropDownDepartman.DataValueField = "departmanID";
DropDownDepartman.DataBind();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class arkOnay : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
try
{
int sid = Convert.ToInt32(Session["ID"].ToString());
int qid = Convert.ToInt32(Request.QueryString["id"]);
var onayla = db.Arkadas.Where(k => k.kullaniciID1 == qid && k.kullaniciID2 == sid).FirstOrDefault();
if (Request.QueryString["islem"].ToString()=="onay")
{
onayla.arkadaslikOnay = true;
db.SaveChanges();
Response.Redirect("profil.aspx");
}
else if (Request.QueryString["islem"].ToString() == "sil")
{
db.Arkadas.Remove(onayla);
db.SaveChanges();
Response.Redirect("profil.aspx");
}
}
catch (Exception)
{
Response.Redirect("profil.aspx");
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class WebForm1 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected string kullaniciIDdondur(string gelenID)
{
int id = Convert.ToInt32(gelenID);
string donecekID="";
var arkadas = db.Arkadas.Where(k=>k.arkadasID==id).FirstOrDefault();
if (Request.QueryString["id"] == null)
{
int kid=Convert.ToInt32(Session["ID"].ToString());
if (arkadas.kullaniciID1==kid)
{
donecekID=arkadas.kullaniciID2.ToString();
}
else
{
donecekID = arkadas.kullaniciID1.ToString();
}
}
else
{
int kid=Convert.ToInt32(Request.QueryString["id"]);
if (arkadas.kullaniciID1==kid)
{
donecekID=arkadas.kullaniciID2.ToString();
}
else
{
donecekID = arkadas.kullaniciID1.ToString();
}
}
return donecekID;
}
protected string ResimGosterici(string id)
{
int yeniID = Convert.ToInt32(id);
// var mesaj = (from b in db.Mesajs where b.mesajID == yeniID orderby b.mesajID descending select b).FirstOrDefault();
var arkadaslik = db.Arkadas.Where(k => k.arkadasID == yeniID).FirstOrDefault();
string resim = "";
if (Request.QueryString["id"] == null)
{
if (Convert.ToInt32(Session["ID"].ToString()) == arkadaslik.kullaniciID1)
{
//2. nin resmi gitcek
int K2id = Convert.ToInt32(arkadaslik.kullaniciID2);
var kullanici = db.Kullanicis.Where(k => k.kullaniciID == K2id).FirstOrDefault();
if (kullanici.resim != null)
{
string strBase64 = Convert.ToBase64String(kullanici.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (kullanici.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
}
else if (Convert.ToInt32(Session["ID"].ToString()) == arkadaslik.kullaniciID2)
{
//1. nin resmi gidicek
int K1id = Convert.ToInt32(arkadaslik.kullaniciID1);
var kullanici = db.Kullanicis.Where(k => k.kullaniciID == K1id).FirstOrDefault();
if (kullanici.resim != null)
{
string strBase64 = Convert.ToBase64String(kullanici.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (kullanici.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
}
}
else
{
if (Convert.ToInt32(Request.QueryString["id"]) == arkadaslik.kullaniciID1)
{
//2. nin resmi gitcek
int K2id = Convert.ToInt32(arkadaslik.kullaniciID2);
var kullanici = db.Kullanicis.Where(k => k.kullaniciID == K2id).FirstOrDefault();
if (kullanici.resim != null)
{
string strBase64 = Convert.ToBase64String(kullanici.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (kullanici.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
}
else if (Convert.ToInt32(Request.QueryString["id"]) == arkadaslik.kullaniciID2)
{
//1. nin resmi gidicek
int K1id = Convert.ToInt32(arkadaslik.kullaniciID1);
var kullanici = db.Kullanicis.Where(k => k.kullaniciID == K1id).FirstOrDefault();
if (kullanici.resim != null)
{
string strBase64 = Convert.ToBase64String(kullanici.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (kullanici.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
}
}
return resim;
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(Session["ID"].ToString());
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (Request.QueryString["id"] == null)
{//ANA KULLANICI PROFİLİ
panelMesaj.Visible = false;
LinkBtnArkadasEkle.Text = "Bilgileri Güncelle <i class=\"fa fa-save\"></i>";
LinkBtnArkadasEkle.CssClass = "btn btn-success";
LinkButtonDuzenle.Visible = true;
// LinkButtonArkEkle.Visible = true;
}
else if (Request.QueryString["id"] == Session["ID"].ToString())
{
Response.Redirect("Profil.aspx");
}
else
{//DİĞER KULLANICI PROFİLİ
id = Convert.ToInt32(Request.QueryString["id"]);
int sesionid = Convert.ToInt32(Session["ID"].ToString());
kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
panelMesaj.Visible = true;
var arkDurum = db.Arkadas.Where(k => (k.kullaniciID1 == id && k.kullaniciID2 == sesionid) || (k.kullaniciID1 == sesionid && k.kullaniciID2 == id)).FirstOrDefault();
if (arkDurum != null)
{
if (arkDurum.arkadaslikOnay==true)
{
LinkBtnArkadasEkle.CssClass = "btn btn-danger";
LinkBtnArkadasEkle.Text = "Arkadaşlıktan Çıkar <i class=\"fa fa-close\"></i>";
}
else
{
if (arkDurum.kullaniciID1==sesionid)
{
LinkBtnArkadasEkle.CssClass = "btn btn-danger";
LinkBtnArkadasEkle.Text = "İsteği İptal Et <i class=\"fa fa-close\"></i>";
}
else
{
LinkBtnArkadasEkle.CssClass = "btn btn-success";
LinkBtnArkadasEkle.Text = "İsteği Onayla <i class=\"fa fa-check\"></i>";
}
}
}
else
{
LinkBtnArkadasEkle.CssClass = "btn btn-success";
LinkBtnArkadasEkle.Text = "Arkadaş Ekle <i class=\"fa fa-save\"></i>";
}
LinkBtnArkadasEkle.Visible = true;
LinkButtonDuzenle.Visible = false;
// LinkButtonArkEkle.Visible = false;
var egitim = db.OkunanBolums.Where(k => k.kullaniciID == id).FirstOrDefault();
var iss = db.KullaniciIsGecmisis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (iss == null)
{
PanelIs.Visible = false;
}
else
{
PanelIs.Visible = true;
var isbilgis = db.ViewisBilgisis.Where(k => k.kullaniciID == id).FirstOrDefault();
lblSirketAd.Text = isbilgis.IsyeriAd;
lblSirketSehir.Text = isbilgis.sehirAd;
lblPozisyon.Text = isbilgis.pozisyon;
lblisGirisT.Text = Convert.ToDateTime(isbilgis.isGirisTarihi).ToShortDateString();
}
if (egitim == null)
{
PanelEgitim.Visible = false;
}
else
{
if (IsPostBack != true)
{
panelMesaj.Visible = true;
var egitimbilgis = db.ViewOkuls.Where(k => k.kullaniciID == id).FirstOrDefault();
lblEgitimSehir.Text = egitimbilgis.sehirAd;
lblOkulAdi.Text = egitimbilgis.uniAd;
lblOkul.Text = egitimbilgis.okulAd;
lblTarih.Text = Convert.ToDateTime(egitimbilgis.girisTarihi).ToShortDateString();
}
}
}
int nid;
if (Request.QueryString["id"] == null)
{
nid = Convert.ToInt32(Session["ID"].ToString());
}
else
{
nid = Convert.ToInt32(Request.QueryString["id"]);
}
var arkList = db.Arkadas.Where(k => (k.kullaniciID1 == nid || k.kullaniciID2 == nid)&&k.arkadaslikOnay==true).ToList();
if (arkList != null)
{
panelArkList.Visible = true;
rptrARK.DataSource = arkList;
rptrARK.DataBind();
}
else
{
panelArkList.Visible = false;
}
if (kisi.resim != null)
{
string strBase64 = Convert.ToBase64String(kisi.resim);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
if (kisi.cinsiyet == "Erkek")
{
Image1.ImageUrl = "~/image/Man.jpg";
}
else
{
Image1.ImageUrl = "~/image/Woman.jpg";
}
}
LabelKullaniciCinsiyet.Text = kisi.cinsiyet;
DateTime dt = kisi.dTarihi.Value;
LabelKullanıcıDogumTarihi.Text = dt.ToShortDateString();
LabelKullaniciİs.Text = kisi.isBilgisi;
var sehir = db.Sehirs.Where(k => k.sehirID == kisi.sehirID).FirstOrDefault();
LabelKullaniciSehir.Text = sehir.sehirAd.ToString();
LabelKullaniciHakımda.Text = kisi.hakkimda;
HyperLinkMail.Text = kisi.gosterilenMail;
HyperLinkMail.NavigateUrl = "https://" + kisi.gosterilenMail;
HyperLinkFace.NavigateUrl = kisi.facebookURL;
HyperLinkTwitter.NavigateUrl = kisi.twitterURL;
LabelKullaniciİsim.Text = kisi.isim + " " + kisi.soyad;
if (IsPostBack != true)
{ //İŞ GÖSTERME
var isbilgis = db.ViewisBilgisis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (isbilgis != null)
{
PanelIs.Visible = true;
lblSirketAd.Text = isbilgis.IsyeriAd;
lblSirketSehir.Text = isbilgis.sehirAd;
lblPozisyon.Text = isbilgis.pozisyon;
lblisGirisT.Text = Convert.ToDateTime(isbilgis.isGirisTarihi).ToShortDateString();
}
//EĞTİM GÖSTERME
var egitimbilgis = db.ViewOkuls.Where(k => k.kullaniciID == id).FirstOrDefault();
if (egitimbilgis!=null)
{
PanelEgitim.Visible = true;
lblEgitimSehir.Text = egitimbilgis.sehirAd;
lblOkulAdi.Text = egitimbilgis.uniAd;
lblOkul.Text = egitimbilgis.okulAd;
lblTarih.Text = Convert.ToDateTime(egitimbilgis.girisTarihi).ToShortDateString();
}
}
}
catch (Exception)
{
// Response.Redirect("~/Profil.aspx");
}
}
protected void LinkBtnMesajGonder_Click(object sender, EventArgs e)
{//PROFİL MESAJI
string mesaj = TextBoxMesajKutusu.Text;
int grup;
if (mesaj != "" || mesaj != null)
{
int profilID = Convert.ToInt32(Request.QueryString["id"]);
int gonderenID = Convert.ToInt32(Session["ID"].ToString());
var mesajlar = (from b in db.Mesajs where (b.kullaniciIDAlan == profilID && b.kullaniciIDGonderen == gonderenID) || (b.kullaniciIDGonderen == profilID && b.kullaniciIDAlan == gonderenID) orderby b.mesajID descending select b).ToList();
if (mesajlar.Count == 0)
{
var tummesajlar = (from b in db.Mesajs orderby b.mesajGrup descending select b).FirstOrDefault();
grup = Convert.ToInt32(tummesajlar.mesajGrup) + 1;
}
else
{
var SonMesaj = mesajlar.FirstOrDefault();
grup = Convert.ToInt32(SonMesaj.mesajGrup);
}
Model.Mesaj nm = new Model.Mesaj();
nm.mesajGrup = grup.ToString();
nm.mesajIcerik = mesaj;
nm.kullaniciIDGonderen = gonderenID;
nm.kullaniciIDAlan = profilID;
nm.mesajZaman = DateTime.Now;
db.Mesajs.Add(nm);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
TextBoxMesajKutusu.Focus();
}
}
protected void LinkButtonDuzenle_Click(object sender, EventArgs e)
{
if ((LinkButtonDuzenle.Text).Substring(0, 1) == "D")
{
DropDownListCinsiyet.Visible = true;
TextBoxDogumTarihi.Visible = true;
TextBoxis.Visible = true;
DropDownListIller.Visible = true;
LinkButtonDuzenle.Text = "Kaydet <i class=\"fa fa-save\"></i>";
LabelKullaniciSehir.Visible = false;
LabelKullaniciİs.Visible = false;
LabelKullanıcıDogumTarihi.Visible = false;
LabelKullaniciCinsiyet.Visible = false;
//BİLGİLERİ GETİRİCEK KODLAR YAZILCAK
TextBoxDogumTarihi.Text = LabelKullanıcıDogumTarihi.Text;
TextBoxis.Text = LabelKullaniciİs.Text;
DropDownListIller.Text = LabelKullaniciSehir.Text;
DropDownListCinsiyet.Text = LabelKullaniciCinsiyet.Text;
}
else
{
DropDownListCinsiyet.Visible = false;
TextBoxDogumTarihi.Visible = false;
TextBoxis.Visible = false;
DropDownListIller.Visible = false;
LinkButtonDuzenle.Text = "Düzenle <i class=\"fa fa-save\"></i>";
LabelKullaniciSehir.Visible = true;
LabelKullaniciİs.Visible = true;
LabelKullanıcıDogumTarihi.Visible = true;
LabelKullaniciCinsiyet.Visible = true;
//KAYDEDİP TEKRAR LİSTELEME YAPILACAK
string ad = DropDownListIller.SelectedItem.Text;
var sehir = db.Sehirs.Where(k => k.sehirAd == ad).FirstOrDefault();
string[] dizi = TextBoxDogumTarihi.Text.Replace(".", "/").Split('/');
int id = Convert.ToInt32(Session["ID"].ToString());
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
kisi.isBilgisi = TextBoxis.Text;
kisi.cinsiyet = DropDownListCinsiyet.SelectedItem.Text;
kisi.dTarihi = new DateTime(Convert.ToInt32(dizi[2]), Convert.ToInt32(dizi[0]), Convert.ToInt32(dizi[1]));
kisi.sehirID = sehir.sehirID;
db.SaveChanges();
Response.Redirect("~/Profil.aspx");
}
}
protected void LinkBtnArkadasEkle_Click(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("~/Duzenle.aspx");
}
else
{
int id = Convert.ToInt32(Request.QueryString["id"]);
int sessionid = Convert.ToInt32(Session["ID"].ToString());
var arkDurum = db.Arkadas.Where(k => (k.kullaniciID1 == id && k.kullaniciID2 == sessionid) || (k.kullaniciID1 == sessionid && k.kullaniciID2 == id)).FirstOrDefault();
if (arkDurum != null)
{
if (arkDurum.arkadaslikOnay == true)
{
//Ark.cıkar
db.Arkadas.Remove(arkDurum);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
else
{
if (arkDurum.kullaniciID1==sessionid)
{
//Ark.cıkar
db.Arkadas.Remove(arkDurum);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
else
{
arkDurum.arkadaslikOnay = true;
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
}
}
else
{
//ark.ekle
Model.Arkada arkads = new Model.Arkada();
arkads.kullaniciID1 = sessionid;
arkads.kullaniciID2 = id;
arkads.arkadaslikOnay = false;
db.Arkadas.Add(arkads);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class KayitAdim5 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
ButtonResimSec.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click(); return false;");
if (Session["ID"]==null)
{
Response.Redirect("Login.aspx");
}
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.cinsiyet=="Erkek")
{
imageView1.ImageUrl = "image\\Man.jpg";
}
else
{
imageView1.ImageUrl = "image\\Woman.jpg";
}
}
protected void LinkButtonGec_Click1(object sender, EventArgs e)
{
int id = (int)Session["ID"];
string yol;
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.cinsiyet == "Erkek")
{
yol = @"C:\Users\MustafaKemal\Desktop\son proje\MezunSistemiProjesi\image\Man.jpg";
}
else
{
yol = @"C:\Users\MustafaKemal\Desktop\son proje\MezunSistemiProjesi\image\Woman.jpg";
}
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(yol);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(yol, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
kisi.resim= imageData;
db.SaveChanges();
Response.Redirect("Profil.aspx");
}
protected void LinkButtonIleri_Click(object sender, EventArgs e)
{
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (FileUpload1.HasFile)
{
try
{
string strTestFilePath = FileUpload1.PostedFile.FileName;
string strTestFileName = Path.GetFileName(strTestFilePath);
Int32 intFileSize = FileUpload1.PostedFile.ContentLength;
string strContentType = FileUpload1.PostedFile.ContentType;
string ext = Path.GetExtension(strTestFileName);
string yol = Path.GetFullPath(strTestFilePath);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
//
Stream strmStream = FileUpload1.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
byte[] bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
kisi.resim = bytUpfile;
db.SaveChanges();
Label1.Visible = false;
}
else
{
Response.Write("<script>alert('Lütfen Bir Resim Formatı Seçiniz!');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
//string strBase64 = Convert.ToBase64String(kisi.resim);
//imageView1.ImageUrl = "data:Image/png;base64," + strBase64;
if (kisi.resim!=null)
{
Response.Redirect("Profil.aspx");
}
else
{
Label1.Visible = true;
}
}
protected void ButtonResimSec_Click(object sender, EventArgs e)
{
}
protected void LinkButtonYukle_Click(object sender, EventArgs e)
{
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class Site1 : System.Web.UI.MasterPage
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(Session["ID"].ToString());
//okul grupları
var okulbul = db.OkunanBolums.Where(k => k.kullaniciID == id).FirstOrDefault();
if (okulbul != null)
{
var bolum = db.Bolums.Where(k => k.bolumID == okulbul.bolumID).FirstOrDefault();
var okul = db.ViewOkuls.Where(k => k.okulID == bolum.okulID).FirstOrDefault();
var uni = db.ViewOkuls.Where(k => k.uniID == okul.uniID).FirstOrDefault();
panelokulGruplari.Visible = true;
if (bolum.bolumAd.Length > 20)
{
lblGrpBolum.Text = bolum.bolumAd.Substring(0, 20) + "...";
}
else
{
lblGrpBolum.Text = bolum.bolumAd;
}
lblGrpBolum.NavigateUrl = "Grup.aspx?g=b&id=" + bolum.bolumID.ToString();
if (okul.okulAd.Length > 20)
{
lblGrpOkul.Text = okul.okulAd.Substring(0, 20) + "...";
}
else
{
lblGrpOkul.Text = okul.okulAd;
}
lblGrpOkul.NavigateUrl = "Grup.aspx?g=o&id=" + okul.okulID.ToString();
if (uni.uniAd.Length > 20)
{
lblGrpUni.Text = uni.uniAd.Substring(0, 20) + "...";
}
else
{
lblGrpUni.Text = uni.uniAd;
}
lblGrpUni.NavigateUrl = "Grup.aspx?g=u&id=" + uni.uniID.ToString();
}
// var bildirim =(db.Bildirimlers.Where(b => b.kullaniciID == id)).ToList();
var bildirim = (from b in db.Bildirimlers where b.kullaniciID == id orderby b.bildirimID descending select b).ToList();
rptrBildirim.DataSource = bildirim;
rptrBildirim.DataBind();
//id nin geçtigi bütün mesajları getirir
var mesaj = (from b in db.Mesajs where b.kullaniciIDAlan == id || b.kullaniciIDGonderen == id orderby b.mesajID descending select b).ToList();
//tekrar eden mesajları filtreler.
mesaj = mesaj.GroupBy(test => test.mesajGrup)
.Select(grp => grp.First())
.ToList();
rptrMesaj.DataSource = mesaj;
rptrMesaj.DataBind();
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
LabelKullaniciİsimKucuk.Text = kisi.isim[0].ToString().ToUpper() + kisi.isim.Substring(1, kisi.isim.Length - 1).ToLower();
string strBase64 = Convert.ToBase64String(kisi.resim);
Image1KucukResim.ImageUrl = "data:Image/png;base64," + strBase64;
//Ark isteklerini listele
var istekList = db.Arkadas.Where(k=>k.kullaniciID2==id && k.arkadaslikOnay==false).ToList();
rptrArkistekler.DataSource = istekList;
rptrArkistekler.DataBind();
}
catch (Exception)
{
Response.Redirect("Login.aspx");
}
}
protected string resimDoldur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
string resim="";
if (dondurucu.resim != null)
{
string strBase64 = Convert.ToBase64String(dondurucu.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (dondurucu.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
return resim;
}
protected string isimDondur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
return dondurucu.isim;
}
protected string MesajGosterici(string id)
{
string isim = "";
int yeniID = Convert.ToInt32(id);
var mesaj = (from b in db.Mesajs where b.mesajID == yeniID orderby b.mesajID descending select b).FirstOrDefault();
if (Convert.ToInt32(Session["ID"].ToString())==mesaj.kullaniciIDAlan)
{
var kisi1 = db.Kullanicis.Where(o => o.kullaniciID == mesaj.kullaniciIDGonderen).FirstOrDefault();
isim = kisi1.isim + " " + kisi1.soyad;
}
else if (Convert.ToInt32(Session["ID"].ToString())==mesaj.kullaniciIDGonderen)
{
var kisi2 = db.Kullanicis.Where(o => o.kullaniciID == mesaj.kullaniciIDAlan).FirstOrDefault();
isim = kisi2.isim + " " + kisi2.soyad;
}
return isim;
}
protected void LinkButtonArkadaslikReddet_Click(object sender, EventArgs e)
{
}
protected void LinkButtonArkadaslikKabul_Click1(object sender, EventArgs e)
{
//int id = Convert.ToInt32(Request.QueryString["id"]);
//int sessionid = Convert.ToInt32(Session["ID"].ToString());
//var arkDurum = db.Arkadas.Where(k =>k.kullaniciID1=)
//arkDurum.arkadaslikOnay = true;
//db.SaveChanges();
//Response.Redirect(Page.Request.Url.ToString());
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class KayitAdim2 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.isBilgisi!=null)
{
Response.Redirect("KayitAdim3.aspx");
}
}
protected void LinkButtonİleri_Click(object sender, EventArgs e)
{
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
kisi.isBilgisi = TextBoxIsbilgisi.Text;
db.SaveChanges();
Response.Redirect("KayitAdim3.aspx");
}
protected void LinkButtonGec_Click1(object sender, EventArgs e)
{
Response.Redirect("KayitAdim3.aspx");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class KayitAdim4 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ID"] == null)
{
Response.Redirect("Login.aspx");
}
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.sehirID != null)
{
Response.Redirect("KayitAdim5.aspx");
}
}
protected void LinkButtonGec_Click(object sender, EventArgs e)
{
Response.Redirect("KayitAdim5.aspx");
}
protected void LinkButtonİleri_Click(object sender, EventArgs e)
{
string ad=DropDownListIller.SelectedItem.Text;
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
var sehir = db.Sehirs.Where(k => k.sehirAd == ad).FirstOrDefault();
kisi.sehirID = sehir.sehirID;
db.SaveChanges();
Response.Redirect("KayitAdim5.aspx");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class WebForm3 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
int id ;
if (Request.QueryString["id"]==null)
{
id = Convert.ToInt32(Session["ID"].ToString());
var sonMesaj = (from b in db.Mesajs where b.kullaniciIDAlan == id || b.kullaniciIDGonderen == id orderby b.mesajID descending select b).FirstOrDefault();
Response.Redirect("~/mesajlar.aspx?id=" + sonMesaj.mesajID.ToString());
}
try
{
// mesajlardaki kişileri listeler.
id = Convert.ToInt32(Session["ID"].ToString());
var mesajKisiler = (from b in db.Mesajs where b.kullaniciIDAlan == id || b.kullaniciIDGonderen == id orderby b.mesajID descending select b).ToList();
mesajKisiler = mesajKisiler.GroupBy(test => test.mesajGrup)
.Select(grp => grp.First())
.ToList();
rptrMesajKisiler.DataSource = mesajKisiler;
rptrMesajKisiler.DataBind();
//mesajın içerigini listeler
int mesajinID = Convert.ToInt32(Request.QueryString["id"]);
int karsiID;
var karsi = (from b in db.Mesajs where b.mesajID == mesajinID orderby b.mesajID descending select b).FirstOrDefault();
if (karsi.kullaniciIDAlan==id)
{
karsiID = Convert.ToInt32(karsi.kullaniciIDGonderen);
}
else
{
karsiID =Convert.ToInt32(karsi.kullaniciIDAlan);
}
var mesajlar = (from b in db.Mesajs where (b.kullaniciIDAlan == id && b.kullaniciIDGonderen == karsiID )||( b.kullaniciIDGonderen == id && b.kullaniciIDAlan == karsiID) orderby b.mesajID descending select b).ToList();
rptrMesajListele.DataSource = mesajlar;
rptrMesajListele.DataBind();
}
catch (Exception)
{
}
}
protected bool idBenimMi(string id)
{
if (id==Session["ID"].ToString())
{
return true;
}
else
{
return false;
}
}
protected string AktifMesaj(string gelenID)
{
if (gelenID==Request.QueryString["id"])
{
return "active";
}
else
{
return "";
}
}
protected string MesajGosterici(string id)
{
string isim = "";
int yeniID = Convert.ToInt32(id);
var mesaj = (from b in db.Mesajs where b.mesajID == yeniID orderby b.mesajID descending select b).FirstOrDefault();
if (Convert.ToInt32(Session["ID"].ToString()) == mesaj.kullaniciIDAlan)
{
var kisi1 = db.Kullanicis.Where(o => o.kullaniciID == mesaj.kullaniciIDGonderen).FirstOrDefault();
isim = kisi1.isim + " " + kisi1.soyad;
}
else if (Convert.ToInt32(Session["ID"].ToString()) == mesaj.kullaniciIDGonderen)
{
var kisi2 = db.Kullanicis.Where(o => o.kullaniciID == mesaj.kullaniciIDAlan).FirstOrDefault();
isim = kisi2.isim + " " + kisi2.soyad;
}
return isim;
}
protected void LinkBtnMesajGonder_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["ID"].ToString());
int mesajinID = Convert.ToInt32(Request.QueryString["id"]);
int karsiID;
var karsi = (from b in db.Mesajs where b.mesajID == mesajinID orderby b.mesajID descending select b).FirstOrDefault();
if (karsi.kullaniciIDAlan == id)
{
karsiID = Convert.ToInt32(karsi.kullaniciIDGonderen);
}
else
{
karsiID = Convert.ToInt32(karsi.kullaniciIDAlan);
}
Model.Mesaj yeniMsj = new Model.Mesaj();
yeniMsj.kullaniciIDAlan = karsiID;
yeniMsj.kullaniciIDGonderen = id;
yeniMsj.mesajIcerik = TextBoxMesajKutusu.Text;
yeniMsj.mesajZaman = DateTime.Now;
yeniMsj.mesajOkunma = false;
yeniMsj.mesajGrup = karsi.mesajGrup;
db.Mesajs.Add(yeniMsj);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
TextBoxMesajKutusu.Focus();
}
protected string resimDoldur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
string resim = "";
if (dondurucu.resim != null)
{
string strBase64 = Convert.ToBase64String(dondurucu.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (dondurucu.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
return resim;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class Onay : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
int UyeID;
DateTime UyeZamani;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["kid"] != null && Request.QueryString["kd1"] != null)
{
UyeZamani = Convert.ToDateTime(Request.QueryString["kd1"]);
// UyeKod = Request.QueryString["kd2"];
UyeID = Convert.ToInt32(Request.QueryString["kid"]);
}
else
{
Response.Redirect("~/login.aspx");
}
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
var kisi = db.Kullanicis.Where(o => o.kullaniciID == UyeID).FirstOrDefault();
if (kisi.uyeKodu == txtOnay.Text.Trim())
{
LabelOnay.Visible = false;
if (kisi != null)
{
kisi.onay = true;
db.SaveChanges();
}
Response.Redirect("profile.aspx");
}
else
{
LabelOnay.Visible = true;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class KayitAdim1 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
RangeValidator1.MaximumValue = DateTime.Now.ToShortDateString();
RangeValidator1.MinimumValue = new DateTime(1900, 01, 01).ToShortDateString();
//si.dTarihi
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
}
protected void LinkButtonIleri_Click(object sender, EventArgs e)
{
string[] dizi = TextBoxDogumTarihi.Text.Split('/');
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
kisi.dTarihi = new DateTime(Convert.ToInt32(dizi[2]), Convert.ToInt32(dizi[0]), Convert.ToInt32(dizi[1]));
db.SaveChanges();
Response.Redirect("KayitAdim2.aspx");
}
protected void LinkButtonGec_Click(object sender, EventArgs e)
{
Response.Redirect("KayitAdim2.aspx");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class Login : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
if (CheckBoxSozlesme.Checked)
{
var kisi = db.Kullanicis.Where(o => o.email == kayitEmail.Text).FirstOrDefault();
if (kisi != null)
{
LabelSozlesmeKontrol.Visible = true;
LabelSozlesmeKontrol.Text = "Mevcut E-posta adresi girdiniz. !";
}
else
{
Random rdn = new Random();
string random = rdn.Next(10000000, 99999999).ToString();
LabelSozlesmeKontrol.Visible = false;
Model.Kullanici k1 = new Model.Kullanici();
DateTime uyeZamani = System.DateTime.Now;
k1.isim = kayitAd.Text;
k1.soyad = kayitSoyad.Text;
k1.email = kayitEmail.Text;
k1.sifre = kayitPassword1.Text;
k1.onay = false;
k1.uyeKoduZaman = uyeZamani;
k1.uyeKodu = random;
db.Kullanicis.Add(k1);
db.SaveChanges();
long id = k1.kullaniciID;
SmtpClient mlClient = new SmtpClient();
MailMessage mlMessage = new MailMessage();
mlMessage.To.Add(kayitEmail.Text);
mlMessage.From = new MailAddress("<EMAIL>", "Site Üye Onayı");
mlMessage.Subject = "Mail İle Uye Kayıt Onayı";
mlMessage.IsBodyHtml = true;
mlMessage.Body = "Sayın " + kayitAd.Text + "<br/>" + "İsimli Hesabı Aktif Hale Getirmek İçin Kodunuz : " + random;
NetworkCredential guvenlikKarti = new NetworkCredential("codetech.destek", "4256123789");
mlClient.Credentials = guvenlikKarti;
mlClient.Port = 587;
mlClient.Host = "smtp.gmail.com";
mlClient.EnableSsl = true;
mlClient.Send(mlMessage);
Response.Redirect("Onay.aspx/?kd1=" + uyeZamani + "&kid=" + id);
}
}
else
{
LabelSozlesmeKontrol.Text = "Lütfen Sözleşmeyi Kabul Ediniz. !";
LabelSozlesmeKontrol.Visible = true;
}
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
string mail = girisEmail.Text;
string sifre = girisPassword.Text;
var kisi = db.Kullanicis.Where(o => o.email == mail && o.sifre == sifre).FirstOrDefault();
if (kisi != null)
{
LabelGirisHataMesaji.Visible = true;
LabelGirisHataMesaji.Text = kisi.isim;
if (kisi.onay == true)
{
if (kisi.dTarihi == null)
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("KayitAdim1.aspx");
}
else if (kisi.isBilgisi == null)
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("KayitAdim2.aspx");
}
else if (kisi.cinsiyet == null)
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("KayitAdim3.aspx");
}
else if (kisi.sehirID == null)
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("KayitAdim4.aspx");
}
else if (kisi.resim == null)
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("KayitAdim5.aspx");
}
else
{
Session["ID"] = kisi.kullaniciID;
Response.Redirect("Profil.aspx");
}
}
else
{
Random rdn = new Random();
string random = rdn.Next(10000000, 99999999).ToString();
kisi.uyeKodu = random;
db.SaveChanges();
SmtpClient mlClient = new SmtpClient();
MailMessage mlMessage = new MailMessage();
mlMessage.To.Add(kisi.email);
mlMessage.From = new MailAddress("<EMAIL>", "Site Üye Onayı");
mlMessage.Subject = "Mail İle Uye Kayıt Onayı";
mlMessage.IsBodyHtml = true;
mlMessage.Body = "Sayın " + kayitAd.Text + "<br/>" + "Hesabınızı Aktif Hale Getirmek İçin Yeni Kodunuz : " + random;
NetworkCredential guvenlikKarti = new NetworkCredential("codetech.destek", "4256123789");
mlClient.Credentials = guvenlikKarti;
mlClient.Port = 587;
mlClient.Host = "smtp.gmail.com";
mlClient.EnableSsl = true;
mlClient.Send(mlMessage);
Response.Redirect("Onay.aspx/?kd1=" + kisi.uyeKoduZaman + "&kid=" + kisi.kullaniciID);
}
}
else
{
LabelGirisHataMesaji.Visible = true;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class denemeAmaclidir : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
iller.Add("Adana");
iller.Add(" Adıyaman");
iller.Add(" Afyon");
iller.Add(" Ağrı");
iller.Add(" Amasya");
iller.Add(" Ankara");
iller.Add(" Antalya");
iller.Add(" Artvin");
iller.Add(" Aydın");
iller.Add(" Balıkesir");
iller.Add(" Bilecik");
iller.Add(" Bingöl");
iller.Add(" Bitlis");
iller.Add(" Bolu");
iller.Add(" Burdur");
iller.Add(" Bursa");
iller.Add(" Çanakkale");
iller.Add(" Çankırı");
iller.Add(" Çorum");
iller.Add(" Denizli");
iller.Add(" Diyarbakır");
iller.Add(" Edirne");
iller.Add(" Elazığ");
iller.Add(" Erzincan");
iller.Add(" Erzurum");
iller.Add(" Eskişehir");
iller.Add(" Gaziantep");
iller.Add(" Giresun");
iller.Add(" Gümüşhane");
iller.Add(" Hakkari");
iller.Add(" Hatay");
iller.Add(" Isparta");
iller.Add(" İçel (Mersin)");
iller.Add(" İstanbul");
iller.Add(" İzmir");
iller.Add(" Kars");
iller.Add(" Kastamonu");
iller.Add(" Kayseri");
iller.Add(" Kırklareli");
iller.Add(" Kırşehir");
iller.Add(" Kocaeli");
iller.Add(" Konya");
iller.Add(" Kütahya");
iller.Add(" Malatya");
iller.Add(" Manisa");
iller.Add(" K.maraş");
iller.Add(" Mardin");
iller.Add(" Muğla");
iller.Add(" Muş");
iller.Add(" Nevşehir");
iller.Add(" Niğde");
iller.Add(" Ordu");
iller.Add(" Rize");
iller.Add(" Sakarya");
iller.Add(" Samsun");
iller.Add(" Siirt");
iller.Add(" Sinop");
iller.Add(" Sivas");
iller.Add(" Tekirdağ");
iller.Add(" Tokat");
iller.Add(" Trabzon");
iller.Add(" Tunceli");
iller.Add(" Şanlıurfa");
iller.Add(" Uşak");
iller.Add(" Van");
iller.Add(" Yozgat");
iller.Add(" Zonguldak");
iller.Add(" Aksaray");
iller.Add(" Bayburt");
iller.Add(" Karaman");
iller.Add(" Kırıkkale");
iller.Add(" Batman");
iller.Add(" Şırnak");
iller.Add(" Bartın");
iller.Add(" Ardahan");
iller.Add(" Iğdır");
iller.Add(" Yalova");
iller.Add(" Karabük");
iller.Add(" Kilis");
iller.Add(" Osmaniye");
iller.Add(" Düzce");
}
List<string> iller = new List<string>();
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < iller.Count; i++)
{
Model.Sehir sehir = new Model.Sehir();
sehir.sehirID = i+1;
sehir.sehirAd = iller[i];
db.Sehirs.Add(sehir);
db.SaveChanges();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class WebForm2 : System.Web.UI.Page
{
protected string resimDoldur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
string resim = "";
if (dondurucu.resim != null)
{
string strBase64 = Convert.ToBase64String(dondurucu.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (dondurucu.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
return resim;
}
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected void Page_Load(object sender, EventArgs e)
{
try
{
int sid = Convert.ToInt32(Session["ID"].ToString());
var okulbul = db.OkunanBolums.Where(k=>k.kullaniciID==sid).FirstOrDefault();
if (okulbul!=null)
{
var bolum = db.Bolums.Where(k => k.bolumID == okulbul.bolumID).FirstOrDefault();
var okul = db.ViewOkuls.Where(k=>k.okulID==bolum.okulID).FirstOrDefault();
var uni = db.ViewOkuls.Where(k => k.uniID == okul.uniID).FirstOrDefault();
panelOkulGruplari.Visible = true;
lblBolumAdi.Text = bolum.bolumAd;
lblBolumAdi.NavigateUrl = "Grup.aspx?g=b&id="+bolum.bolumID.ToString();
lblOkulAdi.Text = okul.okulAd;
lblOkulAdi.NavigateUrl = "Grup.aspx?g=o&id="+okul.okulID.ToString();
lblUniAdi.Text = uni.uniAd;
lblUniAdi.NavigateUrl = "Grup.aspx?g=u&id="+uni.uniID.ToString();
var bolumUyeList = db.OkunanBolums.Where(k => k.bolumID == bolum.bolumID).ToList();
rptrBolumGrp.DataSource = bolumUyeList;
rptrBolumGrp.DataBind();
var okulUyeList = db.ViewOkuls.Where(k => k.okulID == okul.okulID).ToList();
rptrOkulGrp.DataSource = okulUyeList;
rptrOkulGrp.DataBind();
var uniUyeList = db.ViewOkuls.Where(k => k.uniID == uni.uniID).ToList();
rptrUniGrp.DataSource = uniUyeList;
rptrUniGrp.DataBind();
}
}
catch (Exception)
{
Response.Redirect("login.aspx");
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class WebForm5 : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
protected string resimDoldur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
string resim = "";
if (dondurucu.resim != null)
{
string strBase64 = Convert.ToBase64String(dondurucu.resim);
resim = "data:Image/png;base64," + strBase64;
}
else
{
if (dondurucu.cinsiyet == "Erkek")
{
resim = "~/image/Man.jpg";
}
else
{
resim = "~/image/Woman.jpg";
}
}
return resim;
}
protected string idgetir()
{
return Session["ID"].ToString();
}
protected string tarihDoldur(string id)
{
int pid = Convert.ToInt32(id);
var pay = db.Paylasims.Where(k => k.paylasimID == pid).FirstOrDefault();
DateTime dt = Convert.ToDateTime(pay.tarih);
string ay = "";
if (dt.Month == 1) ay = "Ocak";
if (dt.Month == 2) ay = "Şubat";
if (dt.Month == 3) ay = "Mart";
if (dt.Month == 4) ay = "Nisan";
if (dt.Month == 5) ay = "Mayıs";
if (dt.Month == 6) ay = "Haziran";
if (dt.Month == 7) ay = "Temmuz";
if (dt.Month == 8) ay = "Ağustos";
if (dt.Month == 9) ay = "Eylül";
if (dt.Month == 10) ay = "Ekim";
if (dt.Month == 11) ay = "Kasım";
if (dt.Month == 12) ay = "Aralık";
return dt.Day + " " + ay;
}
protected string isimDondur(string id)
{
int kid = Convert.ToInt32(id);
var dondurucu = db.Kullanicis.Where(k => k.kullaniciID == kid).FirstOrDefault();
return dondurucu.isim + " " + dondurucu.soyad;
}
protected void Page_Load(object sender, EventArgs e)
{
try
{//Ana Kullanıcı bilgileri Dolduruluyor.
int sid = Convert.ToInt32(Session["ID"].ToString());
var kbilgi = db.Kullanicis.Where(k => k.kullaniciID == sid).FirstOrDefault();
HyperLinkAnaKulaniciAd.Text = kbilgi.isim + " " + kbilgi.soyad;
HyperLinkAnaKulaniciAd.NavigateUrl = "profil.aspx?id=" + kbilgi.kullaniciID.ToString();
LabelMesajTarih.Text = DateTime.Now.ToShortDateString();
ImageAnaKullanici.ImageUrl = resimDoldur(kbilgi.kullaniciID.ToString());
}
catch (Exception)
{
Response.Redirect("login.aspx");
}
if (Request.QueryString["id"] == null || Request.QueryString["g"] == null)
{
Response.Redirect("Gruplar.aspx");
}
else
{
int bid = Convert.ToInt32(Request.QueryString["id"]);
if (Request.QueryString["g"] == "b")
{
//Bolum bilgileri doldurulacak
var kullanicilist = db.OkunanBolums.Where(k => k.bolumID == bid).ToList();
rptrUyeList.DataSource = kullanicilist;
rptrUyeList.DataBind();
panelBolumBaslik.Visible = true;
panelOkulBaslik.Visible = true;
var bolum = db.Bolums.Where(k => k.bolumID == bid).FirstOrDefault();
LabelBolumBaslik.Text = bolum.bolumAd;
var okul = db.OkulFakultes.Where(k => k.okulID == bolum.okulID).FirstOrDefault();
LabelOkulBaslik.Text = okul.okulAd;
var uni = db.Universites.Where(k => k.uniID == okul.uniID).FirstOrDefault();
LabelUniBaslik.Text = uni.uniAd;
var paylasim = db.Paylasims.Where(p => p.grup == "b" && p.ogeID == bid).ToList();
rptrPaylasim.DataSource = paylasim;
rptrPaylasim.DataBind();
}
else if (Request.QueryString["g"] == "o")
{
//okul bilgileri doldurulacak
var kullanicilist = db.ViewOkuls.Where(k => k.okulID == bid).ToList();
rptrUyeList.DataSource = kullanicilist;
rptrUyeList.DataBind();
panelBolumBaslik.Visible = false;
panelOkulBaslik.Visible = true;
var okul = db.OkulFakultes.Where(k => k.okulID == bid).FirstOrDefault();
LabelOkulBaslik.Text = okul.okulAd;
var uni = db.Universites.Where(k => k.uniID == okul.uniID).FirstOrDefault();
LabelUniBaslik.Text = uni.uniAd;
var paylasim = db.Paylasims.Where(p => p.grup == "o" && p.ogeID == bid).ToList();
rptrPaylasim.DataSource = paylasim;
rptrPaylasim.DataBind();
}
else if (Request.QueryString["g"] == "u")
{
//universite bilgileri doldurulacak
var kullanicilist = db.ViewOkuls.Where(k => k.uniID == bid).ToList();
rptrUyeList.DataSource = kullanicilist;
rptrUyeList.DataBind();
panelBolumBaslik.Visible = false;
panelOkulBaslik.Visible = false;
var uni = db.Universites.Where(k => k.uniID == bid).FirstOrDefault();
LabelUniBaslik.Text = uni.uniAd;
var paylasim = db.Paylasims.Where(p => p.grup == "u" && p.ogeID == bid).ToList();
rptrPaylasim.DataSource = paylasim;
rptrPaylasim.DataBind();
}
else
{
Response.Redirect("Gruplar.aspx");
}
}
}
protected List<Model.Yorum> yorumDondurucu(string idpaylasim)
{
int iddd = Convert.ToInt32(idpaylasim);
var yorumlar = db.Yorums.Where(k => k.paylasimID == iddd).ToList();
return yorumlar;
}
protected void rptrPaylasim_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
protected void ButtonPaylasim_Click(object sender, EventArgs e)
{
int grubid = Convert.ToInt32(Request.QueryString["id"]);
string grupoge = Request.QueryString["g"];
int id = Convert.ToInt32(Session["ID"].ToString());
Model.Paylasim pay = new Model.Paylasim();
pay.kullaniciID = id;
pay.icerik = TextBoxKullaniciYorum.Text;
pay.grup = grupoge;
pay.ogeID = grubid;
pay.tarih = DateTime.Now;
db.Paylasims.Add(pay);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
TextBox txt;
int paylasimIDD;
protected void rptrYorum_ItemCommand(object source, RepeaterCommandEventArgs e)
{
paylasimIDD = Convert.ToInt32(e.CommandArgument);
}
protected void rptrPaylasim_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "linkbtn")
{
string[] str = Request.Form.GetValues("txtYorum"+ Convert.ToInt32(e.CommandArgument).ToString());
int id = Convert.ToInt32(Session["ID"].ToString());
Model.Yorum yorum = new Model.Yorum();
yorum.paylasimID = Convert.ToInt32(e.CommandArgument);////////////
yorum.tarih = DateTime.Now;
yorum.kullaniciID = id;
yorum.icerik = str[0]; ////
db.Yorums.Add(yorum);
db.SaveChanges();
Response.Redirect(Page.Request.Url.ToString());
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class KayitAdim3 : System.Web.UI.Page
{ Model.MezunVsEntities db = new Model.MezunVsEntities();
static short cins;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ID"] == null)
{
Response.Redirect("Login.aspx");
}
if (IsPostBack!=true)
{
cins = 0;
}
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (kisi.cinsiyet != null)
{
Response.Redirect("KayitAdim4.aspx");
}
}
protected void LinkButtonKadin_Click(object sender, EventArgs e)
{ cins = 1;
LinkButton1Erkek.BorderStyle = System.Web.UI.WebControls.BorderStyle.NotSet;
LinkButtonKadin.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;
Label1.Visible = false;
}
protected void LinkButtonGec_Click(object sender, EventArgs e)
{
Response.Redirect("KayitAdim4.aspx");
}
protected void LinkButton1ilerii_Click(object sender, EventArgs e)
{
if (cins == 0)
{
Label1.Visible = true;
}
else
{
Label1.Visible = false;
int id = (int)Session["ID"];
var kisi = db.Kullanicis.Where(k => k.kullaniciID == id).FirstOrDefault();
if (cins == 1)
{
kisi.cinsiyet = "Kadın";
}
else if (cins == 2)
{
kisi.cinsiyet = "Erkek";
}
db.SaveChanges();
Response.Redirect("KayitAdim4.aspx");
}
}
protected void LinkButton1Erkek_Click(object sender, EventArgs e)
{
cins += 2;
LinkButton1Erkek.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;
LinkButtonKadin.BorderStyle = System.Web.UI.WebControls.BorderStyle.NotSet;
Label1.Visible = false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MezunSistemiProjesi
{
public partial class SifremiUnuttum : System.Web.UI.Page
{
Model.MezunVsEntities db = new Model.MezunVsEntities();
//int UyeID;
//DateTime UyeZamani;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
var kisi = db.Kullanicis.Where(o => o.email ==txtePosta.Text).FirstOrDefault();
if (kisi!=null)
{
SmtpClient mlClient = new SmtpClient();
MailMessage mlMessage = new MailMessage();
mlMessage.To.Add(txtePosta.Text);
mlMessage.From = new MailAddress("<EMAIL>", "Şifre Hatırlatma");
mlMessage.Subject = "Mail İle Şifre Hatırlatma";
mlMessage.IsBodyHtml = true;
mlMessage.Body = "Sayın " + kisi.isim +" "+kisi.soyad+ "<br/>" + " Hesabınızın Mevcut Şifresi : " + kisi.sifre;
NetworkCredential guvenlikKarti = new NetworkCredential("codetech.destek", "4256123789");
mlClient.Credentials = guvenlikKarti;
mlClient.Port = 587;
mlClient.Host = "smtp.gmail.com";
mlClient.EnableSsl = true;
mlClient.Send(mlMessage);
LabelOnay.ForeColor = System.Drawing.Color.LimeGreen;
LabelOnay.Text = "Şifreniz E-posta Adresine gönderilmiştir.";
LabelOnay.Visible = true;
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
LabelOnay.ForeColor = System.Drawing.Color.OrangeRed;
LabelOnay.Text = "Girmiş Olduğunuz E-posta Adresi Hatalı!";
LabelOnay.Visible = true;
}
}
}
} | c7da7697911010cb26f3a5216139d3b702deb786 | [
"C#"
] | 16 | C# | MkemalSari/Mezun-Sistemi | 70688bd69bc2287d6620b81b9ec080b7d438e9da | 81a8d4b92a612fa571945db817981f29e1d001c0 |
refs/heads/master | <repo_name>KingsleyBell/anna_website<file_sep>/README.md
# <NAME>
Portfolio website for <NAME>
<file_sep>/app/static/js/contact.js
var quill, contactText;
function htmlDecode(input){
if (input.length == 0) {
return input;
}
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
$(document).ready(function () {
quill = new Quill('#snow-container-text', {
placeholder: "Contact text",
theme: "snow"
});
quill.clipboard.dangerouslyPasteHTML(htmlDecode(contactText));
$("#contact-form").on("submit", function () {
var myTextEditor = document.querySelector("#snow-container-text");
var textHtml = myTextEditor.children[0].innerHTML;
$("#text").val(textHtml);
});
});
<file_sep>/app/util.py
from datetime import datetime
import json
import os
from flask import Flask
application = Flask(__name__)
@application.context_processor
def inject_now():
return {'now': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')}
@application.context_processor
def inject_year():
return {'year': datetime.utcnow().year}
db_path = os.path.join(application.static_folder, 'db/db.json')
about_path = os.path.join(application.static_folder, 'db/about.json')
contact_path = os.path.join(application.static_folder, 'db/contact.json')
def get_section_by_id(db, section_id):
return [s for s in db if s['id'] == section_id][0]
def update_db_file(db_file_path, new_db):
with open(db_file_path, 'w') as db_write:
db_write.write(json.dumps(new_db))
def get_image_from_db(db, section_id, image_id):
section = get_section_by_id(db, section_id)
return [i for i in section["images"] if i["id"] == image_id][0]
def delete_image_file(filename):
upload_folder = os.path.join(application.static_folder, 'images/uploads')
os.remove(os.path.join(upload_folder, filename))<file_sep>/app/static/js/edit_section.js
var quill, sectionText;
function htmlDecode(input){
if (input.length == 0) {
return input;
}
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
$(document).ready(function () {
quill = new Quill('#snow-container', {
placeholder: "Section text here",
theme: "snow",
formats: ["header", "bold", "underline", "italic"],
});
quill.clipboard.dangerouslyPasteHTML(htmlDecode(sectionText));
$("#section-form").on("submit", function (e) {
if (quill.getLength() <= 1) {
$("#text").val("");
} else {
var myEditor = document.querySelector("#snow-container");
var html = myEditor.children[0].innerHTML;
$("#text").val(html);
}
});
// Jquery UI stuff
$(".edit-section-image").draggable();
$(".edit-section-image img").resizable({
aspectRatio: true
});
});
<file_sep>/app/static/js/about.js
var quill, aboutHeading, aboutText;
function htmlDecode(input){
if (input.length == 0) {
return input;
}
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
$(document).ready(function () {
quill = new Quill('#snow-container-heading', {
placeholder: "About heading",
theme: "snow"
});
quill.clipboard.dangerouslyPasteHTML(htmlDecode(aboutHeading));
quill = new Quill('#snow-container-text', {
placeholder: "About text",
theme: "snow"
});
quill.clipboard.dangerouslyPasteHTML(htmlDecode(aboutText));
$("#about-form").on("submit", function () {
var myHeadingEditor = document.querySelector("#snow-container-heading");
var myTextEditor = document.querySelector("#snow-container-text");
var headingHtml = myHeadingEditor.children[0].innerHTML;
var textHtml = myTextEditor.children[0].innerHTML;
$("#heading").val(headingHtml);
$("#text").val(textHtml);
});
});
<file_sep>/app/app.py
# Import routes
from routes import main
from routes import admin
from routes import ajax
from util import application
if __name__ == "__main__":
application.run(host='0.0.0.0', port=800)
<file_sep>/app/routes/main.py
import json
from flask import render_template
from util import about_path, contact_path, application, db_path, get_section_by_id
@application.route('/')
def home():
db = json.loads(open(db_path, 'r').read())
about = json.loads(open(about_path, 'r').read())
return render_template(
'index.html',
about=about,
db=db,
)
@application.route("/contact")
def contact():
contact_json = json.loads(open(contact_path, 'r').read())['text']
about = json.loads(open(about_path, 'r').read())
return render_template(
'contact.html',
contact=contact_json,
about=about
)
@application.route('/x/<string:section_id>/')
def display_section(section_id):
db = json.loads(open(db_path, 'r').read())
about = json.loads(open(about_path, 'r').read())
section = get_section_by_id(db, section_id)
return render_template(
'section.html',
section=section,
about=about
)
<file_sep>/app/routes/admin.py
import json
import os
import re
from flask import jsonify, redirect, render_template, request, url_for
from werkzeug.utils import secure_filename
from auth import requires_auth
from util import about_path, application, contact_path, db_path, delete_image_file, get_section_by_id, update_db_file
@application.route('/admin/', methods=['GET', 'POST'])
@requires_auth
def admin_sections():
db = json.loads(open(db_path, 'r').read())
if request.method == 'POST': # Delete section
section_id = request.form.get('section_id')
section = get_section_by_id(db, section_id)
for image in section['images']:
delete_image_file(image['url'])
db.remove(section)
update_db_file(db_path, db)
return jsonify({'success': True})
else:
return render_template('admin/edit_sections.html', db=db)
@application.route('/new_section/', methods=['GET', 'POST'])
@requires_auth
def new_section():
db = json.loads(open(db_path, 'r').read())
if request.method == 'POST':
section_name = request.form.get('section')
section_id = re.sub('[^A-Za-z0-9]+', '_', section_name).lower()
image_file = request.files.get('file')
file_extension = image_file.filename.split('.')[-1]
upload_folder = os.path.join(application.static_folder, 'images/uploads')
filename = secure_filename(str(section_id) + '.' + file_extension)
image_file.save(os.path.join(upload_folder, filename))
section_dict = {
'name': section_name,
'id': section_id,
"image_url": filename,
'text': '',
'images': []
}
db.append(section_dict)
update_db_file(db_path, db)
return redirect(url_for('admin_sections'))
else:
return render_template('admin/new_section.html', db=db)
@application.route('/edit_section/<string:section_id>/', methods=['GET', 'POST'])
@requires_auth
def edit_section(section_id):
db = json.loads(open(db_path, 'r').read())
section = get_section_by_id(db, section_id)
if request.method == 'POST':
section_name = request.form.get('name')
section_id = re.sub('[^A-Za-z0-9]+', '_', section_name).lower()
section_text = request.form.get('text')
section['name'] = section_name
section['id'] = section_id
section['text'] = section_text
image_file = request.files.get('file')
if image_file:
file_extension = image_file.filename.split('.')[-1]
upload_folder = os.path.join(application.static_folder, 'images/uploads')
filename = secure_filename(str(section_id) + '.' + file_extension)
image_file.save(os.path.join(upload_folder, filename))
section["image_url"] = filename
update_db_file(db_path, db)
return redirect(url_for('admin_sections'))
else:
return render_template('admin/edit_section.html', section=section, db=db)
@application.route('/edit_section_images/<string:section_id>/', methods=['GET'])
@requires_auth
def edit_section_images(section_id):
db = json.loads(open(db_path, 'r').read())
section = get_section_by_id(db, section_id)
return render_template('admin/edit_section_images.html', section=section)
@application.route('/edit_image/<string:section_id>/<int:image_id>/', methods=['GET', 'POST'])
@requires_auth
def edit_image(section_id, image_id):
db = json.loads(open(db_path, 'r').read())
section = get_section_by_id(db, section_id)
image = [i for i in section['images'] if i['id'] == image_id][0]
if request.method == 'POST':
section_id = request.form.get('section')
title = request.form.get('title')
year = request.form.get('year')
width = request.form.get('width')
height = request.form.get('height')
materials = request.form.get('materials')
container_width = request.form.get('container_width')
display_width = request.form.get('display_width')
align = request.form.get('align')
db_section = [s for s in db if s['id'] == section_id][0]
if db_section != section:
db_section['images'].append(image)
section['images'].remove(image)
image["title"] = title
image["year"] = year
image["width"] = width
image["height"] = height
image["materials"] = materials
image["container_width"] = container_width
image["display_width"] = display_width
image["align"] = align
update_db_file(db_path, db)
return redirect(url_for('sections'))
else:
sections = [{"name": section["name"], "id": section['id']} for section in db]
return render_template(
'admin/edit_image.html',
image=image,
section=section['id'],
sections=sections
)
@application.route('/upload/<string:section_id>/', methods=['GET', 'POST'])
@requires_auth
def upload(section_id):
db = json.loads(open(db_path, 'r').read())
if request.method == 'POST':
image_ids = []
for s in db:
image_ids += [image['id'] for image in s['images']]
image_id = max(image_ids + [0]) + 1
section = get_section_by_id(db, section_id)
title = request.form.get('title')
if request.files.get('file').filename:
image_type = "image"
image_file = request.files.get('file')
file_extension = image_file.filename.split('.')[-1]
upload_folder = os.path.join(application.static_folder, 'images/uploads')
filename = secure_filename(str(image_id) + '.' + file_extension)
image_file.save(os.path.join(upload_folder, filename))
else:
image_type = "video"
filename = request.form.get('link')
image_dict = {
"id": image_id,
"url": filename,
"type": image_type,
"title": title,
"width": 25,
"top": 0,
"left": 0
}
section['images'].append(image_dict)
update_db_file(db_path, db)
return redirect(url_for('admin_sections'))
else:
sections = {section['name']: section['id'] for section in db}
return render_template('admin/upload.html', sections=sections, section=section_id)
@application.route('/admin_about/', methods=['GET', 'POST'])
@requires_auth
def admin_about():
about_json = json.loads(open(about_path, 'r').read())
if request.method == 'POST':
about_heading = request.form.get('heading')
about_txt = request.form.get('text')
background_colour = request.form.get('backgroundColour')
text_colour = request.form.get('textColour')
show_home_image = request.form.get('showHomeImage')
about_json['heading'] = about_heading
about_json['text'] = about_txt
about_json['background_colour'] = background_colour
about_json['text_colour'] = text_colour
about_json['show_home_image'] = show_home_image
update_db_file(about_path, about_json)
return redirect(url_for('admin_sections'))
else:
return render_template('admin/edit_about.html', about=about_json)
@application.route('/admin_contact/', methods=['GET', 'POST'])
@requires_auth
def admin_contact():
contact_json = json.loads(open(contact_path, 'r').read())
if request.method == 'POST':
contact_txt = request.form.get('text')
contact_json['text'] = contact_txt
update_db_file(contact_path, contact_json)
return redirect(url_for('admin_sections'))
else:
return render_template('admin/edit_contact.html', contact=contact_json)
@application.route('/new_home_image/', methods=['GET', 'POST'])
@requires_auth
def new_home_image():
if request.method == 'POST':
image_file = request.files.get('file')
upload_folder = os.path.join(application.static_folder, 'images')
filename = "home.jpg"
image_file.save(os.path.join(upload_folder, filename))
return redirect(url_for('admin_sections'))
else:
return render_template('admin/upload_file.html', form_label='New Home Image (must be jpg)')
<file_sep>/app/routes/ajax.py
import json
from flask import jsonify, request
from util import application, db_path, delete_image_file, get_image_from_db, get_section_by_id, update_db_file
@application.route('/submitCuration/<string:section_id>/', methods=['POST'])
def submit_curation(section_id):
db = json.loads(open(db_path, 'r').read())
images_str = request.form.get('images')
images = json.loads(images_str)
for image in images:
db_image = get_image_from_db(db, section_id, image["id"])
if db_image != image:
db_image["top"] = image["top"]
db_image["left"] = image["left"]
db_image["width"] = image["width"]
update_db_file(db_path, db)
return jsonify({'success': True})
@application.route('/delete_image/', methods=['POST'])
def delete_image():
section_id = request.form.get('section_id')
image_id = int(request.form.get('image_id'))
db = json.loads(open(db_path, 'r').read())
section = [s for s in db if s['id'] == section_id][0]
image = [i for i in section['images'] if i['id'] == image_id][0]
filename = image['url']
section['images'].remove(image)
delete_image_file(filename)
update_db_file(db_path, db)
return jsonify({'success': True})
@application.route('/cv')
def cv():
return application.send_static_file('pdf/CV.pdf')
@application.route('/shift_section_position', methods=['POST'])
def shift_section_position():
db = json.loads(open(db_path, 'r').read())
section_id = request.form.get('section_id')
shift = int(request.form.get('shift'))
section = get_section_by_id(db, section_id)
section_index = db.index(section)
if section_index == 0 and shift < 0: # can't shift up if at top
return jsonify({'success': False})
if section_index == len(db) - 1 and shift > 0: # Can't shift down if at bottom
return jsonify({'success': False})
db[section_index], db[section_index + shift] = db[section_index + shift], db[section_index]
with open(db_path, 'w') as db_write:
db_write.write(json.dumps(db))
return jsonify({'success': True})
@application.route('/shift_image_position', methods=['POST'])
def shift_image_position():
section_id = request.form.get('section_id')
image_id = int(request.form.get('image_id'))
shift = int(request.form.get('shift'))
db = json.loads(open(db_path, 'r').read())
section = [s for s in db if s['id'] == section_id][0]
image = [i for i in section['images'] if i['id'] == image_id][0]
image_index = section['images'].index(image)
if image_index == 0 and shift < 0: # can't shift up if at top
return jsonify({'success': False})
if image_index == len(section['images']) - 1 and shift > 0: # Can't shift down if at bottom
return jsonify({'success': False})
# swap sections
tmp = section['images'][image_index]
section['images'][image_index] = section['images'][image_index + shift]
section['images'][image_index + shift] = tmp
update_db_file(db_path, db)
return jsonify({'success': True})<file_sep>/app/static/js/index.js
$(document).ready(function() {
$("#home-link").click(function(e) {
e.preventDefault();
$(".section.active").removeClass("active");
$(".nav-link.active").removeClass("active");
$("#section-web-home").addClass("active");
});
$(".nav-link.nav-section").click(function(e) {
var targetId = e.target.id.split("-"),
linkId = targetId[targetId.length - 1];
$(".section.active").removeClass("active");
$(".nav-link.active").removeClass("active");
$("#section-" + linkId).addClass("active");
$(this).addClass("active");
});
$(".menu-nav").click(function(e) {
var targetId = e.target.href.split("-"),
linkId = targetId[targetId.length - 1];
$("#section-" + linkId + " .menu-nav.active.show").removeClass("active show");
});
$(".section-expand").click(function(e) {
let item = $(this).children("span:first");
invertCollapse(item);
});
function invertCollapse(item) {
if (item.html() == "+") {
item.html("-")
}
else {
item.html("+")
}
}
});
| 40ee15d7da73fe668fbec61d8f52491e8c09229e | [
"Markdown",
"Python",
"JavaScript"
] | 10 | Markdown | KingsleyBell/anna_website | 280ab439ca2351ba204bb6117748d537af03e8b1 | a91ea87839718aabda04d5e41b3e7a07177eae12 |
refs/heads/master | <file_sep>#!/usr/bin/bash
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
CACERT="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
/opt/jenkins-dreamer/dreamer.sh --cacert ${CACERT} -H "openshift.default.svc.cluster.local" -t ${TOKEN} -n ${DREAMER_NAMESPACE} --idle-after ${IDLE_AFTER} --wait ${WAIT_TIME} | fa3cbda5bae045e5492ff8f45394b54f0be310a2 | [
"Shell"
] | 1 | Shell | jfchevrette/jenkins-dreamer | 3eefa712146376404e7a745b2e109f32ccaa316f | 1e32f2c52d38e8e46400c547046bd8a20bc1baff |
refs/heads/master | <repo_name>Poncholay/TekDefense<file_sep>/README.md
# TekDefense
Tower Defense in C using SDL
<file_sep>/include/functions.h
/*
* functions.h for functions in /home/wilmot_g/Tower/include
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:42:54 2015 <NAME>
** Last update Sat Jan 2 15:12:18 2016 Poncholay
*/
#ifndef FUNCTION_H_
# define FUNCTION_H_
# include "defines.h"
t_paths *process_paths(t_map *map);
SDL_Surface *get_preview(t_map map, t_assets *assets, int type);
SDL_Surface *which_terrain(t_assets *assets, int **terrain, int i, int j);
char *concatenate(char *str1, char *str2, char separator);
char *get_gif(char *name, SDL_Surface *gif[81]);
char *get_next_line(const int fd);
void *load_texture(char *path, SDL_Surface **texture);
void *my_puterr(char *str, void *error);
int *int_tab(char *str);
t_curve curves(int which);
int get_textures(t_assets *assets);
int choose_map(t_map *map, t_assets *assets);
int get_assets(t_assets *assets);
int my_puterr_int(char *str, int error);
int menu(t_assets *assets);
int match(char *str1, char *str2);
int is_blocked(t_map *map, int i, int j, int which);
int next_spawn_point(t_map *map, int pos[2], int reset);
int lagrange(int xval, t_curve curve);
float distance(int ptn[2], int ptn2[2]);
void get_fortress_pos(t_map *map);
void free_int_tab(int **tab);
void draw_line(t_line coords, SDL_Surface *screen, Uint32 color);
void play_game(t_assets *assets, UNUSED t_stats *stats);
void show_maps(t_maps *maps);
void show_menu(t_assets *assets, int *window, int end, int play);
void map_editor(t_assets *assets);
void play_game(t_assets *assets, t_stats *stats);
void init_stats(t_stats *stats);
void free_tab(char **tab);
void free_maps(t_maps *maps);
void free_map(t_map *map);
void show_stats(t_stats *stats);
void move_units(t_units **units, t_map *map, int *update, t_paths *paths, int *hp);
void free_units(t_units *units);
void spawn_units(t_units **units, t_map *map, int *update, int reset);
#endif /* !FUNCTION_H_ */
<file_sep>/src/match.c
/*
** match.c for match in /home/wilmot_g/my_select
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Tue Dec 30 15:55:11 2014 <NAME>
** Last update Mon Jun 15 18:51:03 2015 <NAME>
*/
#include "tower.h"
int match(char *str1, char *str2)
{
int i;
if (str1 == NULL || str2 == NULL)
return (0);
i = 0;
if (strlen(str1) == strlen(str2))
{
while (str1[i] && str2[i])
{
if (str1[i] == str2[i])
i = i + 1;
else
return (0);
}
return (1);
}
else
return (0);
}
<file_sep>/src/menu.c
/*
** menu.c for menu in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:58:46 2015 <NAME>
** Last update Fri Jul 10 16:12:50 2015 <NAME>
*/
#include "tower.h"
void check_buttons(SDL_Event *ev, int *play, int *end, int *window)
{
int pos_play[2];
int pos_create[2];
int pos_exit[2];
pos_play[0] = 100;
pos_play[1] = 333;
pos_create[0] = 400;
pos_create[1] = 633;
pos_exit[0] = 700;
pos_exit[1] = 933;
if (ev->type == SDL_MOUSEBUTTONDOWN && ev->button.button == SDL_BUTTON_LEFT && ev->button.y > pos_play[0] && ev->button.y < pos_play[1])
{
*play = 1;
*window = 2;
}
else if (ev->button.y > pos_play[0] && ev->button.y < pos_play[1])
*window = 2;
else if (ev->type == SDL_MOUSEBUTTONDOWN && ev->button.button == SDL_BUTTON_LEFT && ev->button.y > pos_create[0] && ev->button.y < pos_create[1])
*window = 1;
else if (ev->button.y > pos_create[0] && ev->button.y < pos_create[1])
*window = 3;
else if (ev->type == SDL_MOUSEBUTTONDOWN && ev->button.button == SDL_BUTTON_LEFT && ev->button.y > pos_exit[0] && ev->button.y < pos_exit[1])
{
*window = 4;
*end = 1;
}
else if (ev->button.y > pos_exit[0] && ev->button.y < pos_exit[1])
*window = 4;
else
*window = 0;
}
void events_menu(int *play, int *end, int *window)
{
SDL_Event ev;
int pos[2];
ev.type = 0;
pos[0] = 1550;
pos[1] = 1850;
SDL_PollEvent(&ev);
if ((ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_ESCAPE) || ev.type == SDL_QUIT)
*end = 1;
if (ev.type == SDL_MOUSEMOTION || (ev.type == SDL_MOUSEBUTTONDOWN && ev.button.button == SDL_BUTTON_LEFT))
{
if (ev.button.x > pos[0] && ev.button.x < pos[1])
check_buttons(&ev, play, end, window);
else
*window = 0;
}
}
void show_menu(t_assets *assets, int *window, int end, int play)
{
SDL_Rect pos;
pos.x = 0;
pos.y = 0;
SDL_BlitSurface(assets->menu.background, NULL, assets->screen, &pos);
pos.x = 1550;
pos.y = 100;
if (*window == 2)
SDL_BlitSurface(assets->menu.play_hover, NULL, assets->screen, &pos);
else
SDL_BlitSurface(assets->menu.play, NULL, assets->screen, &pos);
if (play)
SDL_BlitSurface(((rand() % 2 == 0) ? assets->menu.blood2 : assets->menu.blood), NULL, assets->screen, &pos);
pos.y += 300;
if (*window == 3)
SDL_BlitSurface(assets->menu.create_hover, NULL, assets->screen, &pos);
else
SDL_BlitSurface(assets->menu.create, NULL, assets->screen, &pos);
if (*window == 1)
SDL_BlitSurface(((rand() % 2 == 0) ? assets->menu.blood2 : assets->menu.blood), NULL, assets->screen, &pos);
pos.y += 300;
if (*window == 4)
SDL_BlitSurface(assets->menu.exit_hover, NULL, assets->screen, &pos);
else
SDL_BlitSurface(assets->menu.exit, NULL, assets->screen, &pos);
if (end)
SDL_BlitSurface(((rand() % 2 == 0) ? assets->menu.blood2 : assets->menu.blood), NULL, assets->screen, &pos);
SDL_Flip(assets->screen);
if (play || end || *window == 1)
{
Mix_PlayChannel(-1, assets->sounds.menuclick, 0);
sleep(1);
}
if (*window == 1)
{
map_editor(assets);
*window = 0;
}
}
int menu(t_assets *assets)
{
t_stats stats;
int end;
int play;
int window;
end = 0;
play = 0;
window = 0;
srand(time(NULL));
while (!end)
{
if (Mix_PlayingMusic() != 1)
Mix_PlayMusic(assets->sounds.menumusic, -1);
events_menu(&play, &end, &window);
show_menu(assets, &window, end, play);
if (play)
{
init_stats(&stats);
play_game(assets, &stats);
show_stats(&stats);
play = 0;
Mix_PlayMusic(assets->sounds.menumusic, -1);
}
}
return (0);
}
<file_sep>/src/stats.c
/*
** stats.c for stats in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jun 14 19:43:10 2015 <NAME>
** Last update Mon Jun 15 01:09:12 2015 <NAME>
*/
#include "tower.h"
void init_stats(UNUSED t_stats *stats)
{
}
void show_stats(UNUSED t_stats *stats)
{
}
<file_sep>/src/choose_map.c
/*
** game.c for game in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jun 14 18:55:06 2015 <NAME>
** Last update Tue Jan 5 18:10:24 2016 <NAME>
*/
#include "tower.h"
int **my_realloc(int i, int **map)
{
int **new;
int j;
j = 0;
if ((new = malloc((i + 2) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
while (j < i)
{
new[j] = map[j];
j++;
}
new[j] = NULL;
if (map)
free(map);
return (new);
}
void get_fortress_pos(t_map *map)
{
int i;
int j;
for (i = 0; i < map->height; i++)
for(j = 0; j < map->width; j++)
if (map->objects[i][j] == 2)
{
map->fortress_pos[0] = i;
map->fortress_pos[1] = j;
return;
}
}
void *manage_errors(t_map **maps)
{
t_map *map;
int width[2];
int back;
int height[2];
int i;
int j;
map = *maps;
width[0] = -1;
height[0] = 0;
while (map->terrain[height[0]])
{
back = width[0];
width[0] = 0;
while (map->terrain[height[0]][width[0]] != -1)
width[0]++;
if (width[0] != back && back != -1)
{
free_map(map);
return (my_puterr("\033[01;31mMap is not a rectangle\033[0m\n", NULL));
}
height[0]++;
}
width[1] = -1;
height[1] = 0;
while (map->objects[height[1]])
{
back = width[1];
width[1] = 0;
while (map->objects[height[1]][width[1]] != -1)
width[1]++;
if (width[1] != back && back != -1)
{
free_map(map);
return (my_puterr("\033[01;31mMap is not a rectangle\033[0m\n", NULL));
}
height[1]++;
}
if (width[0] != width[1] || height[0] != height[1])
{
free_map(map);
return (my_puterr("\033[01;31mObjects and terrain aren't the same size\033[0m\n", NULL));
}
i = 0;
back = 0;
while (map->objects[i])
{
j = 0;
while (map->objects[i][j] != -1)
{
if (map->objects[i][j] == 2)
back++;
j++;
}
i++;
}
if (back != 1)
{
free_map(map);
return (my_puterr("\033[01;31mBad number of tower\033[0m\n", NULL));
}
if (width[0] < 6 || height[0] < 6)
{
free_map(map);
return (my_puterr("\033[01;31mMap is too small\033[0m\n", NULL));
}
back = 0;
for (i = 0; map->objects[i]; i++)
for (j = 0; map->objects[i][j] != -1; j++)
if (map->objects[i][j] == 5 && (i == 0 || j == 0 || j == width[0] - 1 || i == height[0] - 1))
back = 1;
if (!back)
{
free_map(map);
return (my_puterr("\033[01;31mNo entry for troops\033[0m\n", NULL));
}
return ("OK");
}
void *get_map(char *path, t_map *map)
{
int fd;
char *s;
int i;
printf("\n\033[01;37m-Processing %s\033[0m\n", path);
if ((path = concatenate("Maps/", path, 0)) == NULL)
return (my_puterr("Malloc : error\n", NULL));
if ((fd = open(path, O_RDWR)) == -1)
return (my_puterr("Open : error\n", NULL));
s = get_next_line(fd);
if (!match("Objects:", s))
{
if (s != NULL)
{
my_puterr("\033[01;31m\"", NULL);
my_puterr(s, NULL);
my_puterr("\"", NULL);
free(s);
}
else
my_puterr("\033[01;31mMalloc failed", NULL);
while ((s = get_next_line(fd)) != NULL)
free(s);
my_puterr(" :\nMissing \"Objects:\" instruction in ", NULL);
my_puterr(path, NULL);
free(path);
close(fd);
return (my_puterr("\033[0m\n", NULL));
}
free(s);
i = 0;
map->objects = NULL;
while ((s = get_next_line(fd)) != NULL && !match("Terrain:", s))
{
map->objects = my_realloc(i, map->objects);
map->objects[i++] = int_tab(s);
free(s);
}
map->objects[i] = NULL;
if (!match(s, "Terrain:"))
{
if (s != NULL)
{
my_puterr("\"", NULL);
my_puterr(s, NULL);
my_puterr("\"", NULL);
free(s);
}
else
my_puterr("\033[01;31mMalloc failed", NULL);
while ((s = get_next_line(fd)) != NULL)
free(s);
my_puterr("\nMissing \"Terrain:\" instruction in ", NULL);
my_puterr(path, NULL);
free(path);
close(fd);
return (my_puterr("\n", NULL));
}
free(s);
i = 0;
map->terrain = NULL;
while ((s = get_next_line(fd)) != NULL)
{
map->terrain = my_realloc(i, map->terrain);
map->terrain[i++] = int_tab(s);
free(s);
}
map->terrain[i] = NULL;
map->units = NULL;
free(path);
close(fd);
return (manage_errors(&map));
}
void add_in_maps(char *path, t_maps **maps)
{
t_maps *tmp;
t_maps *elem;
if ((elem = malloc(sizeof(t_maps))) == NULL)
return;
if (get_map(path, &elem->map) == NULL)
return;
puts("\033[01;32mOK\033[0m");
elem->next = NULL;
elem->prev = NULL;
if (*maps != NULL)
{
tmp = *maps;
while (tmp->next != NULL)
tmp = tmp->next;
elem->next = NULL;
elem->prev = tmp;
tmp->next = elem;
}
else
*maps = elem;
}
int check_extension(char *str)
{
int i;
i = 0;
while (str[i])
i++;
if (i == 0)
return (0);
i--;
if (i < 5)
return (0);
if (str[i] == 'p' && str[i - 1] == 'a' && str[i - 2] == 'm' && str[i - 3] == '.')
return (1);
return (0);
}
int get_maps(t_maps **maps)
{
struct dirent *dirent;
DIR *dir;
int nbr;
nbr = 0;
if ((dir = opendir("Maps")) == NULL)
return (-1);
while ((dirent = readdir(dir)) != NULL)
{
if (check_extension(dirent->d_name))
add_in_maps(dirent->d_name, maps);
nbr++;
}
closedir(dir);
return (1);
}
void show_maps(t_maps *maps)
{
int k;
int i;
int j;
k = 0;
puts("");
while (maps != NULL)
{
printf("Map n°%d\n", k++);
i = 0;
while (maps->map.terrain[i])
{
j = 0;
while (maps->map.terrain[i][j] != -1)
printf("%d ", maps->map.terrain[i][j++]);
i++;
puts("");
}
puts("");
i = 0;
while (maps->map.objects[i])
{
j = 0;
while (maps->map.objects[i][j] != -1)
printf("%d ", maps->map.objects[i][j++]);
i++;
puts("");
}
puts("");
i = 0;
while (maps->map.units[i])
{
j = 0;
while (maps->map.units[i][j] != -1)
printf("%d ", maps->map.units[i][j++]);
i++;
puts("");
}
maps = maps->next;
if (maps != NULL)
puts("\n");
}
}
SDL_Surface *which_terrain(t_assets *assets, int **terrain, int i, int j)
{
int nb;
nb = terrain[i][j];
if (nb == 0)
return (assets->terrain.grass);
if (nb == 1)
return (assets->terrain.stone);
if (nb == 2)
return (assets->terrain.dirt);
if (nb == 3)
return (assets->terrain.darkstone);
if (nb == 4)
return (assets->terrain.riverbed);
return (NULL);
}
SDL_Surface *which_objects(t_assets *assets, int **terrain, int i, int j, int *is_fortress)
{
int nb;
nb = terrain[i][j];
if (nb == 2)
{
*is_fortress = 1;
return (assets->buildings.fortress);
}
if (nb == 3)
return (assets->terrain.tree);
if (nb == 4)
return (assets->terrain.bush);
return (NULL);
}
SDL_Surface *get_preview(t_map map, t_assets *assets, int type)
{
SDL_Surface *preview;
SDL_Surface *tile;
SDL_Surface *tile2;
SDL_Surface *tile3;
SDL_Surface *frame;
SDL_Rect pos;
double scale_x;
double scale_y;
int i;
int j;
int width;
int height;
int is_fortress;
Uint32 color;
t_line coords;
for (height = 0; map.terrain[height]; height++);
for (width = 0; map.terrain[0][width] != -1; width++);
preview = SDL_CreateRGBSurface(SDL_HWSURFACE, ((type == 0) ? PREVIEW : MINIMAP), ((type == 0) ? PREVIEW : MINIMAP), BPP, 0, 0, 0, 0);
frame = SDL_CreateRGBSurface(SDL_HWSURFACE, ((type == 0) ? PREVIEW : MINIMAP) + ((type == 2) ? 4 : 10), ((type == 0) ? PREVIEW : MINIMAP) + ((type == 2) ? 4 : 10), BPP, 0, 0, 0, 0);
scale_x = (double)((double)((((type == 0) ? PREVIEW : MINIMAP) + 0) / width) / 100);
scale_y = (double)((double)((((type == 0) ? PREVIEW : MINIMAP) + 0) / height) / 100);
for (i = 0; map.terrain[i]; i++)
{
pos.y = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / height) * i));
for (j = 0; map.terrain[i][j] != -1; j++)
{
pos.x = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / width) * j));
tile = which_terrain(assets, map.terrain, i, j);
tile2 = SDL_CreateRGBSurface(SDL_HWSURFACE, 100, 100, BPP, 0, 0, 0, 0);
SDL_BlitSurface(tile, NULL, tile2, NULL);
tile3 = zoomSurface(tile2, scale_x, scale_y, 1);
SDL_FreeSurface(tile2);
SDL_BlitSurface(tile3, NULL, preview, &pos);
SDL_FreeSurface(tile3);
is_fortress = 0;
if (type == 0 && ((tile = which_objects(assets, map.objects, i, j, &is_fortress))) != NULL)
{
tile2 = SDL_CreateRGBSurface(SDL_HWSURFACE, ((is_fortress) ? 400 : 100), ((is_fortress) ? 714 : 100), BPP, 0, 0, 0, 0);
SDL_BlitSurface(tile, NULL, tile2, NULL);
tile3 = zoomSurface(tile2, scale_x, scale_y, 1);
SDL_SetColorKey(tile3, SDL_SRCCOLORKEY, SDL_MapRGB(tile2->format, 0, 0, 0));
SDL_FreeSurface(tile2);
pos.y = pos.y - tile3->h + (int)((float)100 * scale_y);
SDL_BlitSurface(tile3, NULL, preview, &pos);
pos.y = pos.y + tile3->h - (int)((float)100 * scale_y);
SDL_FreeSurface(tile3);
}
}
}
if (type == 2)
{
color = SDL_MapRGB(preview->format, 255, 255, 255);
coords.y1 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / height) * map.i));
coords.x1 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / width) * map.j));
coords.y2 = coords.y1;
coords.x2 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / width) * (map.j + ((map.j + 19 > width) ? (-map.j + width) : 19)))) - 1;
draw_line(coords, preview, color);
coords.y1++;
coords.y2++;
draw_line(coords, preview, color);
coords.x2 = coords.x1;
coords.y2 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / height) * (map.i + ((map.i + 9 > height) ? (-map.i + height) : 9)))) - 1;
draw_line(coords, preview, color);
coords.x1++;
coords.x2++;
draw_line(coords, preview, color);
coords.y1 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / height) * (map.i + ((map.i + 9 > height) ? (-map.i + height) : 9)))) - 1;
coords.x1 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / width) * (map.j + ((map.j + 19 > width) ? (-map.j + width) : 19)))) - 1;
coords.y2 = coords.y1;
coords.x2 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / width) * map.j));
draw_line(coords, preview, color);
coords.y1--;
coords.y2--;
draw_line(coords, preview, color);
coords.x2 = coords.x1;
coords.y2 = (int)((double)((double)(((type == 0) ? (double)PREVIEW : (double)MINIMAP) / height) * map.i));
draw_line(coords, preview, color);
coords.x1--;
coords.x2--;
draw_line(coords, preview, color);
}
pos.x = ((type == 2) ? 2 : 5);
pos.y = ((type == 2) ? 2 : 5);
SDL_BlitSurface(preview, NULL, frame, &pos);
SDL_FreeSurface(preview);
return (frame);
}
void display_map_choose(t_maps *maps, t_assets *assets)
{
SDL_Surface *preview;
SDL_Rect pos;
preview = get_preview(maps->map, assets, 0);
pos.x = (WIN_X - PREVIEW) / 2 - 5;
pos.y = (WIN_Y - PREVIEW) / 2 - 5;
SDL_BlitSurface(preview, NULL, assets->screen, &pos);
SDL_FreeSurface(preview);
}
void check_other_buttons(SDL_Event *ev, t_maps **maps)
{
if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_UP)
{
if ((*maps)->prev != NULL)
*maps = (*maps)->prev;
}
else if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_DOWN)
{
if ((*maps)->next != NULL)
*maps = (*maps)->next;
}
}
void *event_choose(int *choose, int *end, t_maps **maps, t_map *map)
{
SDL_Event ev;
int i;
int j;
int len;
ev.type = 0;
SDL_WaitEvent(&ev);
if ((ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_ESCAPE) || ev.type == SDL_QUIT)
*end = 1;
if (ev.type == SDL_KEYDOWN)
check_other_buttons(&ev, maps);
len = 0;
if (ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_RETURN)
{
for (i = 0; (*maps)->map.terrain[i]; i++)
for (len = 0; (*maps)->map.terrain[i][len] != -1; len++);
if ((map->terrain = malloc((i + 2) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
i = 0;
while ((*maps)->map.terrain[i])
{
j = 0;
if ((map->terrain[i] = malloc((len + 1) * sizeof(int))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
while ((*maps)->map.terrain[i][j] != -1)
{
map->terrain[i][j] = (*maps)->map.terrain[i][j];
j++;
}
map->terrain[i][j] = -1;
i++;
}
map->terrain[i] = NULL;
for (i = 0; (*maps)->map.terrain[i]; i++)
for (len = 0; (*maps)->map.terrain[i][len] != -1; len++);
if ((map->objects = malloc((i + 2) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
i = 0;
while ((*maps)->map.objects[i])
{
j = 0;
if ((map->objects[i] = malloc((len + 1) * sizeof(int))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
while ((*maps)->map.objects[i][j] != -1)
{
map->objects[i][j] = (*maps)->map.objects[i][j];
j++;
}
map->objects[i][j] = -1;
i++;
}
map->objects[i] = NULL;
*choose = 1;
}
return (NULL);
}
int choose_map(t_map *map, t_assets *assets)
{
t_maps *maps;
t_maps *tmp;
int choose;
int end;
maps = NULL;
choose = 0;
end = 0;
printf("\n\033[01;37mProcessing maps :\033[0m\n");
if (get_maps(&maps) == -1)
return (my_puterr_int("Could not get maps\n", -1));
if ((tmp = maps) == NULL)
return (0);
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = maps;
maps->prev = tmp;
while (!choose && !end)
{
display_map_choose(maps, assets);
SDL_Flip(assets->screen);
event_choose(&choose, &end, &maps, map);
}
free_maps(maps);
return (choose);
}
<file_sep>/src/units.c
/*
** units.c for units in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Fri Jul 10 17:29:47 2015 <NAME>
** Last update Tue Jan 5 15:00:33 2016 <NAME>
*/
#include "tower.h"
int next_spawn_point(t_map *map, int pos[2], int reset)
{
static int i = 0;
static int j = 0;
if (reset)
{
i = 0;
j = 0;
return (0);
}
while (i < map->height)
{
while (j < map->width)
{
if (map->objects[i][j] == 5)
{
pos[0] = i;
pos[1] = j;
j++;
return (1);
}
j++;
}
j = 0;
i++;
}
i = 0;
j = 0;
return (0);
}
void add_in_units(t_units **units, int pos[2], int type, int id)
{
t_units *tmp;
t_units *elem;
if ((elem = malloc(sizeof(t_units))) == NULL)
return;
elem->next = elem;
elem->prev = elem;
elem->type = type;
elem->id = id;
elem->frame = 0;
elem->at_spawn = 1;
elem->moved = 0;
elem->pos[0] = pos[0];
elem->pos[1] = pos[1];
elem->pos_prev[0] = pos[0];
elem->pos_prev[1] = pos[1];
elem->pos_prev_anim[0] = pos[0];
elem->pos_prev_anim[1] = pos[1];
if (*units != NULL)
{
tmp = *units;
while (tmp->next != *units)
tmp = tmp->next;
elem->next = *units;
elem->prev = tmp;
tmp->next = elem;
(*units)->prev = elem;
}
else
*units = elem;
}
int change_anim(t_units *unit)
{
if (unit->pos[0] > unit->pos_prev[0])
return (10);
if (unit->pos[0] < unit->pos_prev[0])
return (30);
if (unit->pos[1] > unit->pos_prev[1])
return (0);
if (unit->pos[1] < unit->pos_prev[1])
return (20);
return (unit->frame);
}
int check_if_moved(t_units *units, int i, int j)
{
t_units *tmp;
if ((tmp = units->next) == units || tmp == NULL)
return (1);
while ((tmp->pos[0] != i || tmp->pos[1] != j) && tmp != units)
tmp = tmp->next;
if (tmp->pos[0] == i && tmp->pos[1] == j)
return (tmp->moved);
return (1);
}
void try_other_way(t_units *unit, t_map *map, int *update)
{
int tiles[4][2];
int i;
tiles[0][0] = unit->pos[0] - 1;
tiles[0][1] = unit->pos[1];
tiles[1][0] = unit->pos[0];
tiles[1][1] = unit->pos[1] + 1;
tiles[2][0] = unit->pos[0] + 1;
tiles[2][1] = unit->pos[1];
tiles[3][0] = unit->pos[0];
tiles[3][1] = unit->pos[1] - 1;
for (i = 0; i < 4; i++)
if (!is_blocked(map, tiles[i][0], tiles[i][1], 1) && (tiles[i][0] != unit->pos_prev[0] || tiles[i][1] != unit->pos_prev[1]) && !unit->moved)
{
unit->pos_prev[0] = unit->pos[0];
unit->pos_prev[1] = unit->pos[1];
unit->pos_prev_anim[0] = unit->pos[0];
unit->pos_prev_anim[1] = unit->pos[1];
map->units[unit->pos_prev[0]][unit->pos_prev[1]] = 0;
unit->pos[0] = tiles[i][0];
unit->pos[1] = tiles[i][1];
map->units[unit->pos[0]][unit->pos[1]] = unit->id;
unit->at_spawn = 0;
unit->frame = change_anim(unit);
*update = 1;
unit->moved = 1;
}
}
void move_unit(t_units *unit, t_map *map, int *update, t_paths *paths)
{
t_paths *tmp;
tmp = paths;
while ((tmp->pos[0] != unit->pos[0] || tmp->pos[1] != unit->pos[1]) && tmp->next != paths)
tmp = tmp->next;
if (tmp->pos[0] == unit->pos[0] && tmp->pos[1] == unit->pos[1])
{
if (!is_blocked(map, tmp->best_way[0], tmp->best_way[1], 1))
{
unit->pos_prev[0] = unit->pos[0];
unit->pos_prev[1] = unit->pos[1];
unit->pos_prev_anim[0] = unit->pos[0];
unit->pos_prev_anim[1] = unit->pos[1];
map->units[unit->pos_prev[0]][unit->pos_prev[1]] = 0;
unit->pos[0] = tmp->best_way[0];
unit->pos[1] = tmp->best_way[1];
map->units[unit->pos[0]][unit->pos[1]] = unit->id;
unit->at_spawn = 0;
unit->frame = change_anim(unit);
*update = 1;
unit->moved = 1;
}
else if (check_if_moved(unit, tmp->best_way[0], tmp->best_way[1]))
try_other_way(unit, map, update);
if (check_if_moved(unit, tmp->best_way[0], tmp->best_way[1]) && !unit->moved)
{
unit->moved = 1;
unit->pos_prev_anim[0] = unit->pos[0];
unit->pos_prev_anim[1] = unit->pos[1];
}
}
}
void remove_unit(t_units **unit)
{
t_units *next;
t_units *prev;
prev = (*unit)->prev;
next = (*unit)->next;
free(*unit);
prev->next = next;
next->prev = prev;
}
int kamikaze(t_units **unit, int *hp, t_units ***units)
{
t_units *new;
int change;
(*unit)->moved = 1;
change = (*unit == *(*units)) ? 1 : 0;
new = (*(*units))->next;
remove_unit(unit);
/* update stats */
(*hp)--;
*(*units) = (change) ? new : *(*units);
*units = (change) ? &(*(*units)) : *units;
return (1);
}
int is_on_fortress(t_units **unit, t_map *map, int *hp, t_units ***units)
{
if (map->fortress_pos[0] == (*unit)->pos[0] && map->fortress_pos[1] == (*unit)->pos[1] && (*unit)->moved == 0)
return (kamikaze(unit, hp, units));
return (0);
}
void reset_movement(t_units *units)
{
t_units *tmp;
if ((tmp = units->next) == NULL)
return;
while (tmp != units)
{
tmp->moved = 0;
tmp = tmp->next;
}
tmp->moved = 0;
}
int check_movement(t_units *units)
{
t_units *tmp;
if ((tmp = units->next) == NULL)
return (1);
while (tmp != units)
{
if (!tmp->moved)
return (0);
tmp = tmp->next;
}
if (!tmp->moved)
return (0);
return (1);
}
void move_units(t_units **units, t_map *map, int *update, t_paths *paths, int *hp)
{
t_units *tmp;
if (*units != NULL)
{
reset_movement(*units);
while (*units && !check_movement(*units))
{
tmp = *units;
while (tmp && tmp != (*units)->prev)
{
if (tmp && !is_on_fortress(&tmp, map, hp, &units) && tmp->moved == 0)
move_unit(tmp, map, update, paths);
if (tmp)
tmp = tmp->next;
}
if (tmp && !is_on_fortress(&tmp, map, hp, &units) && tmp->moved == 0)
move_unit(tmp, map, update, paths);
}
}
}
void spawn_units(t_units **units, t_map *map, int *update, int reset)
{
static int spawned = 0;
static int wave = 1;
static int id = 1;
int pos[2];
if (reset)
{
spawned = 0;
wave = 1;
id = 1;
return;
}
if (spawned >= 0)
while (next_spawn_point(map, pos, 0))
if (!is_blocked(map, pos[0], pos[1], 1))
{
add_in_units(units, pos, KNIGHT + wave % 6, id);
map->units[pos[0]][pos[1]] = id++;
*update = 1;
}
spawned++;
if (spawned == lagrange(wave, curves(UNITS_NBR)))
{
spawned = -30 + (int)sqrt(wave);
wave++;
}
}
<file_sep>/src/free.c
/*
** free.c for free in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Mon Jun 15 18:28:10 2015 <NAME>
** Last update Tue Jul 7 11:27:20 2015 <NAME>
*/
#include "tower.h"
void free_int_tab(int **tab)
{
int i;
i = 0;
while (tab && tab[i])
free(tab[i++]);
if (tab)
free(tab);
}
void free_map(t_map *map)
{
if (map->objects)
free_int_tab(map->objects);
if (map->terrain)
free_int_tab(map->terrain);
if (map->units)
free_int_tab(map->units);
free(map);
}
void free_maps(t_maps *maps)
{
t_maps *tmp;
t_maps *tmp2;
if (maps == NULL)
return;
tmp = maps->next;
while (tmp != maps)
{
if (tmp->map.objects)
free_int_tab(tmp->map.objects);
if (tmp->map.terrain)
free_int_tab(tmp->map.terrain);
if (tmp->map.units)
free_int_tab(tmp->map.units);
tmp2 = tmp;
tmp = tmp->next;
free(tmp2);
}
if (maps->map.objects)
free_int_tab(maps->map.objects);
if (maps->map.terrain)
free_int_tab(maps->map.terrain);
if (maps->map.units)
free_int_tab(maps->map.units);
free(maps);
}
void free_units(t_units *units)
{
t_units *tmp;
t_units *tmp2;
if (units == NULL)
return;
tmp = units->next;
while (tmp != units)
{
tmp2 = tmp;
tmp = tmp->next;
free(tmp2);
}
free(units);
}
void free_tab(char **tab)
{
int i;
i = 0;
while (tab && tab[i])
free(tab[i++]);
if (tab)
free(tab);
}
<file_sep>/src/paths.c
/*
1;3803;0c** game.c for game in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Tue Dec 26 14:55:00 2015 Poncholay
** Last update Sun Dec 27 22:13:00 2015 Poncholay
*/
#include "tower.h"
int *init_ke(t_map *map, t_paths *path)
{
int *ke;
int i;
if ((ke = malloc((map->nb_path + 2) * sizeof(int ))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (i = 0; i < map->nb_path + 2; i++)
ke[i] = 0;
ke[0] = path->id;
return (ke);
}
void add_or_remove_from_ke(int id, int which, int *ke)
{
int i;
i = 0;
if (which == 0)
{
while (ke[i + 1])
{
ke[i] = ke[i + 1];
i++;
}
ke[i] = '\0';
}
else if (which == 1)
{
while (ke[i])
i++;
ke[i++] = id;
ke[i] = '\0';
}
}
void set_list_on_ke(t_paths **paths, int id)
{
t_paths *tmp;
tmp = (*paths)->next;
while (tmp->id != id && tmp != *paths)
tmp = tmp->next;
if (tmp->id == id)
*paths = tmp;
}
float extract_path(int key, int *ke, t_paths *end, t_paths *start)
{
float len;
if (key == 0)
{
free(ke);
return (-1);
}
for (len = 1; end->id != start->id; len++)
set_list_on_ke(&end, end->visited_by);
return (len);
}
void reinit_paths(t_paths *paths)
{
t_paths *tmp;
tmp = paths;
while (tmp->next != paths)
{
tmp->visited = 0;
tmp = tmp->next;
}
tmp->visited = 0;
}
float pathfinding(t_paths *path, t_map *map)
{
t_paths *start;
int end;
int i;
int *ke;
end = 0;
start = path;
ke = init_ke(map, path);
reinit_paths(path);
path->visited = 1;
path->visited_by = path->id;
while (ke[0] && !end)
{
set_list_on_ke(&path, ke[0]);
add_or_remove_from_ke(0, 0, ke);
for (i = 0; path->neighboors[i] && !end; i++)
if (!(path->neighboors[i])->visited)
{
add_or_remove_from_ke((path->neighboors[i])->id, 1, ke);
(path->neighboors[i])->visited = 1;
(path->neighboors[i])->visited_by = path->id;
if ((path->neighboors[i])->pos[0] == map->fortress_pos[0] && (path->neighboors[i])->pos[1] == map->fortress_pos[1])
end = 1;
}
}
return (extract_path(end, ke, path, start));
}
float distance(int ptn[2], int ptn2[2])
{
return sqrt(pow(ptn2[1] - ptn[1], 2) + pow(ptn2[0] - ptn[0], 2));
}
void get_best_way(t_paths **path, t_map *map)
{
float best_len;
float len;
int best_way;
int i;
best_way = 0;
for (i = 0; (*path)->neighboors[i] != NULL; i++);
if (i == 1)
best_way = 0;
else
for (i = 0; (*path)->neighboors[i] != NULL; i++)
{
if (((*path)->neighboors[i])->pos[0] == map->fortress_pos[0] && ((*path)->neighboors[i])->pos[1] == map->fortress_pos[1])
{
best_len = 1;
best_way = i;
}
else if (i == 0)
{
best_len = pathfinding((*path)->neighboors[i], map);
best_way = i;
}
else
if ((distance(((*path)->neighboors[i])->pos, map->fortress_pos)) < best_len)
if ((len = pathfinding((*path)->neighboors[i], map)) < best_len && len != -1)
{
best_len = len;
best_way = i;
}
}
(*path)->best_way[0] = (*path)->neighboors[best_way]->pos[0];
(*path)->best_way[1] = (*path)->neighboors[best_way]->pos[1];
}
void add_neighboor(t_paths **paths, int i, int j)
{
t_paths *tmp;
int k;
if ((tmp = (*paths)->next) == NULL)
return;
while (tmp != *paths && (tmp->pos[0] != i || tmp->pos[1] != j))
tmp = tmp->next;
if (tmp->pos[0] == i && tmp->pos[1] == j)
{
for (k = 0; (*paths)->neighboors[k] != NULL && k < 4; k++);
if (k < 4 && (*paths)->neighboors[k] == NULL)
(*paths)->neighboors[k] = tmp;
}
}
void add_neighboors(t_map *map, t_paths **paths)
{
int tiles[4][2];
int i;
tiles[0][0] = (*paths)->pos[0] - 1;
tiles[1][0] = (*paths)->pos[0];
tiles[2][0] = (*paths)->pos[0] + 1;
tiles[3][0] = (*paths)->pos[0];
tiles[0][1] = (*paths)->pos[1];
tiles[1][1] = (*paths)->pos[1] + 1;
tiles[2][1] = (*paths)->pos[1];
tiles[3][1] = (*paths)->pos[1] - 1;
for (i = 0; i < 4; i++)
if (!is_blocked(map, tiles[i][0], tiles[i][1], 1))
add_neighboor(paths, tiles[i][0], tiles[i][1]);
}
void add_in_paths(t_paths **paths, int i, int j, int id)
{
t_paths *elem;
t_paths *tmp;
int k;
if ((elem = malloc(sizeof(t_paths))) == NULL)
return;
elem->visited = 0;
elem->id = id;
elem->pos[0] = i;
elem->pos[1] = j;
elem->next = elem;
for (k = 0; k < 4; k++)
elem->neighboors[k] = NULL;
if (*paths != NULL)
{
tmp = *paths;
while (tmp->next != *paths)
tmp = tmp->next;
elem->next = *paths;
tmp->next = elem;
}
else
*paths = elem;
}
t_paths *process_paths(t_map *map)
{
t_paths *paths;
t_paths *tmp;
int i;
int j;
int id;
paths = NULL;
id = 1;
map->nb_path = 0;
for (i = 0; i < map->height; i++)
for (j = 0; j < map->width; j++)
if (map->objects[i][j] == 1 || map->objects[i][j] == 5 || map->objects[i][j] == 2)
{
add_in_paths(&paths, i, j, id++);
map->nb_path++;
}
if (paths == NULL)
return (NULL);
tmp = paths->next;
while (tmp != paths)
{
add_neighboors(map, &tmp);
tmp = tmp->next;
}
add_neighboors(map, &paths);
if (PREPROCESS)
{
for (tmp = paths; tmp->next != paths; tmp = tmp->next)
if (tmp->pos[0] != map->fortress_pos[0] || tmp->pos[1] != map->fortress_pos[1])
get_best_way(&tmp, map);
if (tmp->pos[0] != map->fortress_pos[0] || tmp->pos[1] != map->fortress_pos[1])
get_best_way(&tmp, map);
puts("\n\033[01;32mProcessed Paths\033[0m\n");
}
return (paths);
}
<file_sep>/include/tower.h
/*
** tower.h for tower in /home/wilmot_g/Tower/include
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:46:30 2015 <NAME>
** Last update Sun Jun 14 17:41:57 2015 <NAME>
*/
#ifndef TOWER_H_
# define TOWER_H_
# include "structs.h"
# include "functions.h"
#endif /* !TOWER_H_ */
<file_sep>/src/game.c
/*
** game.c for game in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Tue Jul 7 14:55:00 2015 <NAME>
** Last update Fri Feb 12 14:04:04 2016 <NAME>
*/
#include "tower.h"
SDL_Surface *get_holed_tile(int nb, t_assets *assets)
{
if (nb == 0)
return (assets->terrain.grass_hole);
if (nb == 1)
return (assets->terrain.stone_hole);
if (nb == 2)
return (assets->terrain.dirt_hole);
if (nb == 3)
return (assets->terrain.darkstone_hole);
if (nb == 4)
return (assets->terrain.riverbed_hole);
return (NULL);
}
void get_doodad(int nb, int i, int j, t_assets *assets)
{
SDL_Rect pos;
SDL_Surface *doodad;
pos.x = 10 + j * 100;
pos.y = i * 100;
doodad = NULL;
if (nb == 2)
{
doodad = assets->buildings.fortress;
pos.x -= doodad->w / 3;
pos.y += 70;
}
else if (nb == 3)
doodad = assets->terrain.tree;
else if (nb == 4)
doodad = assets->terrain.bush;
if (doodad != NULL)
{
pos.y -= (doodad->h - 50);
SDL_BlitSurface(doodad, NULL, assets->screen, &pos);
}
}
void draw_units(int nb, int i, int j, t_assets *assets, int k, t_units *units)
{
SDL_Rect pos;
SDL_Surface *unit;
t_units *tmp;
pos.x = 10 + j * 100;
pos.y = i * 100;
unit = NULL;
if (nb > 0)
{
if ((tmp = units) == NULL)
return;
while (tmp->id != nb && tmp->next != units)
tmp = tmp->next;
if (tmp->id != nb)
return;
if (tmp->type == BOWMAN)
unit = assets->anims.bowman[k + tmp->frame];
else if (tmp->type == KNIGHT)
unit = assets->anims.knight[k + tmp->frame];
else if (tmp->type == LONGBOWMAN)
unit = assets->anims.longbowman[k + tmp->frame];
else if (tmp->type == PIKEMAN)
unit = assets->anims.pikeman[k + tmp->frame];
else if (tmp->type == SOLDIER)
unit = assets->anims.soldier[k + tmp->frame];
else if (tmp->type == MANGUDAI)
unit = assets->anims.mangudai[k + tmp->frame];
if (tmp->pos_prev_anim[0] > tmp->pos[0])
pos.y += (10 - k) * 10;
if (tmp->pos_prev_anim[0] < tmp->pos[0])
pos.y -= (10 - k) * 10;
if (tmp->pos_prev_anim[1] > tmp->pos[1])
pos.x += (10 - k) * 10;
if (tmp->pos_prev_anim[1] < tmp->pos[1])
pos.x -= (10 - k) * 10;
}
else if (nb <= ANGMAR && nb >= WOODEN)
{
if (nb == ANGMAR)
unit = assets->buildings.tower_angmar;
if (nb == ORC)
unit = assets->buildings.tower_orc;
if (nb == GOBLIN)
unit = assets->buildings.tower_goblin;
if (nb == STONE)
unit = assets->buildings.tower_stone;
if (nb == WOODEN)
unit = assets->buildings.tower_wooden;
pos.y -= unit->h - 100;
}
if (unit != NULL)
SDL_BlitSurface(unit, NULL, assets->screen, &pos);
}
void get_tile(t_map *map, int i, int j, t_assets *assets)
{
SDL_Rect pos;
int tiles[5];
int collide;
tiles[0] = map->terrain2[i][j];
tiles[1] = (i != 0) ? map->terrain2[i - 1][j] : -1;
tiles[2] = (j != 18) ? map->terrain2[i][j + 1] : -1;
tiles[3] = (i != 8) ? map->terrain2[i + 1][j] : -1;
tiles[4] = (j != 0) ? map->terrain2[i][j - 1] : -1;
pos.x = 10 + j * 100;
pos.y = i * 100;
collide = 0;
if (tiles[0] != 1 && tiles[0] != -2)
{
if (tiles[1] != -1 && tiles[0] != tiles[1])
{
SDL_BlitSurface(which_terrain(assets, map->terrain2, i - 1, j), NULL, assets->screen, &pos);
collide = 1;
}
else if (tiles[2] != -1 && tiles[0] != tiles[2])
{
SDL_BlitSurface(which_terrain(assets, map->terrain2, i, j + 1), NULL, assets->screen, &pos);
collide = 1;
}
else if (tiles[3] != -1 && tiles[0] != tiles[3])
{
SDL_BlitSurface(which_terrain(assets, map->terrain2, i + 1, j), NULL, assets->screen, &pos);
collide = 1;
}
else if (tiles[4] != -1 && tiles[0] != tiles[4])
{
SDL_BlitSurface(which_terrain(assets, map->terrain2, i, j - 1), NULL, assets->screen, &pos);
collide = 1;
}
}
if (!collide)
SDL_BlitSurface(which_terrain(assets, map->terrain2, i, j), NULL, assets->screen, &pos);
else
SDL_BlitSurface(get_holed_tile(map->terrain2[i][j], assets), NULL, assets->screen, &pos);
}
void draw_map(t_map *map, t_assets *assets, int frame, t_units *units)
{
SDL_Surface *minimap;
SDL_Rect pos;
int i;
int j;
minimap = get_preview(*map, assets, 2);
SDL_BlitSurface(assets->menu.stone, NULL, assets->screen, NULL);
for (i = 0; i < 10; i++)
for (j = 0; j < 20; j++)
{
if (i < 9 && j < 19)
{
get_tile(map, i, j, assets);
get_doodad(map->objects2[i][j], i, j, assets);
}
draw_units(map->units2[((i) ? i - 1 : i)][((j) ? j - 1 : j)], ((i) ? i - 1 : i) , ((j) ? j - 1 : j), assets, frame, units);
}
pos.x = WIN_X - 190;
pos.y = WIN_Y - 180;
SDL_BlitSurface(minimap, NULL, assets->screen, &pos);
SDL_Flip(assets->screen);
SDL_FreeSurface(minimap);
}
void events_graphic(int *end, t_map *map, SDL_Event *ev, int *update)
{
int pos[4];
if ((ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_ESCAPE) || ev->type == SDL_QUIT)
*end = 1;
if (ev->type == SDL_KEYDOWN)
{
if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_UP && map->i > 0)
{
(map->i)--;
*update = 1;
}
else if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_DOWN && map->i + 10 < map->height)
{
(map->i)++;
*update = 1;
}
else if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_RIGHT && map->j + 19 < map->width)
{
(map->j)++;
*update = 1;
}
else if (ev->type == SDL_KEYDOWN && ev->key.keysym.sym == SDLK_LEFT && map->j > 0)
{
(map->j)--;
*update = 1;
}
}
if (ev->type == SDL_MOUSEBUTTONDOWN)
{
pos[0] = 10;
pos[1] = WIN_X - 10;
pos[2] = 0;
pos[3] = WIN_Y - 180;
if (ev->button.x > pos[0] && ev->button.x < pos[1] && ev->button.y > pos[2] && ev->button.y < pos[3])
{
if (ev->button.button == SDL_BUTTON_WHEELUP && map->i > 0)
{
(map->i)--;
*update = 1;
}
else if (ev->button.button == SDL_BUTTON_WHEELDOWN && map->i + 10 < map->height)
{
(map->i)++;
*update = 1;
}
else if (ev->button.button == SDL_BUTTON_X1 && map->j > 0)
{
(map->j)--;
*update = 1;
}
else if (ev->button.button == SDL_BUTTON_X2 && map->j + 19 < map->width)
{
(map->j)++;
*update = 1;
}
}
}
}
int is_blocked(t_map *map, int i, int j, int which)
{
if (i < 0 || j < 0)
return (1);
if (i >= ((which == 0) ? 10 : map->height) || j >= ((which == 0) ? 19 : map->width))
return (1);
if (((which == 0) ? map->objects2[i][j] : map->objects[i][j]) == 2)
return (0);
if (which == 0 && map->terrain2[i][j] == 1)
return (1);
if (which == 0 && map->objects2[i][j] != 0)
return (1);
if (which == 1 && map->objects[i][j] != 1 && map->objects[i][j] != 5)
return (1);
if (((which == 0) ? map->terrain2[i][j] : map->terrain[i][j]) == 3 ||
((which == 0) ? map->units2[i][j] : map->units[i][j]) != 0)
return (1);
return (0);
}
void events_game(t_map *map, SDL_Event *ev, int *update)
{
int i;
int j;
int pos[4];
if (ev->type == SDL_MOUSEBUTTONDOWN && ev->button.button == SDL_BUTTON_LEFT)
{
pos[0] = 10;
pos[1] = WIN_X - 10;
pos[2] = 0;
pos[3] = WIN_Y - 180;
if (ev->button.x > pos[0] && ev->button.x < pos[1] && ev->button.y > pos[2] && ev->button.y < pos[3])
{
i = (ev->button.y) / 100;
j = (ev->button.x - 10) / 100;
if (i < 9 && j < 19 && !is_blocked(map, i, j, 0))
{
/* Test */
map->units[i + map->i][j + map->j] = ANGMAR - rand() % 5;
*update = 1;
}
}
}
}
void update_maps(t_map *map)
{
int i;
int j;
for (i = map->i; i < 9 + map->i; i++)
{
for (j = map->j; j < 19 + map->j; j++)
{
if (i < map->height && j < map->width)
map->terrain2[i - map->i][j - map->j] = map->terrain[i][j];
else
map->terrain2[i - map->i][j - map->j] = -2;
}
map->terrain2[i - map->i][j - map->j] = -1;
}
for (i = map->i; i < 9 + map->i; i++)
{
for (j = map->j; j < 19 + map->j; j++)
{
if (i < map->height && j < map->width)
map->objects2[i - map->i][j - map->j] = map->objects[i][j];
else
map->objects2[i - map->i][j - map->j] = -2;
}
map->objects2[i - map->i][j - map->j] = -1;
}
for (i = map->i; i < 9 + map->i; i++)
{
for (j = map->j; j < 19 + map->j; j++)
{
if (i < map->height && j < map->width)
map->units2[i - map->i][j - map->j] = map->units[i][j];
else
map->units2[i - map->i][j - map->j] = 0;
}
map->units2[i - map->i][j - map->j] = -1;
}
}
void start_game(t_map *map, UNUSED t_stats *stats, t_assets *assets)
{
int frame;
int win;
int end;
int update;
/* int t_prev; */
/* int t; */
int hp;
SDL_Event ev;
t_units *units;
t_paths *paths;
units = NULL;
Mix_PlayMusic(assets->sounds.gamemusic, -1);
win = 0;
end = 0;
frame = 0;
/* t_prev = SDL_GetTicks(); */
get_fortress_pos(map);
paths = process_paths(map);
spawn_units(NULL, NULL, &update, 1);
next_spawn_point(NULL, NULL, 1);
hp = NB_HP;
while (!win && !end)
{
ev.type = 0;
update = 0;
while (SDL_PollEvent(&ev))
if (ev.type == SDL_KEYDOWN || ev.type == SDL_MOUSEBUTTONDOWN)
{
events_game(map, &ev, &update);
events_graphic(&end, map, &ev, &update);
}
if (frame == 0)
{
move_units(&units, map, &update, paths, &hp);
spawn_units(&units, map, &update, 0);
}
if (update)
update_maps(map);
/* t = SDL_GetTicks(); */
draw_map(map, assets, frame, units);
/*while ((t - t_prev) < 100)
{
SDL_Delay(10);
t = SDL_GetTicks();
}
t_prev = t;*/
frame = ((frame == 9) ? 0 : frame + 1);
}
free_units(units);
}
void *fill_submap(t_map *map)
{
int i;
int j;
if ((map->terrain2 = malloc((11) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (i = 0; i < 9; i++)
{
if ((map->terrain2[i] = malloc((20) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (j = 0; j < 19; j++)
{
if (i < map->height && j < map->width)
map->terrain2[i][j] = map->terrain[i][j];
else
map->terrain2[i][j] = -2;
}
map->terrain2[i][j] = -1;
}
map->terrain2[i] = NULL;
if ((map->objects2 = malloc((11) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (i = 0; i < 9; i++)
{
if ((map->objects2[i] = malloc((20) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (j = 0; j < 19; j++)
{
if (i < map->height && j < map->width)
map->objects2[i][j] = map->objects[i][j];
else
map->objects2[i][j] = -2;
}
map->objects2[i][j] = -1;
}
map->objects2[i] = NULL;
if ((map->units = malloc((map->height + 1) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
if ((map->units2 = malloc((11) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (i = 0; i < map->height; i++)
{
if ((map->units[i] = malloc((map->width + 1) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (j = 0; j < map->width; j++)
map->units[i][j] = 0;
map->units[i][j] = -1;
}
map->units[i] = NULL;
for (i = 0; i < 9; i++)
{
if ((map->units2[i] = malloc((20) * sizeof(int *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
for (j = 0; j < 19; j++)
{
if (i < map->height && j < map->width)
map->units2[i][j] = 0;
else
map->units2[i][j] = -2;
}
map->units2[i][j] = -1;
}
map->units2[i] = NULL;
map->i = 0;
map->j = 0;
return (NULL);
}
void play_game(t_assets *assets, t_stats *stats)
{
t_map map;
if (choose_map(&map, assets) == 0)
return;
map.height = 0;
map.width = 0;
map.i = 0;
map.j = 0;
for (map.height = 0; map.terrain[map.height]; (map.height)++);
for (map.width = 0; map.terrain[0][map.width] != -1; (map.width)++);
fill_submap(&map);
start_game(&map, stats, assets);
if (map.objects)
free_int_tab(map.objects);
if (map.terrain)
free_int_tab(map.terrain);
if (map.units)
free_int_tab(map.units);
if (map.objects2)
free_int_tab(map.objects2);
if (map.terrain2)
free_int_tab(map.terrain2);
if (map.units2)
free_int_tab(map.units2);
}
<file_sep>/src/main.c
/*
** main.c for main in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:48:08 2015 <NAME>
** Last update Fri Jul 10 16:00:46 2015 <NAME>
*/
#include "tower.h"
void free_assets(t_assets *assets)
{
int i;
SDL_FreeSurface(assets->buildings.fortress);
SDL_FreeSurface(assets->buildings.tower_angmar);
SDL_FreeSurface(assets->buildings.tower_goblin);
SDL_FreeSurface(assets->buildings.tower_orc);
SDL_FreeSurface(assets->buildings.tower_stone);
SDL_FreeSurface(assets->buildings.tower_wooden);
SDL_FreeSurface(assets->terrain.darkstone);
SDL_FreeSurface(assets->terrain.darkstone_hole);
SDL_FreeSurface(assets->terrain.dirt);
SDL_FreeSurface(assets->terrain.dirt_hole);
SDL_FreeSurface(assets->terrain.grass);
SDL_FreeSurface(assets->terrain.grass_hole);
SDL_FreeSurface(assets->terrain.riverbed);
SDL_FreeSurface(assets->terrain.riverbed_hole);
SDL_FreeSurface(assets->terrain.stone);
SDL_FreeSurface(assets->terrain.stone_hole);
SDL_FreeSurface(assets->terrain.tree);
SDL_FreeSurface(assets->terrain.bush);
SDL_FreeSurface(assets->menu.exit);
SDL_FreeSurface(assets->menu.exit_hover);
SDL_FreeSurface(assets->menu.create);
SDL_FreeSurface(assets->menu.create_hover);
SDL_FreeSurface(assets->menu.play);
SDL_FreeSurface(assets->menu.play_hover);
SDL_FreeSurface(assets->menu.background);
SDL_FreeSurface(assets->menu.stone);
SDL_FreeSurface(assets->menu.back);
SDL_FreeSurface(assets->menu.up);
SDL_FreeSurface(assets->menu.down);
SDL_FreeSurface(assets->menu.blood);
SDL_FreeSurface(assets->menu.blood2);
i = 0;
while (i < 80)
{
SDL_FreeSurface(assets->anims.bowman[i]);
SDL_FreeSurface(assets->anims.longbowman[i]);
SDL_FreeSurface(assets->anims.knight[i]);
SDL_FreeSurface(assets->anims.mangudai[i]);
SDL_FreeSurface(assets->anims.pikeman[i]);
SDL_FreeSurface(assets->anims.soldier[i]);
i++;
}
Mix_FreeChunk(assets->sounds.menuclick);
Mix_FreeChunk(assets->sounds.newwave);
Mix_FreeChunk(assets->sounds.attack);
Mix_FreeChunk(assets->sounds.crumble);
Mix_FreeChunk(assets->sounds.lost);
Mix_FreeChunk(assets->sounds.flesh);
Mix_FreeChunk(assets->sounds.heavy);
Mix_FreeChunk(assets->sounds.missed);
Mix_FreeMusic(assets->sounds.gamemusic);
Mix_FreeMusic(assets->sounds.menumusic);
i = 0;
while (i < 4)
Mix_FreeChunk(assets->sounds.walk[i++]);
i = 0;
while (i < 6)
Mix_FreeChunk(assets->sounds.death[i++]);
}
int main()
{
t_assets assets;
if (SDL_Init(SDL_INIT_VIDEO) == -1)
return (my_puterr_int("Can't init SDL\n", -1));
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
if ((assets.screen = SDL_SetVideoMode(WIN_X, WIN_Y, BPP, SDL_HWSURFACE | SDL_NOFRAME)) == NULL)
return (my_puterr_int("Can't set video mode\n", -1));
SDL_WM_SetCaption("Tek Defence", NULL);
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) == -1)
return (my_puterr_int("Could not initiate sound module\n", -1));
Mix_AllocateChannels(100);
if (get_assets(&assets) != 1)
return (my_puterr_int("Could not load assets\n", -1));
SDL_EnableUNICODE(1);
/*
Mix_VolumeMusic(20);
*/
menu(&assets);
free_assets(&assets);
Mix_CloseAudio();
SDL_Quit();
return (0);
}
<file_sep>/src/lagrange.c
/*
** lagrange.c for tek_defense in /home/poncholay/Desktop/Tower/src
**
** Made by Poncholay
** Login <<EMAIL>>
**
** Started on Sun Dec 27 22:45:49 2015 Poncholay
** Last update Mon Dec 28 14:02:04 2015 Poncholay
*/
#include "tower.h"
t_curve curves(int which)
{
t_curve curve;
if (which == UNITS_NBR)
{
curve.x[0] = 1;
curve.y[0] = 5;
curve.x[1] = 4;
curve.y[1] = 8;
curve.x[2] = 10;
curve.y[2] = 10;
curve.x[3] = 15;
curve.y[3] = 15;
curve.len = 4;
}
if (which == TIME_BETWEEN_WAVES)
{
}
return (curve);
}
int lagrange(int xval, t_curve curve)
{
float temp;
float total;
int i;
int j;
total = 0.0;
for (i = 0; i < curve.len; i++)
{
temp = 1;
for(j = 0; j < curve.len; j++)
if (j != i)
temp = temp * (xval - curve.x[j]) / (curve.x[i] - curve.x[j]);
temp *= curve.y[i];
total += temp;
}
return ((int)total);
}
<file_sep>/src/map_editor.c
/*
** map_editor.c for map_editor in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jun 14 19:40:52 2015 <NAME>
** Last update Tue Jun 23 16:03:07 2015 <NAME>
*/
#include "tower.h"
void map_editor(UNUSED t_assets *assets)
{
puts("Map Editor not finished atm");
}
<file_sep>/src/int_tab.c
/*
** int_tab.c for int_tab in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Mon Jun 15 18:24:51 2015 <NAME>
** Last update Tue Jun 23 16:13:21 2015 <NAME>
*/
#include "tower.h"
int *int_tab(char *str)
{
char **tabl;
int *table;
int i;
int k;
int j;
i = 0;
j = 0;
if (!str)
return (NULL);
while (str && str[i] && str[i] == ' ')
i++;
if ((tabl = malloc((strlen(str) + 2) * sizeof(char *))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
while (str && str[i])
{
if ((tabl[j] = malloc((strlen(str) + 2) * sizeof(char))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
k = 0;
while (str[i] && str[i] != ' ')
tabl[j][k++] = str[i++];
tabl[j][k] = '\0';
while (str[i] && str[i] == ' ')
i++;
j++;
}
tabl[j] = NULL;
i = 0;
if ((table = malloc((j + 1) * sizeof(int))) == NULL)
return (my_puterr("Malloc : error\n", NULL));
while (tabl[i])
{
table[i] = atoi(tabl[i]);
i++;
}
table[i] = -1;
free_tab(tabl);
return (table);
}
<file_sep>/include/defines.h
/*
** defines.h for defines in /home/wilmot_g/Tower/include
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:44:51 2015 <NAME>
** Last update Sat Jan 2 15:09:34 2016 Poncholay
*/
#ifndef DEFINES_H_
# define DEFINES_H_
# include <SDL/SDL.h>
# include <SDL/SDL_image.h>
# include <SDL/SDL_mixer.h>
# include <SDL/SDL_rotozoom.h>
# include <unistd.h>
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <fcntl.h>
# include <stdarg.h>
# include <time.h>
# include <sys/ioctl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <dirent.h>
# define PREVIEW 500
# define MINIMAP 176
# define WIN_X 1920
# define WIN_Y 1080
# define BPP 32
# define UNUSED __attribute__((__unused__))
# define PREPROCESS 1
# define DIFFICULTY 5
# define NB_HP 20
# define UNITS_NBR 1
# define TIME_BETWEEN_WAVES 2
# define KNIGHT 42
# define PIKEMAN 43
# define SOLDIER 44
# define BOWMAN 45
# define LONGBOWMAN 46
# define MANGUDAI 47
# define ANGMAR -10
# define GOBLIN -11
# define ORC -12
# define STONE -13
# define WOODEN -14
#endif /* !DEFINES_H_ */
<file_sep>/include/structs.h
/*
** structs.h for structs in /home/wilmot_g/Tower/include
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sat Jun 13 15:45:58 2015 <NAME>
** Last update Tue Jan 5 14:59:14 2016 <NAME>
*/
#ifndef STRUCTS_H_
# define STRUCTS_H_
#include "defines.h"
typedef struct s_line
{
int x1;
int x2;
int y1;
int y2;
} t_line;
typedef struct s_anims
{
SDL_Surface *bowman[81];
SDL_Surface *pikeman[81];
SDL_Surface *soldier[81];
SDL_Surface *knight[81];
SDL_Surface *longbowman[81];
SDL_Surface *mangudai[81];
} t_anims;
typedef struct s_buildings
{
SDL_Surface *fortress;
SDL_Surface *tower_angmar;
SDL_Surface *tower_goblin;
SDL_Surface *tower_orc;
SDL_Surface *tower_stone;
SDL_Surface *tower_wooden;
} t_buildings;
typedef struct s_terrain
{
SDL_Surface *dirt;
SDL_Surface *dirt_hole;
SDL_Surface *grass;
SDL_Surface *grass_hole;
SDL_Surface *darkstone;
SDL_Surface *darkstone_hole;
SDL_Surface *riverbed;
SDL_Surface *riverbed_hole;
SDL_Surface *stone;
SDL_Surface *stone_hole;
SDL_Surface *bush;
SDL_Surface *tree;
} t_terrain;
typedef struct s_menu
{
SDL_Surface *exit_hover;
SDL_Surface *exit;
SDL_Surface *play_hover;
SDL_Surface *play;
SDL_Surface *create_hover;
SDL_Surface *create;
SDL_Surface *background;
SDL_Surface *blood;
SDL_Surface *blood2;
SDL_Surface *back;
SDL_Surface *up;
SDL_Surface *down;
SDL_Surface *stone;
} t_menu;
typedef struct s_sounds
{
Mix_Chunk *menuclick;
Mix_Chunk *newwave;
Mix_Chunk *walk[4];
Mix_Chunk *attack;
Mix_Chunk *crumble;
Mix_Chunk *lost;
Mix_Chunk *death[6];
Mix_Chunk *flesh;
Mix_Chunk *heavy;
Mix_Chunk *missed;
Mix_Music *menumusic;
Mix_Music *gamemusic;
} t_sounds;
typedef struct s_assets
{
t_anims anims;
t_buildings buildings;
t_terrain terrain;
t_menu menu;
t_sounds sounds;
SDL_Surface *screen;
} t_assets;
typedef struct s_map
{
int **terrain;
int **objects;
int **units;
int **terrain2;
int **objects2;
int **units2;
int i;
int j;
int width;
int height;
int fortress_pos[2];
int nb_path;
} t_map;
typedef struct s_stats
{
int units_killed;
int tower_built;
int upgrades;
int gold_earned;
} t_stats;
typedef struct s_curve
{
int x[10];
int y[10];
int len;
} t_curve;
typedef struct s_units t_units;
struct s_units
{
int type;
int frame;
int speed;
int health;
int id;
int at_spawn;
int moved;
int pos[2];
int pos_prev[2];
int pos_prev_anim[2];
t_units *next;
t_units *prev;
};
typedef struct s_paths t_paths;
struct s_paths
{
int id;
int visited;
int visited_by;
int pos[2];
int best_way[2];
t_paths *neighboors[4];
t_paths *next;
};
typedef struct s_maps t_maps;
struct s_maps
{
t_map map;
t_maps *next;
t_maps *prev;
};
#endif /* !STRUCTS_H_ */
<file_sep>/src/get_assets.c
/*
** get_assets.c for get_assets in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jun 14 16:25:59 2015 <NAME>
** Last update Thu Jul 9 10:33:45 2015 <NAME>
*/
#include "tower.h"
char *get_gif(char *name, SDL_Surface *gif[81])
{
int i;
char *tmp;
char *tmp2;
SDL_Surface *tmp_s;
SDL_Surface *tmp_s2;
i = 0;
if ((tmp2 = malloc((strlen(name) + 6) * sizeof(char))) == NULL)
return (NULL);
strcpy(tmp2, name);
if ((tmp = concatenate(tmp2, ".png", 0)) == NULL)
return (NULL);
free(tmp2);
while (i < 80)
{
tmp[strlen(name) - 1] = (i % 10) + 48;
tmp[strlen(name) - 2] = (i / 10) + 48;
if ((tmp_s = IMG_Load(tmp)) == NULL)
{
fprintf(stderr, "%s is missing\n", tmp);
free(tmp);
return (NULL);
}
if ((gif[i] = SDL_DisplayFormatAlpha(tmp_s)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(tmp_s);
if ((tmp_s2 = SDL_CreateRGBSurface(SDL_SWSURFACE, gif[i]->w, gif[i]->h, 32,
gif[i]->format->Rmask,
gif[i]->format->Gmask,
gif[i]->format->Bmask,
gif[i]->format->Amask)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
if ((tmp_s = SDL_DisplayFormatAlpha(tmp_s2)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(tmp_s2);
if (SDL_SetAlpha(gif[i], 0, gif[i]->format->alpha) == -1)
return (my_puterr("Could not apply transparency\n", NULL));
if (SDL_BlitSurface(gif[i], NULL, tmp_s, NULL) == -1)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(gif[i]);
gif[i] = tmp_s;
printf("\033[00;32m%s loaded\033[0m\n", tmp);
i++;
}
gif[i] = '\0';
free(tmp);
return ("OK");
}
void *load_texture(char *path, SDL_Surface **texture)
{
SDL_Surface *tmp;
SDL_Surface *tmp2;
if ((tmp = IMG_Load(path)) == NULL)
{
my_puterr(path, NULL);
return (my_puterr("is missing\n", NULL));
}
if ((*texture = SDL_DisplayFormatAlpha(tmp)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(tmp);
if ((tmp2 = SDL_CreateRGBSurface(SDL_SWSURFACE, (*texture)->w, (*texture)->h, 32,
(*texture)->format->Rmask,
(*texture)->format->Gmask,
(*texture)->format->Bmask,
(*texture)->format->Amask)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
if ((tmp = SDL_DisplayFormatAlpha(tmp2)) == NULL)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(tmp2);
if ((SDL_SetAlpha(*texture, 0, (*texture)->format->alpha)) == -1)
return (my_puterr("Could not apply transparency\n", NULL));
if (SDL_BlitSurface(*texture, NULL, tmp, NULL) == -1)
return (my_puterr("Could not apply transparency\n", NULL));
SDL_FreeSurface(*texture);
*texture = tmp;
printf("\033[00;32m%s loaded\033[0m\n", path);
return ("Ok");
}
int get_sounds(t_assets *assets)
{
if ((assets->sounds.menuclick = Mix_LoadWAV("assets/Sounds/MenuClick.wav")) == NULL)
return (my_puterr_int("Could not load MenuClick.wav\n", 0));
if ((assets->sounds.newwave = Mix_LoadWAV("assets/Sounds/NewWave.wav")) == NULL)
return (my_puterr_int("Could not load NewWave.wav\n", 0));
if ((assets->sounds.walk[0] = Mix_LoadWAV("assets/Sounds/Walk/Walk1.wav")) == NULL)
return (my_puterr_int("Could not load Walk1.wav\n", 0));
if ((assets->sounds.walk[1] = Mix_LoadWAV("assets/Sounds/Walk/Walk2.wav")) == NULL)
return (my_puterr_int("Could not load Walk2.wav\n", 0));
if ((assets->sounds.walk[2] = Mix_LoadWAV("assets/Sounds/Walk/Walk3.wav")) == NULL)
return (my_puterr_int("Could not load Walk3.wav\n", 0));
if ((assets->sounds.walk[3] = Mix_LoadWAV("assets/Sounds/Walk/Walk4.wav")) == NULL)
return (my_puterr_int("Could not load Walk4.wav\n", 0));
if ((assets->sounds.attack = Mix_LoadWAV("assets/Sounds/Fortress/Attack.wav")) == NULL)
return (my_puterr_int("Could not load Attack.wav\n", 0));
if ((assets->sounds.crumble = Mix_LoadWAV("assets/Sounds/Fortress/Crumble.wav")) == NULL)
return (my_puterr_int("Could not load Crumble.wav\n", 0));
if ((assets->sounds.lost = Mix_LoadWAV("assets/Sounds/Fortress/Lost.wav")) == NULL)
return (my_puterr_int("Could not load Lost.wav\n", 0));
if ((assets->sounds.flesh = Mix_LoadWAV("assets/Sounds/Arrow/Flesh.wav")) == NULL)
return (my_puterr_int("Could not load Flesh.wav\n", 0));
if ((assets->sounds.heavy = Mix_LoadWAV("assets/Sounds/Arrow/Heavy.wav")) == NULL)
return (my_puterr_int("Could not load Heavy.wav\n", 0));
if ((assets->sounds.missed = Mix_LoadWAV("assets/Sounds/Arrow/Missed.wav")) == NULL)
return (my_puterr_int("Could not load Missed.wav\n", 0));
if ((assets->sounds.death[0] = Mix_LoadWAV("assets/Sounds/Death/Death.wav")) == NULL)
return (my_puterr_int("Could not load Death.wav\n", 0));
if ((assets->sounds.death[1] = Mix_LoadWAV("assets/Sounds/Death/Death2.wav")) == NULL)
return (my_puterr_int("Could not load Death2.wav\n", 0));
if ((assets->sounds.death[2] = Mix_LoadWAV("assets/Sounds/Death/Death3.wav")) == NULL)
return (my_puterr_int("Could not load Death3.wav\n", 0));
if ((assets->sounds.death[3] = Mix_LoadWAV("assets/Sounds/Death/Death4.wav")) == NULL)
return (my_puterr_int("Could not load Death4.wav\n", 0));
if ((assets->sounds.death[4] = Mix_LoadWAV("assets/Sounds/Death/Death5.wav")) == NULL)
return (my_puterr_int("Could not load Death5.wav\n", 0));
if ((assets->sounds.death[5] = Mix_LoadWAV("assets/Sounds/Death/Death6.wav")) == NULL)
return (my_puterr_int("Could not load Death6.wav\n", 0));
if ((assets->sounds.menumusic = Mix_LoadMUS("assets/Sounds/MenuMusic.wav")) == NULL)
return (my_puterr_int("Could not load MenuMusic.wav\n", 0));
if ((assets->sounds.gamemusic = Mix_LoadMUS("assets/Sounds/GameMusic.wav")) == NULL)
return (my_puterr_int("Could not load GameMusic.wav\n", 0));
return (1);
}
int get_textures(t_assets *assets)
{
if (load_texture("assets/Fortress/Fortress2.png", &(assets->buildings.fortress)) == NULL ||
load_texture("assets/Towers/AngmarTower.png", &(assets->buildings.tower_angmar)) == NULL ||
load_texture("assets/Towers/GoblinTower.png", &(assets->buildings.tower_goblin)) == NULL ||
load_texture("assets/Towers/OrcTower.png", &(assets->buildings.tower_orc)) == NULL ||
load_texture("assets/Towers/StoneTower.png", &(assets->buildings.tower_stone)) == NULL ||
load_texture("assets/Towers/WoodenTower.png", &(assets->buildings.tower_wooden)) == NULL)
return (0);
if (load_texture("assets/Terrain/Darkstone.png", &(assets->terrain.darkstone)) == NULL ||
load_texture("assets/Terrain/Dirt.png", &(assets->terrain.dirt)) == NULL ||
load_texture("assets/Terrain/Grass.png", &(assets->terrain.grass)) == NULL ||
load_texture("assets/Terrain/RiverBed.png", &(assets->terrain.riverbed)) == NULL ||
load_texture("assets/Terrain/Stone.png", &(assets->terrain.stone)) == NULL ||
load_texture("assets/Terrain/DarkstoneHole.png", &(assets->terrain.darkstone_hole)) == NULL ||
load_texture("assets/Terrain/DirtHole.png", &(assets->terrain.dirt_hole)) == NULL ||
load_texture("assets/Terrain/GrassHole.png", &(assets->terrain.grass_hole)) == NULL ||
load_texture("assets/Terrain/RiverBedHole.png", &(assets->terrain.riverbed_hole)) == NULL ||
load_texture("assets/Terrain/StoneHole.png", &(assets->terrain.stone_hole)) == NULL)
return (0);
if (load_texture("assets/Background.png", &(assets->menu.background)) == NULL ||
load_texture("assets/Buttons/Exit.png", &(assets->menu.exit)) == NULL ||
load_texture("assets/Buttons/Create.png", &(assets->menu.create)) == NULL ||
load_texture("assets/Buttons/Play.png", &(assets->menu.play)) == NULL ||
load_texture("assets/Buttons/ExitHover.png", &(assets->menu.exit_hover)) == NULL ||
load_texture("assets/Buttons/CreateHover.png", &(assets->menu.create_hover)) == NULL ||
load_texture("assets/Buttons/PlayHover.png", &(assets->menu.play_hover)) == NULL ||
load_texture("assets/Buttons/Blood.png", &(assets->menu.blood)) == NULL ||
load_texture("assets/Buttons/Blood2.png", &(assets->menu.blood2)) == NULL ||
load_texture("assets/Buttons/Up.png", &(assets->menu.up)) == NULL ||
load_texture("assets/Buttons/Down.png", &(assets->menu.down)) == NULL ||
load_texture("assets/Buttons/Back.png", &(assets->menu.back)) == NULL ||
load_texture("assets/Background.jpg", &(assets->menu.stone)) == NULL)
return (0);
if (load_texture("assets/Trees/Tree.png", &(assets->terrain.tree)) == NULL ||
load_texture("assets/Trees/Bush.png", &(assets->terrain.bush)) == NULL)
return (0);
return (get_sounds(assets));
}
int get_assets(t_assets *assets)
{
if (get_gif("assets/Units/Archer/frame_000", assets->anims.bowman) == NULL ||
get_gif("assets/Units/ArcLong/frame_000", assets->anims.longbowman) == NULL ||
get_gif("assets/Units/Cavalier/frame_000", assets->anims.knight) == NULL ||
get_gif("assets/Units/Lancier/frame_000", assets->anims.pikeman) == NULL ||
get_gif("assets/Units/ManAtArm/frame_000", assets->anims.soldier) == NULL ||
get_gif("assets/Units/Mangudai/frame_000", assets->anims.mangudai) == NULL)
return (my_puterr_int("A sprite is missing\n", 0));
return (get_textures(assets));
}
<file_sep>/src/errors.c
/*
** errors.c for errors in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jun 14 17:49:46 2015 <NAME>
** Last update Sun Jun 14 17:51:35 2015 <NAME>
*/
#include "tower.h"
int my_puterr_int(char *str, int error)
{
write(2, str, strlen(str));
return (error);
}
void *my_puterr(char *str, void *error)
{
write(2, str, strlen(str));
return (error);
}
<file_sep>/src/draw_line.c
/*
** draw_line.c for draw_line in /home/wilmot_g/Tower/src
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Thu Jul 9 13:37:34 2015 <NAME>
** Last update Thu Jul 9 13:56:28 2015 <NAME>
*/
#include "tower.h"
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
int bpp;
Uint8 *p;
bpp = surface->format->BytesPerPixel;
p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
if (bpp == 1)
*p = pixel;
else if (bpp == 2)
*(Uint16 *)p = pixel;
else if (bpp == 3)
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
p[0] = (pixel >> 16) & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = pixel & 0xff;
}
else
{
p[0] = pixel & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = (pixel >> 16) & 0xff;
}
else if (bpp == 4)
*(Uint32 *)p = pixel;
}
void draw_cas_un(t_line coords, SDL_Surface *screen, Uint32 color)
{
int x;
x = coords.x1;
while (x <= coords.x2)
{
if (coords.x2 - coords.x1 != 0)
putpixel(screen, x, coords.y1 + ((coords.y2 - coords.y1) *
(x - coords.x1)) /
(coords.x2 - coords.x1), color);
x++;
}
}
void draw_cas_deux(t_line coords, SDL_Surface *screen, Uint32 color)
{
int y;
y = coords.y1;
while (y <= coords.y2)
{
if (coords.y2 - coords.y1 != 0)
putpixel(screen, coords.x1 + ((coords.x2 - coords.x1) *
(y - coords.y1)) /
(coords.y2 - coords.y1), y, color);
y++;
}
}
void swap(t_line *coords)
{
int tmp;
tmp = coords->x1;
coords->x1 = coords->x2;
coords->x2 = tmp;
tmp = coords->y1;
coords->y1 = coords->y2;
coords->y2 = tmp;
}
void draw_line(t_line coords, SDL_Surface *screen, Uint32 color)
{
if (coords.x1 <= coords.x2 && (coords.x2 - coords.x1) >=
abs(coords.y2 - coords.y1))
draw_cas_un(coords, screen, color);
else if (coords.x1 > coords.x2 && abs(coords.x2 - coords.x1) >=
abs(coords.y2 - coords.y1))
{
swap(&coords);
draw_cas_un(coords, screen, color);
}
else if ((coords.y2 - coords.y1) >= 0 && abs(coords.x2 - coords.x1) <=
abs(coords.y2 - coords.y1))
draw_cas_deux(coords, screen, color);
else
{
swap(&coords);
draw_cas_deux(coords, screen, color);
}
}
<file_sep>/Makefile
##
## Makefile for Makefile in /home/wilmot_g/Tower
##
## Made by <NAME>
## Login <<EMAIL>>
##
## Started on Sat Jun 13 15:41:55 2015 <NAME>
## Last update Sun Dec 27 22:52:06 2015 Poncholay
##
CC = gcc ##-pg -W -O2
CFLAGS += -W -Wall -Wextra
CFLAGS += -pedantic
CFLAGS += -I./include/
LDFLAGS += -lSDL -lSDL_image -lSDL_mixer -lSDL_gfx -lm -g
SRCDIR = src
OBJDIR = obj
MKDIR = mkdir
RM = rm -f
RMDIR = rm -rf
NAME = tek_defense
SRC = concatenate.c \
choose_map.c \
draw_line.c \
errors.c \
free.c \
game.c \
get_assets.c \
get_next_line.c \
int_tab.c \
lagrange.c \
main.c \
map_editor.c \
match.c \
menu.c \
paths.c \
stats.c \
units.c \
OBJ = $(addprefix $(OBJDIR)/, $(SRC:.c=.o))
$(OBJDIR)/%.o: $(SRCDIR)/%.c
@if [ ! -d $(OBJDIR) ] ; then $(MKDIR) $(OBJDIR) ; fi
@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ -c $<
@echo -e "Object created :\t"$<" > "$@
$(NAME): $(OBJ)
$(CC) -o $(NAME) $(OBJ) $(LDFLAGS)
all: $(NAME)
clean:
$(RM) $(OBJ)
@if [ -d $(OBJDIR) ] ; then $(RMDIR) $(OBJDIR) ; fi
fclean: clean
$(RM) $(NAME)
re: fclean all
.PHONY: all clean fclean re
| 81e485a9f7567ab25532b5a8bb67eb9e7709f3c3 | [
"Markdown",
"C",
"Makefile"
] | 21 | Markdown | Poncholay/TekDefense | 22747609ba99b966f3465ba0125c7ca4800c4afa | 15042121c8f040149a4f16d2273f12eb8cb9a236 |
refs/heads/master | <repo_name>markloud/StatePattern<file_sep>/StatePattern/Health/IHealth.cs
namespace StatePattern.Health
{
public interface IHealth
{
void DoBattle(Warrior w);
}
}<file_sep>/StatePattern/Health/Normal.cs
namespace StatePattern.Health
{
public class Normal : IHealth
{
void IHealth.DoBattle(Warrior w)
{
//warrior can transition to another state based on the outcome
w.SetHealth(new Weak());
}
}
}<file_sep>/StatePattern/Health/SuperStrong.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StatePattern.Health
{
public class SuperStrong : IHealth
{
void IHealth.DoBattle(Warrior w)
{
//warrior can transition to another state based on the outcome
w.SetHealth(new Normal());
}
}
}
<file_sep>/StatePattern/Health/Strong.cs
namespace StatePattern.Health
{
public class Strong : IHealth
{
void IHealth.DoBattle(Warrior w)
{
//warrior can transition to another state based on the outcome
w.SetHealth(new SuperStrong());
}
}
}<file_sep>/StatePattern/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StatePattern
{
class Program
{
static void Main(string[] args)
{
Warrior w = new Warrior();
w.ShowHealth();
w.Battle();
w.ShowHealth();
w.Battle();
w.ShowHealth();
w.Battle();
w.ShowHealth();
w.Battle();
w.ShowHealth();
Console.ReadKey();
}
}
}
| f7561a2d8597d57a149e51ed921e34ca88d22e8c | [
"C#"
] | 5 | C# | markloud/StatePattern | 536f75b848ab270fd7ceb6aaf110c3046ee724dd | 4a7d6c7ab429c0da6fb7690f180a9d8b8ea85a74 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-19 20:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0019_auto_20160219_2322'),
]
operations = [
migrations.AddField(
model_name='page',
name='img',
field=models.ImageField(default='/media/default-img.png', help_text='150x150px', upload_to='/images/', verbose_name='Ваше фото'),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-21 08:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0027_auto_20160220_2107'),
]
operations = [
migrations.AlterField(
model_name='page',
name='img',
field=models.ImageField(default='default-img.png', help_text='Any text', upload_to='images/', verbose_name='Ваше фото'),
),
migrations.AlterField(
model_name='page',
name='pub_date',
field=models.DateTimeField(verbose_name='date published'),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-20 05:59
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pages', '0024_auto_20160220_0859'),
]
operations = [
migrations.RemoveField(
model_name='page',
name='img',
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-20 05:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pages', '0021_remove_page_img'),
]
operations = [
migrations.RemoveField(
model_name='image',
name='img',
),
migrations.DeleteModel(
name='Image',
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-19 12:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0004_auto_20160219_1508'),
]
operations = [
migrations.AlterField(
model_name='page',
name='pub_date',
field=models.DateTimeField(verbose_name='date published'),
),
migrations.AlterField(
model_name='page',
name='updated_date',
field=models.DateTimeField(verbose_name='date updated'),
),
]
<file_sep>from django.shortcuts import render, get_object_or_404
from .models import Page
from .forms import ContactForm
def home(request):
context = {
'test_var': 'test variable value',
# 'pages': Page.objects.all().order_by('-updated_date')
'pages': Page.objects.order_by('-updated_date')[:3]
}
return render(request, 'base.html', context)
def page_full(request, slug):
instance = get_object_or_404(Page, slug=slug)
context = {
'page': instance,
}
return render(request, 'page-full.html', context)
# Contact form
def contact(request):
context = {
'contact_form': ContactForm,
}
return render(request, 'contact.html', context)<file_sep>from django.db import models
from django.template.defaultfilters import slugify
from unidecode import unidecode
# from transliterate import translit, get_available_language_codes
# from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class Page(models.Model):
title = models.CharField(max_length=128)
slug = models.SlugField(max_length=50, unique=True, blank=True)
img = models.ImageField(upload_to='images/', verbose_name=u'Ваше фото', help_text='Any text', default='default-img.png')
# body = models.TextField(blank=True)
# body = RichTextField()
body = RichTextUploadingField()
pub_date = models.DateTimeField('date published')
updated_date = models.DateTimeField('date updated', auto_now=True, auto_now_add=False)
def save(self):
if not self.slug:
self.slug = slugify(unidecode(self.title))
# self.slug = slugify(translit(self.title, 'ru', reversed=True))
super(Page, self).save()
def __str__(self):
return self.title
# class Image(models.Model):
# img = models.ForeignKey(Page)
# image = models.ImageField(upload_to='images/')
# def image_img(self):
# if self.image:
# return u'<img src="%s" width="100" />' % self.image.url
# else:
# return '(none)'
# image_img.short_description = 'Thumb'
# image_img.allow_tags = True
<file_sep>from django.contrib import admin
# from .models import Page, Image
from .models import Page
class PageAdmin(admin.ModelAdmin):
list_display = ["title", "slug", "updated_date", "pub_date"]
list_display_links = ["title"]
search_fields = ["title"]
ordering = ['-updated_date']
class Meta:
model = Page
# class ImageAdmin(admin.ModelAdmin):
# list_display = ['img', 'image', 'image_img']
# class Meta:
# model = Image
admin.site.register(Page, PageAdmin)
# admin.site.register(Image, ImageAdmin) | 048994db3aba6b8902322177ca64a2f385b6f7f4 | [
"Python"
] | 8 | Python | m5studio/Django | 97481fb66028a2a23bfcecd1d75411b3ececad48 | 12d4f2e2a6661055455007b7532a04b870f0ebac |
refs/heads/master | <file_sep># Spark PostgreSQL S3 consistency
The purpose of this Spark code is to check consistency and bench data reading to PG and store them into S3 after some processing.
## Build and create the jar file:
```
mvn package
```
## Run
```
./ovh-spark-submit_linux_amd64_1.3.2 --spark-version 3.2.1 --projectid XXXXX --class PgS3Consistency --driver-cores 3 --driver-memory 4G --executor-cores 4 --executor-memory 6G --num-executors 5 --packages org.apache.spark:spark-sql_2.12:3.2.1,org.postgresql:postgresql:42.3.0 swift://XXXX/pgS3Consistency-1.0.jar
```<file_sep>## OOM Java
```
ovh-spark-submit_linux_amd64_1.3.2 --spark-version 3.2.1 --projectid XXXXX --driver-cores 1 --driver-memory 2G --executor-cores 1 --executor-memory 1G --num-executors 1 --class JavaOOM swift://java_oom/javaoom-0.1.jar
```
<file_sep>import numpy as np
import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('oom').getOrCreate()
sc = spark.sparkContext
# set smaller number of partitions so they can fit the screen
spark.conf.set('spark.sql.shuffle.partitions', 8)
# disable broadcast join to see the shuffle
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
length = 10000000
names = np.random.choice(['Bob', 'James', 'Marek', 'Johannes', None], length)
amounts = np.random.randint(0, 1000000, length)
# generate skewed data
country = np.random.choice(
['United Kingdom', 'Poland', 'USA', 'Germany', 'Russia'],
length,
p = [0.05, 0.05, 0.8, 0.05, 0.05]
)
data = pd.DataFrame({'name': names, 'amount': amounts, 'country': country})
transactions = spark.createDataFrame(data).repartition('country')
countries = spark.createDataFrame(pd.DataFrame({
'id': [11, 12, 13, 14, 15],
'country': ['United Kingdom', 'Poland', 'USA', 'Germany', 'Russia']
}))
df = transactions.join(countries, 'country')
# check the partitions data
for i, part in enumerate(df.rdd.glom().collect()):
print({i: part})
# VERY important to stop SparkSession
# Otherwise, the job will keep running indefinitely
spark.stop()<file_sep>from pyspark.sql import SparkSession
# from delta import configure_spark_with_delta_pip
# jar_path = '/opt/spark/workdir/jar'
# jars = [
# f'{jar_path}/hadoop-aws-3.3.2.jar',
# f'{jar_path}/aws-java-sdk-bundle-1.12.382.jar'
# ]
# jars = ','.join(jars)
builder = SparkSession.builder \
.appName('POC_OVH_Stago') \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.config("spark.hadoop.fs.defaultFS", "s3a://delta-error/")
spark = builder.getOrCreate()
# spark = configure_spark_with_delta_pip(builder).getOrCreate()
read_path = 's3a://delta-error/zipcodes.csv'
df = spark.read.csv(read_path)
df.show()
write_path = 's3a://delta-error/dummy_data_delta'
df.write \
.format('Delta') \
.mode('overwrite') \
.save(write_path)<file_sep>import java.util.Properties;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
//
// The purpose of this Spark code is to check consistency and bench data reading to PG and store them into S3 after some processing
//
// The different steps are:
// - extract data from PG with some partitioning/parallelization (spread reading based on one column with lower/upper bounds)
// - store tables (RAW) on S3
// - compute the best rated movies
// - store results on S3
//
// Here after the dataset: https://files.grouplens.org/datasets/movielens/
// Dataset explanation: https://grouplens.org/datasets/movielens/
//
// Here after the ER diagram:
//
// +---------------+ +--------------+
// | movies | | ratings |
// ----------------- ----------------
// | movie_id | | user_id |
// | | | movie_id |
// | title | | |
// | genres | | rating |
// | | | timestamp |
// +---------------+ +--------------+
//
// movie_id: int
// user_id: int
// title: varchar => Jumanji (1995)
// genres: varchar => Adventure|Children|Fantasy
// rating: decimal (0 =< rating <= 10)
// timestamp: long - date/timestamp when the rating was done
public final class PgS3Consistency {
public static void main(String[] args) throws Exception {
// S3 base url
String baseS3Location = "s3a://XXXXX/pgdump";
// S3 credentials
String s3AccessKey = "XXXX";
String s3SecretKey = "XXXXX";
// PG url
String url = "jdbc:postgresql://postgresql-XXXX-XXXX.database.cloud.ovh.net:20184/movielens?sslmode=require";
// PG credentials
String pgUser = "XXXX";
String pgPassword = "<PASSWORD>";
// PG partitioning to parallelize data reading from Spark to DB
String pgPartitioningNb = "10";
// Repartition before copy to S3
int repartitionNb = 5;
SparkSession spark = SparkSession
.builder()
.appName("PgS3Consistency")
.config("spark.hadoop.fs.s3a.access.key", s3AccessKey)
.config("spark.hadoop.fs.s3a.secret.key", s3SecretKey)
.config("spark.hadoop.fs.s3a.endpoint", "s3.gra.perf.cloud.ovh.net")
.config("fs.s3a.path.style.access", "true")
.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
.config("spark.sql.hive.metastorePartitionPruning", "true")
.config("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", "2")
.config("spark.hadoop.mapreduce.fileoutputcommitter.cleanup-failures.ignored", "true")
.config("spark.sql.parquet.filterPushdown", "true")
.config("spark.hadoop.parquet.enable.summary-metadata", "false")
.config("spark.sql.parquet.mergeSchema", "false")
.config("spark.network.timeout", 10000000)
.getOrCreate();
Properties connectionProperties = new Properties();
connectionProperties.put("user", pgUser);
connectionProperties.put("password", <PASSWORD>);
connectionProperties.put("driver", "org.postgresql.Driver");
// read movies
Dataset<Row> moviesDs = spark.read().jdbc(url, "movies", connectionProperties);
// read ratings
// here we add partitioning on "rating" column to parallelize reading
// first, detect lower and upper bound based on rating column
Dataset<Row> bounds = spark.read().jdbc(url,"(SELECT min(rating) as min, max(rating) as max FROM ratings) AS bounds", connectionProperties);
String lowerBound = String.valueOf(bounds.select("min").head().getDecimal(0).intValue());
String upperBound = String.valueOf(bounds.select("max").head().getDecimal(0).intValue() + 1);
connectionProperties.put("numPartitions", pgPartitioningNb);
connectionProperties.put("partitionColumn", "rating");
connectionProperties.put("lowerBound", lowerBound);
connectionProperties.put("upperBound", upperBound);
Dataset<Row> ratingsDs = spark.read().jdbc(url, "ratings", connectionProperties);
// repartition to force a shuffle and redistribute data (not manadatory but for benchmarking purpose to check consistency)
Dataset<Row> ratingsDsRepartitioned = ratingsDs.repartition(repartitionNb);
// First we find which movies have been rated 5000 or more times.
Dataset<Row> qualifyingMovies = ratingsDsRepartitioned
.groupBy("movie_id")
.agg(org.apache.spark.sql.functions.avg("rating"))
.filter("count(rating) >= 5000");
// Within the filtered movies we query the 100 with a greatest average rating.
Dataset<Row> greatestMoviesByAverageRating = moviesDs
.join(qualifyingMovies, moviesDs.col("movie_id").equalTo(qualifyingMovies.col("movie_id")))
.select("avg(rating)", "title")
.orderBy(org.apache.spark.sql.functions.col("avg(rating)").desc())
.limit(100)
.withColumnRenamed("avg(rating)", "average_score");
// Store movies to S3
moviesDs.toDF().write().parquet(baseS3Location + "/movies");
// Store ratings to S3
Dataset<Row> ratingsDsCasted = ratingsDsRepartitioned.withColumn("rating", ratingsDsRepartitioned.col("rating").cast("int"));
ratingsDsCasted.toDF().write().partitionBy("rating").parquet(baseS3Location + "/ratings");
// Store the greatest movies
greatestMoviesByAverageRating.toDF().write().parquet(baseS3Location + "/stats");
spark.stop();
}
}<file_sep># Sample Spark S3 Word Count
Sample Spark project that may be compiled into a JAR for running via `spark-submit`.
## Dependencies
* Spark 3.2.1
* SBT 1.7.2
## Building
To build a JAR for submission via `spark-submit` use the `assembly` SBT task.
```bash
sbt assembly
```
## Helper Task
A custom task exists to both compile the JAR and submit it to the Spark cluster. It will need to be edited to point at your local `spark-submit` executable. This may be used within an IDE such as IntelliJ.
<file_sep>from pyspark.sql import SparkSession
from pyspark.sql.functions import lit
from delta import *
app_name = "PySpark delta"
# Create Spark session with Delta extension
builder = SparkSession.builder.appName(app_name) \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.config("spark.hadoop.fs.defaultFS", "s3a://delta/")
spark = builder.getOrCreate()
spark.sparkContext.setLogLevel("INFO")
#Create a DataFrame
df = spark.range(1, 10)
df = df.withColumn('value', lit('ABC'))
#Save as delta table
df.write.format('delta').save('test_table')
# Read delta table
df = spark.read.format("delta").load("test_table")
df.show()
# Stop Spark Process
spark.stop() | ead1b9a5ef646db52af288df5f41ba64cb0aab5c | [
"Markdown",
"Java",
"Python"
] | 7 | Markdown | morind/data-processing-samples | 16f248477487967b73700830274a2ea77c8669fa | a2b8800a276e8a8040dfe502958ec23682d8abcb |
refs/heads/master | <file_sep>import { Provider, ServiceQueryArgs, ServiceReturn } from '../extenders/Provider';
export class User extends Provider {
public async checkIfExists({
email,
}: ServiceQueryArgs<'checkIfUserExists'>): ServiceReturn<'Boolean'> {
return !!(await this.prisma.user.count({ where: { email } }));
}
public async userDetails(): ServiceReturn<'UserDetails'> {
const id = this.getUserId();
return await this.prisma.user.findOne({
where: { id },
select: {
id: true,
createdAt: true,
updatedAt: true,
email: true,
profile: {
select: {
firstName: true,
lastName: true,
},
},
},
});
}
public async getUserTeams(): ServiceReturn<'UserTeamDetails'> {
const id = this.getUserId();
return await this.prisma.user.findOne({
where: { id },
select: {
id: true,
ownerTeams: {
select: {
id: true,
name: true,
displayName: true,
createdAt: true,
},
},
memberTeams: {
select: {
id: true,
name: true,
displayName: true,
createdAt: true,
},
},
},
});
}
}
<file_sep><p align="center"><img src="https://repository-images.githubusercontent.com/259775937/548b6b00-9a47-11ea-864f-a6d905f657c6" alt="troup-banner" width="300" /></p>
# Troup Server
[](https://spectrum.chat/troup) [](http://makeapullrequest.com) [](https://www.firsttimersonly.com/)
> ### 📢 We are looking for contributors!
>
> This project is under heavy development and is on the lookout for contributors both technical and ono-technical. If you are interested in understanding the product and contributing, do get in touch at <EMAIL>.
The Troup server is the Express-GraphQL app that helps the client address problems that we aim to solve. The server is built atop wonderful open-source projects with the goal of providing a fluid experience to the client.
**Languages:**
- [Typescript][typescript]
**Libraries:**
- [Apollo Server][apollo-server]
- [Prisma][prisma]
- [Nexus Schema][nexus-schema]
## Setting up environment variables
You will need to create two `.env` files in the root and the `prisma` folder. The instructions on setting those up are available within each example:
- [Root environment variables](https://github.com/troup-io/troup-server/blob/master/example.env)
- [Prisma environment variables](https://github.com/troup-io/troup-server/blob/master/prisma/example.env)
## Available scripts
### `yarn boostrap`
Bootstrap the database and the server. This will also seed your local database.
### `yarn dev`
Start the development server and watch for file changes.
### `yarn build`
Build the production-optimised bundle for deployment.
### `yarn start`
Deploy the production-optimised bundle locally to test and simulate the production environment.
### `yarn lint`
Run the linter, catching out any errors or warning that may occur.
### `yarn cmd`
The raw command runner. All commands that are listed as `category:command` can be run using `yarn cmd category command`.
For example, the [`app:dev`][app-dev] command can run as `yarn cmd app dev`.
### UNSAFE: `yarn reset`
Use this if something has gone horribly wrong with your database. It wipes out all data, clears out all volumes and containers and restarts a new container.
Resources: [Available Commands][commands]
[typescript]: https://www.typescriptlang.org/
[apollo-server]: https://www.apollographql.com/docs/apollo-server
[prisma]: https://www.prisma.io
[nexus-schema]: https://github.com/graphql-nexus/schema
[commands]: https://github.com/troup-io/troup-server/blob/master/cmd/COMMANDS.ts
[app-dev]: https://github.com/troup-io/troup-server/blob/master/cmd/COMMANDS.ts#L45
<file_sep>export enum TeamErrors {
INVALID_TEAM = "Sorry, no such team exists. Why don't you create one?",
INVALID_TEAM_ACCESS = "Oops, looks like either this team doesn't exist or you do not have access to this team!",
}
<file_sep># Migration `20200805140215`
This migration has been generated by <NAME> at 8/5/2020, 2:02:15 PM.
You can check out the [state of the schema](./schema.prisma) after the migration.
## Database Steps
```sql
ALTER TABLE "public"."Label" ALTER COLUMN "foreground" DROP NOT NULL,
ALTER COLUMN "isGlobal" DROP NOT NULL;
ALTER TABLE "public"."Project" ADD COLUMN "uid" text NOT NULL ;
ALTER TABLE "public"."Ticket" ADD COLUMN "uid" text NOT NULL ;
CREATE UNIQUE INDEX "Project.uid" ON "public"."Project"("uid")
CREATE UNIQUE INDEX "Ticket.uid" ON "public"."Ticket"("uid")
```
## Changes
```diff
diff --git schema.prisma schema.prisma
migration 20200626212557-init..20200805140215
--- datamodel.dml
+++ datamodel.dml
@@ -1,7 +1,7 @@
datasource db {
provider = "postgresql"
- url = "***"
+ url = "***"
}
generator client {
provider = "prisma-client-js"
@@ -56,8 +56,9 @@
model Project {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ uid String @unique
sequence Int
name String
team Team @relation(fields: [teamId], references: [id])
teamId Int
@@ -69,8 +70,9 @@
model Ticket {
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ uid String @unique
sequence Int
title String
body String
team Team @relation(fields: [teamId], references: [id])
@@ -87,11 +89,11 @@
id Int @default(autoincrement()) @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
value String
- isGlobal Boolean @default(false)
+ isGlobal Boolean? @default(false)
background String
- foreground String @default("#222222")
+ foreground String? @default("#222222")
team Team @relation(fields: [teamId], references: [id])
teamId Int
project Project? @relation(fields: [projectId], references: [id])
projectId Int?
```
<file_sep>import { AuthenticationError } from 'apollo-server-express';
import { Middleware } from '../types/helpers.types';
import { AuthErrors } from '../errors/auth.errors';
import { getUserId, getTeamId } from '../utils';
export const ResourceCheckMiddleware: Middleware = () => async (
root,
args,
context,
info,
next
): Promise<void> => {
const { request } = context;
const userId = getUserId.call({ request });
const teamId = getTeamId.call({ request });
const accessValid = await context.db.user.count({
where: {
AND: [
{
id: userId,
},
{
OR: [
{
memberTeams: {
some: { id: teamId },
},
},
{
ownerTeams: {
some: { id: teamId },
},
},
{
profile: {
isSuperAdmin: true,
},
},
],
},
],
},
});
if (!accessValid) {
throw new AuthenticationError(AuthErrors.ACCESS_DENIED);
}
return await next(root, args, context, info);
};
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Query',
definition(t) {
t.field('checkIfUserExists', {
type: 'Boolean',
description: 'Check if a user already exists while creating',
args: {
email: schema.stringArg({
required: true,
description: "User's email to check against.",
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.user.checkIfExists(data);
},
});
t.field('userDetails', {
type: schema.objectType({
name: 'UserDetails',
definition(t) {
t.model('User')
.id()
.createdAt()
.updatedAt()
.email()
.profile();
},
}),
description:
'Get bare-minimal user details to populate the interface and identify the user.',
async resolve(_, data, ctx: Context) {
return await ctx.user.userDetails();
},
});
t.field('getUserTeams', {
type: schema.objectType({
name: 'UserTeamDetails',
definition(t) {
t.model('User').id();
t.model('User').ownerTeams({
ordering: true,
filtering: true,
pagination: true,
});
t.model('User').memberTeams({
ordering: true,
filtering: true,
pagination: true,
});
},
}),
description: 'Get all the teams the user is associated with as an owner or a member.',
async resolve(_, __, ctx: Context) {
return await ctx.user.getUserTeams();
},
});
},
});
<file_sep># Migration `20200626212557-init`
This migration has been generated by <NAME> at 6/26/2020, 9:25:57 PM.
You can check out the [state of the schema](./schema.prisma) after the migration.
## Database Steps
```sql
CREATE TABLE "public"."Team" (
"adminEmail" text ,"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"displayName" text ,"id" SERIAL,"maxMembers" integer NOT NULL DEFAULT 25,"name" text NOT NULL ,"ownerId" integer NOT NULL ,"updatedAt" timestamp(3) NOT NULL ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."User" (
"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"email" text NOT NULL ,"id" SERIAL,"password" text NOT NULL ,"updatedAt" timestamp(3) NOT NULL ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."UserProfile" (
"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"firstName" text NOT NULL ,"id" SERIAL,"isSuperAdmin" boolean NOT NULL DEFAULT false,"lastName" text NOT NULL ,"professionalCompetence" text ,"updatedAt" timestamp(3) NOT NULL ,"userId" integer NOT NULL ,"utm_campaign" text ,"utm_content" text ,"utm_medium" text ,"utm_source" text ,"utm_term" text ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."Project" (
"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"id" SERIAL,"name" text NOT NULL ,"sequence" integer NOT NULL ,"teamId" integer NOT NULL ,"updatedAt" timestamp(3) NOT NULL ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."Ticket" (
"authorId" integer NOT NULL ,"body" text NOT NULL ,"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"id" SERIAL,"projectId" integer NOT NULL ,"sequence" integer NOT NULL ,"teamId" integer NOT NULL ,"title" text NOT NULL ,"updatedAt" timestamp(3) NOT NULL ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."Label" (
"background" text NOT NULL ,"createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"foreground" text NOT NULL DEFAULT E'#222222',"id" SERIAL,"isGlobal" boolean NOT NULL DEFAULT false,"projectId" integer ,"teamId" integer NOT NULL ,"updatedAt" timestamp(3) NOT NULL ,"value" text NOT NULL ,
PRIMARY KEY ("id"))
CREATE TABLE "public"."_TeamToUser" (
"A" integer NOT NULL ,"B" integer NOT NULL )
CREATE TABLE "public"."_ProjectToUser" (
"A" integer NOT NULL ,"B" integer NOT NULL )
CREATE TABLE "public"."_LabelToTicket" (
"A" integer NOT NULL ,"B" integer NOT NULL )
CREATE UNIQUE INDEX "Team.name" ON "public"."Team"("name")
CREATE UNIQUE INDEX "User.email" ON "public"."User"("email")
CREATE UNIQUE INDEX "UserProfile_userId" ON "public"."UserProfile"("userId")
CREATE UNIQUE INDEX "_TeamToUser_AB_unique" ON "public"."_TeamToUser"("A","B")
CREATE INDEX "_TeamToUser_B_index" ON "public"."_TeamToUser"("B")
CREATE UNIQUE INDEX "_ProjectToUser_AB_unique" ON "public"."_ProjectToUser"("A","B")
CREATE INDEX "_ProjectToUser_B_index" ON "public"."_ProjectToUser"("B")
CREATE UNIQUE INDEX "_LabelToTicket_AB_unique" ON "public"."_LabelToTicket"("A","B")
CREATE INDEX "_LabelToTicket_B_index" ON "public"."_LabelToTicket"("B")
ALTER TABLE "public"."Team" ADD FOREIGN KEY ("ownerId")REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."UserProfile" ADD FOREIGN KEY ("userId")REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Project" ADD FOREIGN KEY ("teamId")REFERENCES "public"."Team"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Ticket" ADD FOREIGN KEY ("teamId")REFERENCES "public"."Team"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Ticket" ADD FOREIGN KEY ("authorId")REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Ticket" ADD FOREIGN KEY ("projectId")REFERENCES "public"."Project"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Label" ADD FOREIGN KEY ("teamId")REFERENCES "public"."Team"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."Label" ADD FOREIGN KEY ("projectId")REFERENCES "public"."Project"("id") ON DELETE SET NULL ON UPDATE CASCADE
ALTER TABLE "public"."_TeamToUser" ADD FOREIGN KEY ("A")REFERENCES "public"."Team"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."_TeamToUser" ADD FOREIGN KEY ("B")REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."_ProjectToUser" ADD FOREIGN KEY ("A")REFERENCES "public"."Project"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."_ProjectToUser" ADD FOREIGN KEY ("B")REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."_LabelToTicket" ADD FOREIGN KEY ("A")REFERENCES "public"."Label"("id") ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE "public"."_LabelToTicket" ADD FOREIGN KEY ("B")REFERENCES "public"."Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE
```
## Changes
```diff
diff --git schema.prisma schema.prisma
migration ..20200626212557-init
--- datamodel.dml
+++ datamodel.dml
@@ -1,0 +1,99 @@
+datasource db {
+ provider = "postgresql"
+ url = "***"
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+
+model Team {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ maxMembers Int @default(25)
+ name String @unique
+ displayName String?
+ adminEmail String?
+ owner User @relation("_UserOwnerOfTeams", fields: [ownerId])
+ ownerId Int
+ members User[]
+ labels Label[]
+ projects Project[]
+ tickets Ticket[]
+}
+
+model User {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ email String @unique
+ password String
+ profile UserProfile
+ memberTeams Team[]
+ ownerTeams Team[] @relation("_UserOwnerOfTeams")
+ projects Project[] @relation(references: [id])
+ tickets Ticket[]
+}
+
+model UserProfile {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ firstName String
+ lastName String
+ isSuperAdmin Boolean @default(false)
+ professionalCompetence String?
+ utm_source String?
+ utm_campaign String?
+ utm_medium String?
+ utm_term String?
+ utm_content String?
+ user User @relation(fields: [userId], references: [id])
+ userId Int
+}
+
+model Project {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ sequence Int
+ name String
+ team Team @relation(fields: [teamId], references: [id])
+ teamId Int
+ tickets Ticket[]
+ members User[]
+ labels Label[]
+}
+
+model Ticket {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ sequence Int
+ title String
+ body String
+ team Team @relation(fields: [teamId], references: [id])
+ teamId Int
+ author User @relation(fields: [authorId], references: [id])
+ authorId Int
+ project Project @relation(fields: [projectId], references: [id])
+ projectId Int
+ labels Label[] @relation(references: [id])
+}
+
+// Supporting models
+model Label {
+ id Int @default(autoincrement()) @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ value String
+ isGlobal Boolean @default(false)
+ background String
+ foreground String @default("#222222")
+ team Team @relation(fields: [teamId], references: [id])
+ teamId Int
+ project Project? @relation(fields: [projectId], references: [id])
+ projectId Int?
+ tickets Ticket[] @relation(references: [id])
+}
```
<file_sep>---
name: Question
about: Have questions? Ask away for answers!
title: '[❓]'
labels: question
assignees: ''
---
<!-- PLEASE delete the sections that are not applicable to you. -->
#### Question
<!-- What is your question about? -->
#### Additional context
<!-- Feel free to provide any additional context including screenshots -->
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Mutation',
definition(t) {
t.field('checkTeamName', {
type: 'Boolean',
description: 'Check if a team by the given name already exists.',
args: {
teamName: schema.stringArg({
required: true,
description: 'Team name to check against.',
}),
},
resolve(_, { teamName }, ctx: Context) {
return ctx.team.checkIfExists({ teamName });
},
});
},
});
<file_sep>#!/usr/bin/env node
import { execSync } from 'child_process';
const commands = [
'docker stop troup_pg_container_1',
'docker rm troup_pg_container_1',
'docker volume rm troup_pg_volume',
'rimraf /var/lib/postgres/troup',
];
for (const command of commands) {
execSync(command, {
stdio: 'inherit',
});
}
<file_sep>/* eslint-disable camelcase */
import { PrismaClient } from 'nexus-plugin-prisma/client';
import { config } from 'dotenv';
import * as bcrypt from 'bcryptjs';
import users from '../../prisma/seed';
config();
const prisma = new PrismaClient();
console.log('Starting seed..');
(async function(): Promise<void> {
try {
const adminHashedPassword = await bcrypt.hash('<PASSWORD>', 10);
const adminUser = await prisma.user.create({
data: {
email: '<EMAIL>',
password: <PASSWORD>,
profile: {
create: {
firstName: 'Admin',
lastName: 'User',
isSuperAdmin: true,
professionalCompetence: 'Admin',
utm_campaign: 'Seed',
utm_source: 'Seed',
utm_content: 'Seed user',
utm_medium: 'Seed',
utm_term: 'SEED',
},
},
ownerTeams: {
create: {
name: 'Troup',
displayName: '#TeamTroup',
adminEmail: '<EMAIL>',
},
},
},
select: {
ownerTeams: {
select: {
id: true,
},
},
},
});
console.log('Created admin and default team!');
console.log('Creating users..');
const teamId = adminUser.ownerTeams[0].id;
for (const user of users) {
const hashedPassword = await bcrypt.hash(user.password, 10);
await prisma.user.create({
data: {
email: user.email,
password: <PASSWORD>,
profile: {
create: {
firstName: user.firstName,
lastName: user.lastName,
},
},
memberTeams: {
connect: {
id: teamId,
},
},
},
});
console.log(`Created user ${user.email}`);
}
console.log(`Created ${users.length} users as memebrs of default team!\n`);
process.exit(0);
} catch (error) {
console.log(error);
throw error;
}
})();
process.on('unhandledRejection', () => {
return;
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'Project',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.sequence();
t.model.name();
t.model.team();
t.model.teamId();
t.model.members({
filtering: true,
ordering: true,
pagination: true,
});
t.model.tickets({
filtering: true,
ordering: true,
pagination: true,
});
t.model.labels({
filtering: true,
ordering: true,
pagination: true,
});
},
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'Ticket',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.team();
t.model.teamId();
t.model.author();
t.model.authorId();
t.model.sequence();
t.model.title();
t.model.body();
t.model.project();
t.model.projectId();
t.model.labels({
filtering: true,
ordering: true,
pagination: true,
});
},
});
<file_sep>import { Provider, ServiceReturn, ServiceMutationArgs } from '../extenders/Provider';
import { randomPastel } from '../../utils';
export class Label extends Provider {
public async create({
value,
color,
}: ServiceMutationArgs<'createGlobalLabel'>): ServiceReturn<'Label'> {
const { teamId } = this;
return await this.prisma.label.create({
data: {
value,
isGlobal: true,
background: color || randomPastel(),
team: {
connect: {
id: teamId,
},
},
},
});
}
}
<file_sep>import { Request } from 'nexus/dist/runtime/schema/schema';
import { Provider } from './extenders/Provider';
import { Team } from './core/Team';
import { Auth } from './core/Auth';
import { Signin } from './core/Auth/Signin';
import { Signup } from './core/Auth/Signup';
import { User } from './core/User';
import { Project } from './core/Project';
import { Ticket } from './core/Ticket';
import { Label } from './core/Label';
export type PartialContext = {
request: Request;
provider: Provider;
auth: {
core: Auth;
signin: Signin;
signup: Signup;
};
team: Team;
user: User;
project: Project;
ticket: Ticket;
label: Label;
};
export type Context = NexusContext & PartialContext;
export const ContextInit = (ctx: ServerContext): PartialContext => {
return {
request: ctx.request,
provider: new Provider(ctx),
auth: {
core: new Auth(ctx),
signin: new Signin(ctx),
signup: new Signup(ctx),
},
team: new Team(ctx),
user: new User(ctx),
project: new Project(ctx),
ticket: new Ticket(ctx),
label: new Label(ctx),
};
};
export interface ServerContext {
db: NexusContext['db'];
request: Request;
}
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Mutation',
definition(t) {
t.field('createProject', {
type: 'Project',
description: 'Create a new project.',
args: {
name: schema.stringArg({
required: true,
description: 'Name of the project to create.',
}),
members: schema.intArg({
description: 'An array of user IDs to associate as members.',
list: true,
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.project.create(data);
},
});
},
});
<file_sep>import * as bcrypt from 'bcryptjs';
import { Provider, ServiceMutationArgs, ServiceReturn } from '../../extenders/Provider';
import { tokenSigner } from '../../../utils';
export class Signup extends Provider {
public async signupUser({
email,
password,
firstName,
lastName,
teamId,
}: ServiceMutationArgs<'signupUser'>): ServiceReturn<'UserData'> {
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.prisma.user.create({
data: {
email,
password: <PASSWORD>,
profile: {
create: {
firstName,
lastName,
},
},
memberTeams: {
connect: {
id: teamId,
},
},
},
});
return {
user,
token: tokenSigner(user.id),
};
}
public async signupTeam({
email,
password,
firstName,
lastName,
teamName,
}: ServiceMutationArgs<'signupTeam'>): ServiceReturn<'TeamSignupData'> {
const hashedPassword = await bcrypt.hash(password, 10);
const { owner, ...team } = await this.prisma.team.create({
data: {
name: teamName,
owner: {
create: {
email,
password: <PASSWORD>,
profile: {
create: {
firstName,
lastName,
},
},
},
},
},
include: {
owner: true,
},
});
return {
user: owner,
team,
token: tokenSigner(owner.id),
};
}
}
<file_sep>import { UserInputError } from 'apollo-server-express';
import { Provider, ServiceReturn } from '../../extenders/Provider';
import { checkPasswordMatch, tokenSigner, checkUserTeam } from '../../../utils';
export class Auth extends Provider {
public async signinUser({
email,
password,
}: {
email: string;
password: string;
}): ServiceReturn<'UserData'> {
const user = await this.prisma.user.findOne({
where: { email },
include: {
profile: true,
memberTeams: {
select: {
id: true,
name: true,
displayName: true,
},
},
ownerTeams: {
select: {
id: true,
name: true,
displayName: true,
},
},
},
});
if (!user) {
throw new UserInputError(`No such user found for email: ${email}`);
}
if (!(await checkPasswordMatch(user, password))) {
throw new UserInputError('Invalid password');
}
return {
token: tokenSigner(user.id),
user,
};
}
public async signinTeam({
email,
password,
teamId: id,
}: {
email: string;
password: string;
teamId: number;
}): ServiceReturn<'TeamSigninData'> {
const user = await this.prisma.user.findOne({
where: { email },
include: {
profile: {
select: {
firstName: true,
lastName: true,
},
},
memberTeams: {
where: {
id,
},
select: {
id: true,
name: true,
displayName: true,
},
},
ownerTeams: {
where: {
id,
},
select: {
id: true,
name: true,
displayName: true,
},
},
},
});
if (!user) {
throw new Error(`No such user found for email: ${email}`);
}
if (!checkUserTeam(user)) {
throw new Error(`User (${email}) is not a member of this team.`);
}
if (!(await checkPasswordMatch(user, password))) {
throw new Error('Invalid password');
}
return {
token: tokenSigner(user.id),
user,
};
}
}
<file_sep>export enum AuthErrors {
ACCESS_DENIED = 'You are not authorised to access this team.',
INVALID_EMAIL = 'Sorry, there is no account associated with this email.',
INVALID_PASSWORD = "The password you've entered is invalid.",
INVALID_TEAM_MEMBER = 'Sorry, you are not part of this team. Please signup or contact the administrator to add you to the team.',
PROJECT_ACCESS_DENIED = 'You are not authorised to create a ticket for this project.',
}
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Mutation',
definition(t) {
t.field('createGlobalLabel', {
type: 'Label',
description: 'Create a new global label.',
args: {
value: schema.stringArg({
required: true,
description: 'The value of the label.',
}),
color: schema.stringArg({
description: 'The color of the label.',
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.label.create(data);
},
});
},
});
<file_sep>#!/usr/bin/env node
import { resolve } from 'path';
import { execSync } from 'child_process';
import COMMANDS, { CommandItem } from './COMMANDS';
const [runner, subrunner] = process.argv.slice(2);
function runSingleCommand(command: CommandItem): void {
const ROOT = resolve(__dirname, '../');
const cwd = resolve(ROOT, command.cwd ?? '.');
try {
execSync(command.command, {
stdio: 'inherit',
cwd,
});
return;
} catch (error) {
if (runner === 'reset' || runner === 'bootstrap') {
runSingleCommand(command);
} else {
process.exit(1);
}
}
}
async function commandRunnner(commands: CommandItem[]): Promise<void> {
if (commands.length) {
for (const command of commands) {
await runSingleCommand(command);
}
}
}
// eslint-disable-next-line complexity
(async function main(): Promise<void> {
const allCommands = Object.keys(COMMANDS);
const availableCommands = allCommands.filter(cmd => cmd.includes(`${runner}:`));
try {
if (runner !== 'bootstrap' && runner !== 'reset' && !availableCommands.length) {
throw 1;
}
if (runner === 'bootstrap') {
const bootstrapCommands = Object.values(COMMANDS)
.filter((command: CommandItem) => command.bsSeq)
.sort((a: CommandItem, b: CommandItem) => a.bsSeq - b.bsSeq) as CommandItem[];
await commandRunnner(bootstrapCommands);
return;
}
if (runner === 'reset') {
const resetCommands = Object.values(COMMANDS)
.filter((command: CommandItem) => command.rsSeq)
.sort((a: CommandItem, b: CommandItem) => a.rsSeq - b.rsSeq) as CommandItem[];
await commandRunnner(resetCommands);
return;
}
if (!subrunner) {
throw 1;
}
if (subrunner) {
const command: CommandItem = COMMANDS[`${runner}:${subrunner}`];
if (command) {
runSingleCommand(command);
return;
} else {
throw 1;
}
}
throw 1;
} catch (error) {
if (error === 1) {
console.log('');
console.log('No matching commands, or malformed arguments. Available commands are:');
console.log(
(availableCommands.length ? availableCommands : allCommands)
.map(cmd => `- ${cmd.replace(':', ' ')}\n`)
.join('')
);
console.log('');
}
process.exit(1);
}
})();
process.on('unhandledRejection', error => {
console.log('\n\n', error);
if ((error as Error).message.includes(`Can't reach database`)) {
return;
}
console.error(error);
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'Label',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.team();
t.model.teamId();
t.model.isGlobal();
t.model.value();
t.model.background();
t.model.project();
t.model.projectId();
t.model.tickets({
filtering: true,
ordering: true,
pagination: true,
});
},
});
<file_sep>/**
* The list of available commands in this project.
* The sequence key is only used if the command is a bootstrap command or if it is a wildcard command.
*
* Additional commands and tasks can be found in .vscode/tasks.json or can be run directly from VS Code task runner.
*/
export interface Commands {
[key: string]: CommandItem;
}
export interface CommandItem {
command: string;
cwd?: string;
bsSeq?: number;
rsSeq?: number;
}
export default {
'db:start': {
command: "docker-compose --project-name 'troup' up -d",
cwd: 'prisma',
bsSeq: 1,
rsSeq: 2,
},
'db:setup': {
command: 'yarn prisma migrate up --experimental',
bsSeq: 2,
rsSeq: 3,
},
'db:generate': {
command: 'yarn prisma generate',
bsSeq: 3,
},
'db:seed': {
command: './node_modules/.bin/ts-node cmd/runners/seed-database',
bsSeq: 4,
rsSeq: 4,
},
'db:clean': {
command: './node_modules/.bin/ts-node cmd/runners/prune-database',
rsSeq: 1,
},
'app:dev': {
command: 'dotenv -- nodehawk',
},
'app:start': {
command: 'rimraf dist && ttsc && node ./dist/server.js',
},
'app:build': {
command: 'rimraf dist && ttsc',
},
'app:lint': {
command: 'eslint src --ext .ts,.json,.js',
},
semver: {
command: 'npm version',
},
'semver:alpha': {
command: 'npm version --prerelease="alpha"',
},
'semver:beta': {
command: 'npm version --prerelease="beta"',
},
};
<file_sep><!-- Fill out the sections and do not forget the checklist at the bottom! :) -->
#### Brief description
<!-- Add a brief description of the changes, or provide some context as to why. -->
#### Issues addressed
<!--
The issue(s) which this PR addresses. Ex:
- Fixes #11
- Fixes #22
...etc.
Please remove this section if it does not apply to you.
-->
#### Additions
<!--
List of additions.
Please remove this section if it does not apply to you.
- keywords: added, created
-->
#### Updates
<!--
List of updates.
Please remove this section if it does not apply to you.
- keywords: updated, modified
-->
#### Removals
<!--
List of removals.
Please remove this section if it does not apply to you.
- keywords: removed, deleted
-->
#### Breaking changes
<!--
List of breaking changes.
Please remove this section if it does not apply to you.
-->
#### Steps to reproduce and test
<!-- List down the steps to either reproduce or test out this PR. -->
#### Notes
<!-- Any additional info, or context you may want to provide. -->
---
#### Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have added tests to cover my changes.
---
#### Contributing policy agreement
- [ ] I have read the [**CONTRIBUTING**](https://github.com/troup-io/troup-server/blob/master/CONTRIBUTING.md) document.
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Query',
definition(t) {
t.field('projects', {
type: 'Project',
description: 'Get all the projects of a particular team.',
list: true,
async resolve(_, __, ctx: Context) {
return await ctx.project.getAll();
},
});
},
});
<file_sep>import { schema } from 'nexus';
export const UserData = schema.objectType({
name: 'UserData',
definition(t) {
t.field('user', {
type: 'User',
description: 'The user object.',
});
t.string('token', {
description: 'The encoded JWT token.',
});
},
});
<file_sep>export type SeedUser = {
email: string;
password: string;
firstName: string;
lastName: string;
};
export default [
{
email: '<EMAIL>',
password: '<PASSWORD>',
firstName: 'John',
lastName: 'Doe',
},
{
email: '<EMAIL>',
password: '<PASSWORD>',
firstName: 'Jane',
lastName: 'Doe',
},
{
email: '<EMAIL>',
password: '<PASSWORD>',
firstName: 'Homer',
lastName: 'Doenut',
},
{
email: '<EMAIL>',
password: '<PASSWORD>',
firstName: 'Marge',
lastName: 'Doenut',
},
] as SeedUser[];
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Mutation',
definition(t) {
t.field('createTicket', {
type: 'Ticket',
description: 'Create a new ticket.',
args: {
projectId: schema.intArg({
required: true,
description: 'The project to associate this ticket with.',
}),
title: schema.stringArg({
required: true,
description: 'Title of the ticket to create.',
}),
body: schema.stringArg({
required: true,
description: 'The content of the ticket.',
}),
labels: schema.stringArg({
list: true,
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.ticket.create(data);
},
});
},
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'Team',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.name();
t.model.displayName();
t.model.adminEmail();
t.model.maxMembers();
t.model.members();
t.model.owner();
t.model.ownerId();
},
});
<file_sep>import { schema } from 'nexus';
import { Context } from '../../../services/Context';
import { UserData } from '../../Types';
export default schema.extendType({
type: 'Mutation',
definition(t) {
t.field('signupUser', {
type: UserData,
description: "Team creation flow. The created user is the team's owner.",
args: {
email: schema.stringArg({
required: true,
description: "The user's email address.",
}),
password: schema.stringArg({
required: true,
description: "The user's password.",
}),
firstName: schema.stringArg({
required: true,
description: "The user's first name.",
}),
lastName: schema.stringArg({
required: true,
description: "The user's last name.",
}),
teamId: schema.intArg({
required: true,
description: 'The ID of the team sign up with.',
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.auth.signup.signupUser(data);
},
});
t.field('signupTeam', {
type: schema.objectType({
name: 'TeamSignupData',
definition(t) {
t.field('team', {
type: 'Team',
description: 'The team object.',
});
t.field('user', {
type: 'User',
description: 'The user object.',
});
t.string('token', {
description: 'The encoded JWT token.',
});
},
}),
description:
'Create a user and the relevant profile, along with the team and relevant profile.',
args: {
email: schema.stringArg({
required: true,
description: "The user's email address.",
}),
password: schema.stringArg({
required: true,
description: "The user's password.",
}),
firstName: schema.stringArg({
required: true,
description: "The user's first name.",
}),
lastName: schema.stringArg({
required: true,
description: "The user's last name.",
}),
teamName: schema.stringArg({
required: true,
description: 'The name of the team being created. Must be unique.',
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.auth.signup.signupTeam(data);
},
});
},
});
<file_sep>import { ServerContext } from '../Context';
import { getUserId, getTeamId } from '../../utils';
export class Provider {
protected prisma: ServerContext['db'];
protected request: ServerContext['request'];
protected userId?: number;
protected teamId?: number;
constructor(ctx: ServerContext) {
this.prisma = ctx.db;
this.request = ctx.request;
this.userId = this.getUserId();
this.teamId = this.getTeamId();
}
public getHeader(key: keyof ServerContext['request']['headers']): string | string[] {
return this.request.headers[key];
}
public getUserId = getUserId.bind(this);
public getTeamId = getTeamId.bind(this);
}
type RootTypes = NexusGen['rootTypes'];
type RootKeys = Exclude<keyof RootTypes, 'Mutation' | 'Query'>;
type RootReturn<T extends RootKeys> = RootTypes[T];
export type ServiceReturn<T extends RootKeys> = Promise<RootReturn<T>>;
export type ServiceArrayReturn<T extends RootKeys> = Promise<Array<RootReturn<T>>>;
export type ServiceQueryArgs<
T extends keyof NexusGen['argTypes']['Query']
> = NexusGen['argTypes']['Query'][T];
export type ServiceMutationArgs<
T extends keyof NexusGen['argTypes']['Mutation']
> = NexusGen['argTypes']['Mutation'][T];
<file_sep>import { Label, PrismaClient } from 'nexus-plugin-prisma/client';
import { randomPastel } from './';
type LabelConnectors = {
connect: Pick<Label, 'id'>[];
create: Pick<Label, 'value' | 'foreground' | 'background'>[];
};
export async function sequenceAndLabels({
teamId,
projectId,
labels,
}): Promise<{
sequence: number;
labelConnectors: LabelConnectors;
}> {
const prisma = this.prisma as PrismaClient;
const sequence =
(projectId
? await prisma.ticket.count({
where: {
projectId,
},
})
: await prisma.project.count({
where: {
teamId,
},
})) + 1;
let labelConnectors = {
connect: [],
create: [],
};
if (projectId > 0 && labels.length) {
const existingLabels = await prisma.label.findMany({
where: {
...(projectId
? {
OR: [
{
projectId,
},
{
isGlobal: true,
},
],
}
: {
isGlobal: true,
}),
},
select: {
id: true,
value: true,
},
});
labelConnectors = labels.reduce((acc, label) => {
const existingLabel = existingLabels.find(
existingLabel => existingLabel.value === label
);
if (existingLabel) {
acc.connect.push({
id: existingLabel.id,
});
} else {
acc.create.push({
value: label,
background: randomPastel(),
team: {
connect: {
id: teamId,
},
},
project: {
connect: {
id: projectId,
},
},
});
}
return acc;
}, labelConnectors);
}
return {
sequence,
labelConnectors,
};
}
<file_sep>import { log } from 'nexus';
import * as bcrypt from 'bcryptjs';
import * as jwt from 'jsonwebtoken';
import { UserGetPayload, TeamGetPayload } from 'nexus-plugin-prisma/client';
import { AuthenticationError } from 'apollo-server-express';
export function tokenSigner(userId: number): string {
return jwt.sign({ userId }, process.env.APP_SECRET);
}
export function tokenRetriever(bearerToken: string, ignoreExpiration = false): { userId: number } {
const token = bearerToken.split(/^bearer\s/i).pop();
if (token && token !== 'null' && token !== 'undefined') {
try {
const { userId } = jwt.verify(token as string, process.env.APP_SECRET, {
ignoreExpiration,
}) as any;
return {
userId: parseInt(userId, 10),
};
} catch (error) {
log.error(error);
throw new AuthenticationError('Invalid token. Please login to get a valid token.');
}
}
return {
userId: null,
};
}
export async function checkPasswordMatch(
user: UserGetPayload<{ select: { password: true } }>,
password: string
): Promise<boolean> {
return await bcrypt.compare(password, user.password);
}
export function checkUserTeam(
user: UserGetPayload<{
include: { memberTeams: { select: { id: true } }; ownerTeams: { select: { id: true } } };
}>
): boolean {
return !!user.memberTeams.length || !!user.ownerTeams.length;
}
export function checkTeamUser(
team: TeamGetPayload<{
select: {
members: {
select: {
id: true;
};
};
owner: {
select: { id: true };
};
};
}>,
userId: number
): boolean {
return !!team.members.length || team.owner.id === userId;
}
export function randomPastel(): string {
return `hsla(${~~(360 * Math.random())},70%,90%,1)`;
}
export function getUserId(): number {
if (this.request.headers.authorization) {
const { userId } = tokenRetriever(this.request.headers.authorization);
return userId;
}
return void 0;
}
export function getTeamId(): number {
if (this.request.headers.context) {
return parseInt(this.request.headers.context.split(/\s/).pop(), 10);
}
return void 0;
}
<file_sep>import { Provider } from '../../extenders/Provider';
export class Auth extends Provider {
// Add any methods that's not exclusively signin or signup methods here
}
<file_sep>import { Context } from '../services/Context';
import { GraphQLFieldResolver, GraphQLResolveInfo } from 'graphql';
export type Middleware = () => (
root: any,
args: any,
context: Context,
info: GraphQLResolveInfo,
next: GraphQLFieldResolver<any, any>
) => void;
<file_sep>import {
Provider,
ServiceReturn,
ServiceMutationArgs,
ServiceArrayReturn,
} from '../extenders/Provider';
import { sequenceAndLabels } from '../../utils/label-sequence';
export class Project extends Provider {
public async create({
name,
members = [],
}: ServiceMutationArgs<'createProject'>): ServiceReturn<'Project'> {
const { teamId, userId } = this;
const { sequence } = await sequenceAndLabels.call(this, {
teamId,
});
return await this.prisma.project.create({
data: {
name,
sequence,
team: {
connect: {
id: teamId,
},
},
members: {
connect: [...members.map(member => ({ id: member })), { id: userId }],
},
},
});
}
public async getAll(): ServiceArrayReturn<'Project'> {
return await this.prisma.project.findMany({
where: {
teamId: this.teamId,
},
});
}
}
<file_sep>import { config } from 'dotenv';
import { use, schema, settings, server } from 'nexus';
import { prisma } from 'nexus-plugin-prisma';
import { PrismaClient } from 'nexus-plugin-prisma/client';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import * as helmet from 'helmet';
import * as compression from 'compression';
config();
import { ContextInit } from './services/Context';
import { ResourceCheckMiddleware } from './middleware/resource-check';
const prismaClient = new PrismaClient();
use(
prisma({
client: {
instance: prismaClient,
},
})
);
schema.addToContext(request => {
return ContextInit({
request,
db: prismaClient,
});
});
settings.change({
logger: {
pretty: true,
},
});
server.express.use(bodyParser.json());
server.express.use(cors());
server.express.use(helmet());
server.express.use(compression());
schema.middleware(ResourceCheckMiddleware);
<file_sep>import { AuthenticationError } from 'apollo-server-express';
import { Provider, ServiceReturn, ServiceMutationArgs } from '../extenders/Provider';
import { AuthErrors } from '../../errors/auth.errors';
import { sequenceAndLabels } from '../../utils/label-sequence';
export class Ticket extends Provider {
public async create({
projectId,
title,
body,
labels,
}: ServiceMutationArgs<'createTicket'>): ServiceReturn<'Ticket'> {
const { teamId, userId } = this;
const resourceValid = await this.prisma.project.count({
where: {
AND: [
{
id: projectId,
},
{
teamId,
},
{
members: {
some: {
id: userId,
},
},
},
],
},
});
if (!resourceValid) {
throw new AuthenticationError(AuthErrors.PROJECT_ACCESS_DENIED);
}
const { sequence, labelConnectors } = await sequenceAndLabels.call(this, {
labels,
projectId,
teamId,
});
return await this.prisma.ticket.create({
data: {
title,
body,
sequence,
labels: labelConnectors,
team: {
connect: {
id: teamId,
},
},
author: {
connect: { id: userId },
},
project: {
connect: { id: projectId },
},
},
});
}
}
<file_sep>import { schema } from 'nexus';
import { Context } from '../../services/Context';
export default schema.extendType({
type: 'Query',
definition(t) {
t.field('teams', {
type: 'Team',
description: 'Fetch the details of all the teams of a particular user.',
list: true,
async resolve(_, __, ctx: Context) {
return await ctx.team.getAll();
},
});
t.field('teamDetailsFromName', {
type: schema.objectType({
name: 'TeamAuthInfoData',
definition(t) {
t.model('Team').id();
t.model('Team').name();
t.model('Team').displayName();
},
}),
description: 'Fetch the information of a particular team by name.',
args: {
name: schema.stringArg({
required: true,
description: "Team's name to fetch data for.",
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.team.teamDetailsFromName(data);
},
});
},
});
<file_sep># Contributing
We absolutely ❤️ contributions and welcome any kind of contributions from the community.
When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Table of Contents
- [Git Setup](#git-setup)
- [Issue Tracking](#issue-tracking)
- [Pull Request Process](#pull-request-process)
- [Code of Conduct](#code-of-conduct)
- [Our Pledge](#our-pledge)
- [Our Standards](#our-standards)
- [Scope](#scope)
- [Enforcement](#enforcement)
- [Attribution](#attribution)
## Git Setup
To start contributing to this repository, first fork it to your GitHub account. Once you have forked it, run the following commands to setup the upstream.
```bash
git remote add upstream https://github.com/troup-io/troup-server.git
```
Though all of you pushes will continue on `origin`, when you want to sync the forked repository with this repository you can simply run the following command:
```bash
git pull --rebase upstream master
```
Please do remember to properly config your workspace git settings for correct contribution attributions. You can run the following commands:
```bash
git config user.name "YOUR NAME HERE"
git config user.email "YOUR EMAIL HERE"
```
## Issue Tracking
All the issues related to the server are tracked on the [repository itself](https://github.com/troup-io/troup-server/issues). For any discussion regarding the project, or for questions, please feel free to ask on our [Spectrum Chat](http://chat.troup.io).
## Pull Request Process
Ensure any install or build dependencies are removed before the end of the layer when doing a build.
Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters.
Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is SemVer.
You may merge the Pull Request in once you have the sign-off of one other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you.
Every pull request must point to the `master` branch, unless stated otherwise.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [<EMAIL>](mailto:<EMAIL>?subject=Violation%20of%20Troup%20CoC). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant, version 1.4](http://contributor-covenant.org/version/1/4)
<file_sep>import { schema } from 'nexus';
import { Context } from '../../../services/Context';
import { UserData } from '../../../graphql/Types';
export default schema.mutationType({
definition(t) {
t.field('signinUser', {
type: UserData,
description: 'General sign in with an email and return the token and user.',
args: {
email: schema.stringArg({
required: true,
description: "The user's email address.",
}),
password: schema.stringArg({
required: true,
description: "The user's password.",
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.auth.signin.signinUser(data);
},
});
t.field('signinTeam', {
type: schema.objectType({
name: 'TeamSigninData',
definition(t) {
t.field('user', {
type: 'User',
description: 'The user object.',
});
t.string('token', {
description: 'The encoded JWT token.',
});
},
}),
description: 'Team sign in with an email and return the token and user.',
args: {
email: schema.stringArg({
required: true,
description: "The user's email address.",
}),
password: schema.stringArg({
required: true,
description: "The user's password.",
}),
teamId: schema.intArg({
required: true,
description: "The team's ID.",
}),
},
async resolve(_, data, ctx: Context) {
return await ctx.auth.signin.signinTeam(data);
},
});
},
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'UserProfile',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.firstName();
t.model.lastName();
t.model.professionalCompetence();
t.model.utm_source();
t.model.utm_campaign();
t.model.utm_medium();
t.model.utm_term();
t.model.utm_content();
},
});
<file_sep>import { schema } from 'nexus';
export default schema.objectType({
name: 'User',
definition(t) {
t.model.id();
t.model.createdAt();
t.model.updatedAt();
t.model.email();
t.model.ownerTeams({
filtering: true,
ordering: true,
pagination: true,
});
t.model.memberTeams({
filtering: true,
ordering: true,
pagination: true,
});
},
});
<file_sep>import { ApolloError, AuthenticationError } from 'apollo-server-express';
import {
Provider,
ServiceMutationArgs,
ServiceReturn,
ServiceQueryArgs,
ServiceArrayReturn,
} from '../extenders/Provider';
import { TeamErrors } from '../../errors/team.errors';
import { checkTeamUser } from '../../utils';
export class Team extends Provider {
public async checkIfExists({
teamName,
}: ServiceMutationArgs<'checkTeamName'>): ServiceReturn<'Boolean'> {
return !!(await this.prisma.team.count({ where: { name: teamName } }));
}
public async getAll(): ServiceArrayReturn<'Team'> {
return await this.prisma.team.findMany({
where: {
OR: [
{
ownerId: this.userId,
},
{
members: {
some: {
id: this.userId,
},
},
},
],
},
});
}
public async teamDetailsFromName({
name,
}: ServiceQueryArgs<'teamDetailsFromName'>): ServiceReturn<'TeamAuthInfoData'> {
const userId = this.getUserId();
let team;
if (userId) {
team = await this.prisma.team.findOne({
where: { name },
select: {
id: true,
name: true,
displayName: true,
members: {
where: { id: userId },
select: {
id: true,
},
},
owner: {
select: { id: true },
},
},
});
} else {
team = await this.prisma.team.findOne({
where: { name },
select: {
id: true,
name: true,
displayName: true,
},
});
}
if (!team) {
throw new ApolloError(TeamErrors.INVALID_TEAM);
}
if (!checkTeamUser(team, userId)) {
throw new AuthenticationError(TeamErrors.INVALID_TEAM_ACCESS);
}
return team;
}
}
| 5d152c7ccf8b7cd76b9e73e8988fdfe301eb58b8 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 44 | TypeScript | troup-io/troup-server | c5c5b16056e030ff46d75aab924e08774da5483a | dbe995c92ab1867ee2a036ed204fcfaafc165681 |
refs/heads/master | <file_sep><div id="terms" class="modal hide fade">
<a name="terms"></a>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<?= w::h3("terms-head") ?>
</div>
<div class="modal-body">
<?= w::div("terms-body") ?>
</div>
<div class="modal-footer">
<?= w::p("terms-foot") ?>
</div>
</div>
<file_sep><div class="container">
<div class="row" <? if(! w::is_a()) echo 'id="step2"'; ?> >
<? if(! w::is_a()){ ?><form class="form" method="post"><? } ?>
<div class="span5">
<?= w::h2("order-form-h") ?>
<label class="radio inline"><?= w::input("radio", "gender-f", "", "name='gender'") ?>Frau</label>
<label class="radio inline"><?= w::input("radio", "gender-m", "", "name='gender'") ?>Herr</label><br>
<?= w::input("text", "name") ?><br>
<?= w::label("number") ?>
<?= w::input("text", "number") ?><br>
<?= w::input("text", "email") ?>
<?= w::label("street") ?>
<?= w::input("text", "street") ?><br>
<?= w::input("text", "code", "input-mini") ?>
<?= w::input("text", "town", "input-middle") ?>
<label class="checkbox"><?= w::input("checkbox", "accept-terms") ?>AGB akzeptieren</label>
</div>
<div class="span7">
<?= w::h2("order-selected-articles-h") ?>
<div class="well">
<?= w::p("order-info", "alert alert-error") ?>
<script id="add_item" type="text/html">
<li {{#demo}}class="demo"{{/demo}} {{#id}}id="{{id}}"{{/id}}>
<div class="input-append pull-right">
<input class="input-minii" type="text" name="menge" value="{{menge}}" onchange="calculate_order()">
<span class="add-on">{{verpackung}}</span>
</div>
<div class="input-append pull-right" style="margin-right: 10px">
<input class="input-minii" type="text" name="preis" value="{{preis.replace('.',',')}}" data-preis="{{preis}}" disabled>
<span class="add-on">€</span>
</div>
<input type="hidden" name="verpackung" value="{{verpackung}}">
<input type="text" name="artikel" value="{{artikel}}" class="input-unstyled input-medium" disabled>
</li>
</script>
<script id="add_input" type="text/html">
<div class="input-append">
<input class="input-minii" type="text">
<div class="btn-group">
<button class="btn">
<span>{{verpackung}}</span>
</button>
</div>
</div>
</script>
<ul id="order-items" class="unstyled">
</ul>
</div>
</div>
<div class="clearfix center">
<?= w::button("step2-back-btn", "btn") ?>
<?= w::button("step2-btn", "btn btn-large btn-danger", "data-loading-text='Bestellung wurde abgeschickt ...'") ?>
</div>
<? if(! w::is_a()){ ?></form><? } ?>
</div>
</div>
<file_sep><div class="row-fluid" <? if(! w::is_a()) echo 'id="step2"'; ?> >
<? if(! w::is_a()){ ?><form class="form" method="post"><? } ?>
<div class="span5">
<?= w::h2("order-form-h") ?>
<?= w::label("gender-f", "radio inline", "", w::input("radio", "gender-f", "", "name='gender'")) ?>
<?= w::label("gender-m", "radio inline", "", w::input("radio", "gender-m", "", "name='gender'")) ?>
<?= w::input("text", "name") ?><br>
<?= w::input("text", "customer") ?>
<?= w::label("number") ?>
<?= w::input("text", "number") ?><br>
<?= w::input("text", "email") ?>
<?= w::label("street") ?>
<?= w::input("text", "street") ?><br>
<?= w::input("text", "code", "input-mini") ?>
<?= w::input("text", "town", "input-middle") ?>
<?= w::label("accept-terms", "checkbox", "", w::input("checkbox", "accept-terms") ) ?>
</div>
<div class="span7">
<?= w::h2("order-selected-articles-h") ?>
<div class="well">
<?= w::p("order-info", "alert alert-error") ?>
<script id="add_item" type="text/html">
<li {{#demo}}class="demo"{{/demo}} {{#id}}id="{{id}}"{{/id}}>
<div class="input-append pull-right">
<input class="input-mini" type="text" name="menge" value="{{menge}}">
<span class="add-on">{{verpackung}}</span>
</div>
<input type="hidden" name="verpackung" value="{{verpackung}}">
<input type="text" name="artikel" value="{{artikel}}" class="input-unstyled input-medium" disabled>
</li>
</script>
<script id="add_input" type="text/html">
<div class="input-append">
<input class="input-minii" type="text">
<div class="btn-group">
<button class="btn dropdown-toggle" data-toggle="dropdown">
<span>{{verpackung}}</span>
<i class="caret"></i>
</button>
<ul class="dropdown-menu">
<li><a href="#" onclick="order_dropdown(this); return false;">Kg</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Stk</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Tassen</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Kisten</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Bund</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Kolli</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Säcke</a></li>
<li><a href="#" onclick="order_dropdown(this); return false;">Kübel</a></li>
</ul>
</div>
</div>
</script>
<ul id="order-items" class="unstyled">
</ul>
</div>
</div>
<div class="clearfix center">
<?= w::button("step2-back-btn", "btn") ?>
<?= w::button("step2-btn", "btn btn-large btn-danger", "data-loading-text='Bestellung wurde abgeschickt ...'") ?>
</div>
<? if(! w::is_a()){ ?></form><? } ?>
</div>
<file_sep><!doctype html>
<!--[if lt IE 7 ]><html class="ie ie6 no-js" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7 no-js" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8 no-js" lang="en"> <![endif]-->
<!--[if IE 9 ]><html class="ie ie9 no-js" lang="en"> <![endif]-->
<!--[if gt IE 9]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8" http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Pastolore - Der Pizza und Pasta Lieferant Wiens</title>
<?= wirby::head(); ?>
<?= wirby::load('head'); ?>
</head>
<body>
<div id="topline">
<div></div>
</div>
<header>
<div class="container">
<img src="<?= w::asset('img/pastolore.png') ?>" width="40%" ?>
<nav>
<ul>
<li><?= w::a("Unser Angebot", w::to(""), w::is("start")) ?></li>
<li><?= w::a("Online Speisekarte", w::to("order"), w::is("order")) ?></li>
<li><?= w::a("Kontakt", w::to("contact"), w::is("contact")) ?></li>
</ul>
</nav>
</div>
</header>
<div class="main-body">
<? if(w::page()): ?>
<?= w::load(w::page()) ?>
<? else: ?>
<div class="tab-pane" id="start"><?= w::load(w::c("start")) ?></div>
<? endif; ?>
</div>
<div class="container">
<div class="row">
<div class="span12">
<img src="<?= w::asset('img/bg-main-gallery-line.png') ?>" alt="">
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="span7">
<?= w::h2("footer-about-h", "center-responsive") ?>
<img src="<?= w::asset('img/logos.png') ?>" alt="Mesh GmbH" width="100%" />
<?= w::p("footer-about-p") ?>
<p style="text-align: right; margin-top: 0;">
<? if( w::page() != "contact" ): ?>
<a href="<?= w::to('contact') ?>" class="button button-small">
<span class="button-text">Mehr Infos</span>
</a>
<? endif; ?>
</p>
</div>
<div class="span5">
<?= w::h2("footer-test-h", "center-responsive") ?>
<div class="comment-author">
<img src="<?= w::asset('img/women1.png') ?>" alt="">
<?= w::p("footer-test-date", "date") ?>
<?= w::p("footer-test-from", "author") ?>
</div>
<div class="comment-content">
<?= w::p("footer-test-body") ?>
</div>
</div>
</div>
<div class="row">
<div class="span12 copyrights">
<div class="brand">Pastolore</div>
<?= w::p("footer-copy", "hidden-phone") ?>
<a class="fb" href="#"></a>
</div>
<p class="visible-phone" style="text-align: center;">© Ihrem Genuss verpflichtet.</p>
</div>
</div>
</footer>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="<?= w::asset('js/bootstrap.min.js') ?>"></script>
<script src="<?= w::asset('js/lightbox.js') ?>"></script>
<script src="<?= w::asset('js/script.js') ?>"></script>
<? wirby::body(); ?>
</body>
</html>
<file_sep><div id="carousel" class="carousel slide">
<div class="container">
<div class="carousel-inner">
<div class="active item">
<img src="<?= w::asset('img/carousel1.jpg') ?>">
<div class="hidden-phone">
<?# w::div("start-slider-2", "hidden-phone") ?>
WIR LIEFERN RICHTIG GUTE PIZZA UND PASTA!
<span></span>
</div>
</div>
<div class="item">
<img src="<?= w::asset('img/carousel2.jpg') ?>">
<div class="hidden-phone">
PROBIEREN SIE ES GLEICH HEUTE AUS!
<?# w::p("start-slider-2") ?>
<span></span>
</div>
</div>
</div>
<a class="carousel-control left" href="#carousel" data-slide="prev"><img src="<?= w::asset('img/carousel-arrow-left.png') ?>" alt=""></a>
<a class="carousel-control right" href="#carousel" data-slide="next"><img src="<?= w::asset('img/carousel-arrow-right.png') ?>" alt=""></a>
</div>
</div>
<div class="container">
<div class="row">
<div class="span3 box center-responsive">
<?= w::h2("start-box1-h") ?>
<img src="<?= w::asset('img/box1.jpg') ?>" alt="">
<?= w::p("start-box1-p") ?>
<a href="<?= w::to("contact") ?>" class="button-color">
<span class="button-icon"><img src="<?= w::asset('img/icon/mail.png') ?>" alt=""></span>
<span class="button-text">Kontakt</span>
</a>
</div>
<div class="span3 box center-responsive">
<?= w::h2("start-box2-h") ?>
<img src="<?= w::asset('img/box2.jpg') ?>" alt="">
<?= w::p("start-box2-p") ?>
<a href="<?= w::to('order') ?>" class="button">
<span class="button-icon"><img src="<?= w::asset('img/icon/truck.png') ?>" alt=""></span>
<span class="button-text">Bestellung</span>
</a>
</div>
<div class="span6">
<div class="board hidden-phone">
<div class="board-inner">
<div class="item active">
<br>
<p><strong>Menü der Woche</strong></p>
<br>
<ul>
<li>
<span class="left">Margerita</span>
<span class="right">5 €</span><br>
</li>
<li>
<span class="left">Cola / Fanta</span>
<span class="right">2 €</span>
</li>
<li>
<span class="left">Nachspeise</span>
<span class="right">2 €</span>
</li>
</ul>
<p style="text-align: center;">gesamt 9 €</p>
</div>
<div class="item">
<br>
<p><strong>Angebot des Monats</strong></p>
<br>
<ul>
<li>
<span class="left">- Salami Pizza</span>
<span class="right">7 €</span>
</li>
<li>
<span class="left">- Frutti di Mare</span>
<span class="right">9 €</span>
</li>
<li>
<span class="left">- Hot Pepperoni</span>
<span class="right">2 €</span>
</li>
</ul>
</div>
</div>
<ul class="board-nav">
<li class="active"><span></span></li>
<li><span></span></li>
</ul>
</div>
</div>
</div>
</div>
<file_sep><?php
date_default_timezone_set('Europe/Vienna');
header('Content-type: application/json; charset=utf-8');
error_reporting(/*E_ALL*/E_STRICT);
//ini_set('display_errors', TRUE);
/**
** Tracking
**/
function track($note=""){
$type = "mail";
$date = date("Y-m-d H:i:s");
$user = isset($_SESSION["user"]) ? $_SESSION["user"][2] : 0;
$addr = $_SERVER["REMOTE_ADDR"];
$client = $_SERVER["HTTP_USER_AGENT"];
try{
DB::insert("logs", array( "type" => $type, "user" => $user, "date" => $date, "ip" => $addr, "client" => $client, "note" => $note ) );
}catch(Exception $e){ return false; }
return true;
};
// Database
require_once "meekrodb/meekrodb.1.6.class.php";
DB::$user = "cust_knotzer";
DB::$dbName = "cust_knotzer";
DB::$password = "<PASSWORD>";
DB::$encoding = "utf8";
/**
** Email
**/
$email = $_POST["email"];
if( isset($email) ){
if( strlen($email["name"])>2 && strlen($email["address"])>5 && strlen($email["message"])>15 ){
if( preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,6}$/', $email["address"]) ){
try {
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$email["to"] = "<EMAIL>";
$email["body"] = "
<html>
<head> <title>Homepage Kontaktaufnahme</title> </head>
<body>
<p>Hallo Michael.</p>
<p>Diese Nachricht wurde über das Kontaktformular<br />
der Homepage verschickt:</p>
<table width='500px'>
<tr><td width='100px'><b>Name</b></td><td>" . $email["name"] . "</td></tr>
<tr><td><b>Email</b></td><td><a href='mailto:" . $email["address"] . "'>" . $email["address"] . "</a></td></tr>
<tr><td><b>Nachricht</b></td><td>" . $email["message"] . "</td></tr>
</table>
<br /><a href='mailto:" . $email["address"] . "'><b>Antworten</b></a>
</body>
</html>
";
$mail->AddAddress($email["to"], "Michael");
$mail->SetFrom("<EMAIL>", "web architects");
$mail->AddReplyTo($email["address"], $email["name"]);
$mail->Subject = "Homepage Kontaktaufnahme";
$mail->AltBody = $email["message"];
$mail->CharSet = "utf-8";
$mail->MsgHTML( $email["body"] );
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 1; // enables SMTP debug information (1 = errors and messages, 2 = messages only)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "wp239.webpack.hosteurope.de"; // SMTP server
$mail->Username = "wp10566993-webarchitects"; // SMTP account username
$mail->Password = "<PASSWORD>"; // SMTP account password
$send = $mail->Send();
track($email["address"].": ".substr($email["message"],0,200)." ...");
$output = array(
"status" => ($send ? "success" : "error"),
"from" => $email["address"],
"to" => $email["to"],
"msg" => $email["body"]
);
} catch (Exception $e) { json_encode( array("status" => "error", "error" => ($e->getMessage()) ) ); };
} else $output = array( "status" => "error", "error" => "Email nicht gültig" );
} else $output = array( "status" => "error", "error" => "Bitte alles ausfüllen" );
} else $output = array( "status" => "error", "error" => "Bitte über das Formular verschicken" );
echo json_encode($output);
/* Standard Mail
$email["to"] = "<EMAIL>";
$email["from"] = "<EMAIL>";
$email["subject"] = "Homepage-Kontakt";
$email["header"] =
"To: " . $email["to"] . "\r\n" .
"From: " . $email["from"] . "\r\n" .
"Reply-To: " . $email["address"] . "\r\n" .
"X-Mailer: PHP/" . phpversion() .
"MIME-Version: 1.0" . "\r\n" .
"Content-type: text/html; charset=iso-8859-1" . "\r\n";
$send = mail($email["to"], $email["subject"], $email["body"], $email["header"]);
*/
?><file_sep><?= w::h1("about-h1"); ?>
<?= w::img("about-img", "Foto vom Lager", 300); ?>
<?= w::p("about-p"); ?>
<?= w::h2("about-h2"); ?>
<?= w::div("about-div"); ?>
<file_sep>function maps_ready(){
if(! $("#map").length){
log("map not embedded");
}
else{
log("map ready");
var mapCenter = new google.maps.LatLng(48.1709, 16.359);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, //DROPDOWN_MENU
position: google.maps.ControlPosition.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE, //SMALL
position: google.maps.ControlPosition.LEFT_TOP
},
panControl: false, // drag-move
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
});
var markerPos = new google.maps.LatLng(48.13755, 16.35952);
var marker = new google.maps.Marker({
position: markerPos,
map: map,
label: "M",
title:"M&M Obst und Gemüse"
});
};
};
function log(msg){
if(typeof console != "undefined") console.log(msg);
};
function site_ready(){
log("site ready");
// init jQuery.address for tabs
$.address.history(true) // browser
.strict(true) // "/"
.tracker($.noop); // do it the own way
$.address.change(function(event) { // internal and external
var id = event.path.split("/")[1];
log("addressed "+id);
$("#tab-"+id).tab('show');
});
// prepare tabs
if(window.no_ajax){
log("we won't load contents");
}
else if($(".tab-content").length){ // if there isn't a specific site
$(".tab-content").load("/", {"type":"content"}); // load "everything" now
$("#tab-menu a").each(function(i,a){
$(a).attr("href", "#"+$(a).attr("href"));
});
$("#tab-menu a").bind("click", function(e){
e.preventDefault();
var id = $(this).attr("href").split("#")[1];
log("clicked "+id);
$.address.value(id);
return false;
});
};
s = window.scroll = {
elm: $(".scroll-elm"), // (header) scrollable 'elm'
from: $(".scroll-from").offset().top, // (content) check if 'from' touches 'elm'
to: -($(".scroll-to").offset().top - 10), // (menu) if so: scroll it to this position
done: false
};
s.fromelm = s.elm.offset().top + s.elm.height();
s.diff = s.from - s.fromelm; // check the bottom edges
$(window).on("scroll", function(e){
s = window.scroll;
s.is = window.pageYOffset;
console.log(s);
if( s.is >= s.diff ){
if(s.done == false){
// s.at = s.diff - s.is;
// if(s.at <= s.to){ s.done = true; s.at = s.to}
s.done = true;
s.elm.animate({top: s.to}, "fast");
}
}else{
if(s.done == true){
s.done = false;
s.elm.animate({top: 0});
}
}
});
// activate if there is one active
//$("#tab-menu .active a").trigger("click");
// prepare email links
$("a").each(function(i,a){
var link = $(a);
if (link.text().match(/\(a\)/)){
var text = link.text().replace("(a)","@");
link.text(text).attr("href","mailto:"+text);
};
});
// prepare contact form
$("input,textarea")
.each(function(i){ // also on focus in
if(!$(this).data("val")) $(this).data("val", $(this).val());
})
.bind("focusin focusout", function(){
if($(this).val()==$(this).data("val")) $(this).val("");
else if(!$(this).val().length) $(this).val($(this).data("val"));
});
$("#contact").bind("submit", function(e){
e.preventDefault();
contact();
});
$("#contact a").bind("click", function(e){
e.preventDefault(); $("#contact").trigger("submit"); return false;
});
log("form binded");
if(window.no_dataTable){
log("datatable not rendered");
}
else if( $(".dataTable table").length ){
// add templates to dom
ich.grabTemplates();
log("templates added");
// prepare order form
window.dataTable = $(".dataTable table").dataTable( {
"sDom": "<'row-fluid'<'pull-left'f><'pull-left'p><'pull-right'ri>><'row-fluid't><'pull-left'p>",
"bStateSave": false,
"bAutoWidth": true,
"bSort": false,
"bPaginate": true,
"sPaginationType": "bootstrap",
"bLengthChange": false,
"iDisplayLength": 60,
"oLanguage": {
"sSearch": "Nach _INPUT_ suchen",
"oPaginate": {
"sFirst": "‹‹",
"sLast": "››",
"sNext": "",
"sPrevious": ""
},
"sInfo": "_START_ bis _END_ aus <span class='label label-important'>_TOTAL_ Artikel</span>",
"sInfoFiltered": " von _MAX_ gesamt",
"sInfoEmpty": "gefiltert <span class='label label-important'>nichts gefunden</span>",
"sEmptyTable": "Wir aktualisieren gerade unser Produktsortiment. Bitte kontaktieren Sie uns telefonisch.",
"sZeroRecords": "Diesen Artikel führen wir leider nicht. Ändere gegebenenfalls den Suchfilter oberhalb."
},
"aoColumns": null,
"fnCreatedRow": function( row, data, index ) {
$("td", row).first().prepend( $("<input>").attr("type", "checkbox") );
// if the checkbox is clicked, the TableTools click is also triggered, so there is no binding necessary
var last = $("td", row).last();
last.html( ich.add_input({
"verpackung": last.text()
}) );
last.find("input").on("blur change", function(e){
check_item( last.parent()[0] );
});
}
} );
log("datatable created");
window.dataTools = new TableTools(dataTable, {
"sRowSelect": "multi",
"sSelectedClass": "active",
"fnRowSelected": function(nodes){ check_item(nodes[0]); },
"fnRowDeselected": function(nodes){ check_item(nodes[0]); }
} );
log("datatable tools");
// add demo chart
ich.add_item({
"demo": true,
"artikel": "Ananas Extra Sweet",
"menge": 5,
"verpackung": "Stk"
}).appendTo("#order-items");
ich.add_item({
"demo": true,
"artikel": "Apfel Golden Delicious",
"menge": 8,
"verpackung": "kg"
}).appendTo("#order-items");
// bind buttons
$("#step1-btn").on("click", function(){
order_items();
$("#step1").hide();
$("#step2").show();
});
$("#step2-btn").on("click", function(){
//$(this).addClass("disabled");
send_order();
});
$("#step2-back-btn").on("click", function(){
$("#step2").hide();
$("#step1").show();
});
log("buttons binded");
} else {
log("datatable not embedded");
};
};
function check_item(row){
var input = $("input:text", row);
if(window.dataTools.fnIsSelected(row)){
if(!input.val().length){
window.dataTools.fnDeselect(row);
}else{
$("input:checkbox", row).attr("checked", true);
};
}else{
if(input.val().length){
window.dataTools.fnSelect(row);
}else{
$("input:checkbox", row).attr("checked", false);
};
};
};
function order_items(){
rows = window.dataTools.fnGetSelected();
$(rows).each(function(i, row){
order_item(row);
});
};
function order_item(row){
var data = window.dataTable.fnGetData(row); // original data
//var head = window.dataTable.fnGetData($("thead tr").first()[0]); // is null
var list = $("#order-items");
var info = $("#order-info");
var name = unescape(data[0].replace(/[\s\W]/g,"-").toLowerCase());
var item = $("#order-item-"+name);
if( item.length ) {
item.remove();
};
ich.add_item({
"id": "order-item-"+name,
"artikel": data[0],
"menge": $("input:text", row).val(),
"verpackung": $("button", row).text().trim()
}).appendTo(list);
$(".demo", list).remove();
info.removeClass("alert-error").text("In deiner Bestellung befinden sich "+list.children().length+" Artikel.");
};
function order_dropdown(element){
console.log(element);
var e = $(element);
var d = e.parents("ul").siblings("button").find("span");
d.text( e.text() );
};
function send_order(){
var items = [];
$("#order-items").children("li").each(function(i, item){
item = $(item);
items.push([
item.find("input[name=artikel]").val(),
item.find("input[name=menge]").val(),
item.find("input[name=verpackung]").val()
]);
});
var post = {
"name": $("input[name=gender]:checked").val()+" "+$("input[id=name]").val(),
"customer": $("input[id=customer]").val(),
"number": $("input[id=number]").val(),
"email": $("input[id=email]").val(),
"street": $("input[id=street]").val(),
"code": $("input[id=code]").val(),
"town": $("input[id=town]").val(),
"items": items
}
if($("input[id=terms]").is(":checked")){
if(
$("input[name=gender]:checked").length > 0 &&
post.name.length > 0 &&
post.customer.length > 0 &&
post.number.length > 0 &&
post.email.length > 0 &&
post.street.length > 0 &&
post.code.length > 0 &&
post.town.length > 0
){
$("#step2-btn").addClass("disabled");
$.ajax({
url: "/",
type: "post",
data: { "type": "order", "order": post },
dataType: "json",
success: function(data, text, xhr){
log(data.msg);
alert("Danke für die Bestellung, "+data.name+"!");
},
error: function(xhr, text, error){
log(text+":");
log(error);
alert("Leider ist ein Fehler aufgetreten.\nRufen Sie uns bitte unter +43 660 6522007 an.\nDanke!")
},
complete: function(){
$("#step2-btn").removeClass("disabled");
}
});
}
else alert("Bitte fülle alle Daten aus. Danke!");
}
else alert("Bitte akzeptiere unsere Geschäftsbedingungen. Danke!");
}
// Validate Contact Form
function contact(){
var post = {
"name": $("#contact-name").val(),
"email": $("#contact-email").val(),
"number": $("#contact-number").val(),
"subject": $("#contact-subject").val(),
"message": $("#contact-message").val()
};
log(post);
if(
post.name.length > 0 &&
post.number.length > 0 &&
post.email.length > 0 &&
post.subject.length > 0 &&
post.message.length > 0
){
$("#contact-btn").addClass("disabled");
$.ajax({
url: "/",
type: "post",
data: { "type": "contact", "contact": post },
dataType: "json",
success: function(data, text, xhr){
log(data.msg);
alert("Danke für die Nachricht, "+data.name+"!");
},
error: function(xhr, text, error){
log(text+":");
log(error);
alert("Leider ist ein Fehler aufgetreten.\nRufen Sie uns bitte unter +43 660 6522007 an.\nDanke!")
},
complete: function(){
$("#contact-btn").removeClass("disabled");
}
});
}
else alert("Um Ihnen schnellstmöglich zu antworten,\nsind alle Angaben nötig. Danke!");
};
/**
* Slide Tabs
*
var slide = function(id){
if(!id) id="knotzer";
log("slide ("+id+")");
var box = $("#wide");
var tab = $("#"+id);
if(!tab.length) tab = $("#knotzer");
var pos = tab.position().left;
$("#menu .current").removeClass("current");
$("."+id).parent().addClass("current");
$("div.tab").hide();
tab.show();
box.fadeOut(0, function(){
$(this).css({"left":-pos}).fadeIn(0, function(){
if(id=="kontakt"){
if(typeof google != "undefined" && $.isFunction(google.maps.Map)) window.setTimeout(showMaps, 10);
else log("no Google");
$("#button").hide();
}else $("#button").fadeIn(200);
});
});
};
// Slide Leistungen
function initLeistungen(){
var leistungenText = $(".slide div");
leistungenText.each( function(i, text){
var id = $.trim( $(this).prev("h2").text() );
var height = $(this).height();
if (height>0) $(this).css({"height": height});
else {
window.setTimeout(function(){log("fuck");initLeistungen();},500);
return false;
};
log(height+"px for "+id);
});
leistungenText.hide();
//leistungenText.first().show();
var leistungenHead = $(".slide h2");
//leistungenHead.first().addClass("active");
leistungenHead.unbind("click").bind("click", function(){
var head = $(this); //"#"+$(this).attr("id")
var text = $(this).next("div"); //head.replace("head","text");
log("show "+$.trim( $(this).text() ));
$(".slide h2").not(head).removeClass("active");
$(head).addClass("active");
$(".slide div").not(text).slideUp(200);
$(text).slideDown(200);
});
};
// Insert Google Maps
function showMaps() {
log("showMaps ()");
$("#maps").css({"height":300,"width":500});
var mapCenter = new google.maps.LatLng(48.2327, 16.3288);
var map = new google.maps.Map(document.getElementById("maps"), {
zoom: 13,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, //DROPDOWN_MENU
position: google.maps.ControlPosition.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE, //SMALL
position: google.maps.ControlPosition.LEFT_TOP
},
panControl: false, // drag-move
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
});
var markerPos = new google.maps.LatLng(48.23874, 16.31957);
var marker = new google.maps.Marker({
position: markerPos,
map: map,
label: "K",
title:"Dr. <NAME>"
});
};
// function codeMaps(map, street){
// var address = $("#maps").attr("data-maps");
// var geocoder = google.maps.Geocoder()
// if (geocoder){
// geocoder.geocode( { 'address': street}, function(results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// var marker = new google.maps.Marker({
// map: map,
// position: results[0].geometry.location
// });
// } else {
// alert("Geocode was not successful for the following reason: " + status);
// }
// });
// }
// }
// Google Maps Images dynamically
// var map1 = $("<img>"); map1.attr("src", "http://maps.google.com/maps/api/staticmap?center=48.23474,16.31957&zoom=14&size=640x273&maptype=roadmap&markers=color:gray%7Clabel:K%7C48.23874,16.31957&sensor=false");
// var map2 = $("<img>"); map2.attr("src", "http://maps.google.com/maps/api/staticmap?center=48.23474,16.35610&zoom=14&size=210x273&maptype=roadmap&sensor=false");
// $("#map1").html(map1); $("#map2").html(map2);
//
//
// function loadMaps() {
// log("loadMaps ()");
// var script = document.createElement("script");
// script.type = "text/javascript";
// script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=showMaps&key=<KEY>";
// document.body.appendChild(script);
// };
//
// window.onload = function () {
// setTimeout(function () {
// window.scripts = [];
// (function () {
// if(src = window.scripts.shift()) {
// tag = document.createElement('script');
// tag.setAttribute('type','text/javascript');
// tag.setAttribute('src', src);
// document.getElementsByTagName('head')[0].appendChild(tag);
// tag.onload = arguments.callee;
// };
// })();
// }, 1);
// }
*/
<file_sep><?php
$root = dirname(__FILE__);
require_once( "wirby/load.php");
$site = new Wirby();
echo $site->render();
?>
<file_sep><?= w::img("start-img", "<NAME>", 400) ?>
<?= w::h1("start-h1") ?>
<?= w::h2("start-h2") ?>
<?= w::p("start-p") ?>
<?= w::h2("start-schlagzeile") ?>
<?= w::div("start-div") ?>
<? // w::img("start-telefon", "Rufen Sie uns an", 200) ?>
<file_sep><?php
/**
* Domain mapping
*/
c::set("domains", array(
"gemuese.test" => "gemuese",
"celik-obstgemuese.at" => "gemuese",
"www.celik-obstgemuese.at" => "gemuese",
"pastolore.test" => "pastolore",
"pastolore.webarchitects.at" => "pastolore",
"www.pastolore.webarchitects.at" => "pastolore"
));
/**
* Routen
*/
c::set("routes", array(
/* Gemüsehändler */
"gemuese.de" => array(
"aktuelle-angebote" => "news",
"online-bestellung" => "order",
"obst-korb" => "fruits",
"ueber-celik" => "about",
"kontakt" => "contact",
"impressum" => "contact"
),
"gemuese.en" => array(
"actual-offers" => "news",
"online-order" => "order",
"fruits-basket" => "fruits",
"about-celik" => "about",
"contact" => "contact",
"imprint" => "contact"
),
"gemuese.es" => array(
"noticias-ofertas" => "news",
"tienda-online" => "order",
"cesta-de-frutas" => "fruits",
"quienes-somos" => "about",
"contacto" => "contact",
"imprenta" => "contact"
),
"pastolore.de" => array(
"online-bestellung" => "order",
"kontakt" => "contact"
)
));
?>
<file_sep><?= w::h1("imprint-h1"); ?>
<?= w::div("imprint-p"); ?>
<?= w::h2("imprint-privacy-h2"); ?>
<?= w::p("imprint-privacy"); ?>
<file_sep>window.wirby_editors = []; // editors
window.wirby_changes = []; // changed editors' ids
function wirby_ready(){
log("CMS: started");
// Editors
wirby_editors = $("[data-wirby]").not("a");
$("#wirby-editors").text(wirby_editors.length+" Editoren");
log("CMS: "+wirby_editors.length+" Editors found");
// Init CKEditor
wirby_editors.each(function(i, elm){
wirby_make( elm );
});
//wirby_editors.on("click",function(e){
// wirby_changed( $(this).attr("id") );
//});
};
var wirby_count = 0;
function wirby_changed(id){
if($.inArray(id, wirby_changes) == -1){
wirby_changes.push(id);
wirby_count++;
var l = $("body").data("lang");
var s = wirby_count>1 ? "Änderungen" : "Änderung";
var a = $("<a>")
.attr({"href": "#", "title": "Alle "+(l?l+" ":"")+"Inhalte abschicken"})
.text(wirby_count+" "+s+" speichern");
$("#wirby-editors").html(a);
$("#wirby-editors a").unbind("click").bind("click", function(e){ e.preventDefault(); wirby_save(); });
};
};
function wirby_save(){
var contents = {};
var lang = $("body").data("lang") || "de";
$.each(wirby_changes, function(i, id){
console.log("CMS: Save "+id);
var content = null;
if( content = $("#"+id).is("img") ) content = $("#"+id).attr("src");
else content = CKEDITOR.instances[id].getData().replace(/ /gi, " ");
if( content ) contents[id] = content;
else console.log("Fehler bei id="+id);
});
$.ajax({
url: "/",
type: "post",
data: { "type": "update", "contents": contents, "lang": lang },
dataType: "json",
success: function(data, text, xhr){
log(data);
var txt = data["updated"]+" geändert";
if(data["inserted"]) txt += " "+data["inserted"]+" hinzugefügt";
$("#wirby-editors").html( txt );
wirby_changes = [];
wirby_count = 0;
},
error: function(xhr, text, error){
log(text+":");
log(error);
}
});
};
function wirby_make(editor){
$editor = $(editor); // jquery object, the other one is pure html
var id = $editor.attr("id"); // if specified by template
if(!id) id = $editor.data("wirby"); // otherwise take the wirby identifier
$editor.attr("id", id); // set it explicitly to avoid problems
if($editor.is("a")){
// TODO: editable menu
}
else if($editor.is("img")){
wirby_make_img($editor);
}
else{
// http://docs.ckeditor.com/#!/guide/dev_toolbar
var config = {
allowedContent: true, // http://docs.ckeditor.com/#!/guide/dev_advanced_content_filter
toolbarGroups: [
{ name: "undo", groups: [ "undo", "cleanup" ] },
{ name: "basicstyles", groups: [ "basicstyles", "links" ] }
],
on: {
"instanceReady": function(){ console.log("CMS: editor ready"); },
"key": function(){ wirby_changed( id ); }
}
};
if(! $editor.is("h1,h2,h3,h4,h5,h6,span")){
config.toolbarGroups.push(
{ name: "clipboard" }
);
}
if($editor.is("div")){
config.toolbarGroups.push(
"/",
{ name: "align" },
{ name: "paragraph", groups: [ "list", "indent" ] },
{ name: "blocks", groups: [ "blocks", "tools" ] },
{ name: "find" }
);
};
$editor.attr("contenteditable", "true");
CKEDITOR.inline(editor, config);
};
function wirby_make_img($editor){
//var width = $editor.width();
//var height = $editor.height();
var $wrapper = $editor.parent(".img"); // it is yet wrapped
if(!$wrapper.length){
console.log("not wrapped");
$wrapper = $("<div>").addClass("img"); // wrap it if not
$editor.wrap($wrapper);
};
//$wrapper.css({"height":height, "width":width});
var $uploader = $("<div>").addClass("uploader");
$uploader.appendTo($wrapper).fineUploader({ // https://github.com/valums/file-uploader/blob/master/readme.md#options-of-both-fineuploader--fineuploaderbasic
debug: true,
multiple: false,
request: { endpoint: '/?type=upload' },
deleteFile: { enabled: false }, // https://github.com/valums/file-uploader/blob/master/docs/options-fineuploaderbasic.md#deletefile-option-properties
dragAndDrop: {
hideDropzones: false,
disableDefaultDropzone: true,
extraDropzones: [$wrapper.get()[0], $uploader.get()[0]]
},
text: {
uploadButton: 'Hierher ziehen oder klicken',
cancelButton: 'X',
retryButton: 'Test',
failUpload: 'Fehler',
dragZone: 'Hierher ziehen',
dropProcessing: 'Losgelassen',
formatProgress: "{percent}% von {total_size}",
waitingForResponse: "Bitte warten"
}
});
$uploader.on("complete", function(e, id, file, json){
$editor.attr("src", "/gemuese/files/"+file);
$editor.data("img", file);
wirby_changed( $editor.data("wirby") );
});
console.log($wrapper);
// var $form = $("<input>").attr({"type":"file"});
// $editor.css({"height":height, "width":width});
// $form.css({"height":height, "width":width});
// console.log($form);
// $form.attr({"id": info.id, "name": images+"["+info.id+"]"});
// var dropZone = $("#area-avatar");
// var dropNear = function(){ dropZone.addClass("drag"); };
// var dropOver = function(){ dropZone.addClass("drop"); };
// var dropOut = function(){ dropZone.removeClass("drag drop"); };
// var avatarChoosen = function(event, files, index, xhr, handler, callBack){
// formNote(l.note.thanks, l.note.success.profile_avatar, "#form-profile-avatar", "success");
// $("#profile-avatar-label").text(l.account.avatarLoading);
// callBack(); // start uploading
// };
// var avatarLoading = function(e, files, index, xhr, handler){
// var percent = parseInt(e.loaded / e.total * 100, 10);
// log("snapAuth: avatarProcess", percent+"%");
// if(percent>=99) $("#profile-avatar-label").text(l.account.avatarProcess);
// else $("#profile-avatar-label").text(l.account.avatarLoading+" ("+percent+"%)");
// };
// var avatarLoaded = function(e, files, index, xhr, handler){
// log("snapAuth: avatarProcess", "finish");
// var text = xhr.responseText? xhr.responseText : (xhr.contents() && xhr.contents().text());
// var json = $.parseJSON( text );
// var avatar = (json&&json.user) ? json.user.avatar_urls.thumb : false;
// if(!avatar) formNote(l.note.error, l.note.profile_avatar, "#form-profile-avatar");
// else {
// that.user.avatar_urls = {"thumb": avatar};
// $("#profile-avatar-thumb").attr('src', avatar);
// $("#profile-avatar-label").text(l.account.avatarLoaded);
// dropOut();
// };
// window.setTimeout(function(){
// $("#profile-avatar-label").text(l.account.avatarChoose);
// }, 2000);
// };
//
// // IE BUG
// // Object doesn't support this property or method" in snap2.js, zeile 185, zeichen 127
// $("#form-profile-avatar").fileUpload({
// "dragDropSupport": true, "dropZone": dropZone,
// "url": conf.urlUserAvatar, "method": "POST",
// "name": "user[avatar]", "multipart": true,
// "onProgress": avatarLoading,"onLoad": avatarLoaded,
// "initUpload": avatarChoosen,"onDocumentDragOver": dropNear,
// "onDragOver": dropOver, "onDragEnter": dropOver, "onDrop": dropOver
// });
};
};
<file_sep><script type="text/javascript" language="javascript">
head.js( <?= "'".join("','",w::c("assets_js"))."'"; ?> );
<? if(w::is_a()){ ?>
head.js( <?= "'".join("','",w::c("assets_admin"))."'"; ?> );
CKEDITOR.disableAutoInline = true;
<? } ?>
head.ready( function(){
<?= w::c("assets_callback"); ?>();
<? if(w::is_a()){ ?>
wirby_ready();
<? } ?>
});
</script>
<? if(w::in_a()){ ?>
<div class="navbar navbar-fixed-<?= w::c('adminbar_position') ?>">
<div class="navbar-inner">
<a class="brand" href="#">Bearbeitungsmodus</a>
<ul class="nav">
<li><a href="#"><i class="icon-refresh"></i> <span id="wirby-editors">
<?if(w::is_a()){?>startet ...<?}else{?>wartet ...<?}?></span></a></li>
<li><a if="wirby-explain">
<? if(w::c("has_error")) { ?>
<?= w::c("has_error"); ?>
<? } // Logged in
elseif(w::is_a()) { ?> Sie können nun unterhalb Inhalte bearbeiten
<? } // Log in
else{ ?> Bitte melden Sie sich an:
<? } ?>
</a></li>
</ul>
<? if(w::is_a()) { ?>
<ul class="nav pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Hallo, <?= w::c("admin", "name") ?> <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="#"><i class="icon-lock"></i> Passwort ändern</a></li>
<li><a href="?type=logout"><i class="icon-home"></i> Abmelden</a></li>
</ul>
</li>
</ul>
<? } else { ?>
<form class="navbar-form pull-right" method="post">
<input name="user" type="text" class="span2" placeholder="Benutzer">
<input name="pass" type="<PASSWORD>" class="span2" placeholder="<PASSWORD>wort">
<input name="type" type="hidden" value="login">
<input name="edit" type="hidden" value="1">
<button type="submit" class="btn"><i class="icon-lock"></i></button>
</form>
<? } ?>
</div>
</div>
<? } else { ?>
<a class="wirby" href="/admin"><i class="icon-wrench icon-white"></i></a>
<? } ?>
<file_sep>
<div class="container">
<div class="row">
<div class="span12">
<?= w::h2("order-h2"); ?>
<?= w::p("order-p"); ?>
</div>
</div>
</div>
<div class="container" id="step1">
<div class="row">
<div class="span12">
<?= w::h2("order-h2-categories"); ?>
<div class="dataTableFilters">
<?= w::div("order-categories"); ?>
</div>
<?= w::h2("order-h2"); ?>
<? if(w::is_a()){ ?>
<script type="text/javascript">
window.no_dataTable = true;
</script>
<? } ?>
<div class="dataTable">
<?= w::div("order-articles"); ?>
</div>
</div>
<div class="clearfix center">
<?= w::button("step1-btn", "btn btn-large btn-danger", "", "id='step1-btn'") ?>
</div>
</div>
</div>
<? w::load("order2") ?>
<file_sep><meta name="generator" content="Wirby" />
<link type="text/css" rel="stylesheet" href="/wirby/libs/bootstrap/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="/wirby/libs/bootstrap/css/bootstrap-responsive.min.css" />
<link type="text/css" rel="stylesheet" href="/wirby/assets/datatable.bootstrap.css" />
<? if(w::in_a()) { ?>
<script type="text/javascript" src="/wirby/libs/ckeditor/ckeditor.js"></script>
<script src="/wirby/libs/fileuploader/client/js/header.js"></script>
<script src="/wirby/libs/fileuploader/client/js/util.js"></script>
<script src="/wirby/libs/fileuploader/client/js/button.js"></script>
<script src="/wirby/libs/fileuploader/client/js/ajax.requester.js"></script>
<script src="/wirby/libs/fileuploader/client/js/deletefile.ajax.requester.js"></script>
<script src="/wirby/libs/fileuploader/client/js/handler.base.js"></script>
<script src="/wirby/libs/fileuploader/client/js/window.receive.message.js"></script>
<script src="/wirby/libs/fileuploader/client/js/handler.form.js"></script>
<script src="/wirby/libs/fileuploader/client/js/handler.xhr.js"></script>
<script src="/wirby/libs/fileuploader/client/js/uploader.basic.js"></script>
<script src="/wirby/libs/fileuploader/client/js/dnd.js"></script>
<script src="/wirby/libs/fileuploader/client/js/uploader.js"></script>
<link type="text/css" rel="stylesheet" href="/wirby/assets/style.css" />
<? } ?>
<script type="text/javascript" src="<?= w::c('assets_loader') ?>"></script>
<? if(w::c("google_analytics")) { ?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<?= w::c("google_analytics") ?>']);
_gaq.push(['_setDomainName', '<?= w::c("domain") ?>']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<? } ?>
<? if(w::c("google_plus")) { ?>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{lang: 'de'}
</script>
<? } ?>
<? if(w::c("microsoft_verification")) { ?>
<meta name="msvalidate.01" content='<?= w::c("microsoft_verification") ?>' />
<? } ?>
<style type="text/css">
a.wirby { display: block; position: fixed; left: 5px; bottom: 5px; width: 20px; height: 20px; opacity: 0.0; }
a.wirby:hover { opacity: 0.7; -webkit-transition: all 0.5s; -moz-transition: all 0.5s; transition: all 0.5s; }
</style>
<file_sep><?php
c::set("google_analytics", false); // "UA-7082989-19");
c::set("adminbar_position", "top");
c::set("mail.ourself", array("Pastolore", "+43 676 4721227") );
c::set("mail.to", array("<EMAIL>", "Bestellsystem") );
c::set("mail.to2", array("<EMAIL>", "Betreuer") );
c::set("mail.from", array("<EMAIL>", "Pastolore Mesh") );
c::set("mail.host", "smtp.gmail.com");
c::set("mail.user", "<EMAIL>");
c::set("mail.pwd", "<PASSWORD>");
c::set("mail.auth", true);
c::set("mail.secure", "tls");
c::set("mail.debug", 1); // (1 = errors and messages, 2 = errors only)
?>
<file_sep><?php
date_default_timezone_set("Europe/Vienna");
if($debug = true){
error_reporting(E_ALL); // E_STRICT
ini_set("display_errors", false);
}
c::set("has_error", false); // error message
c::set("has_info", false); // info msg
c::set("in_wirby", false); // we opened the CMS
c::set("is_admin", false); // we logged in sucessfully
s::start();
class Wirby {
function __construct() {
self::log("Wirby loaded");
$this->language(); // init: language from server
$this->route(); // init: routing with localization
$this->database(); // init: connect database
$this->forms(); // forms: order, contact
$this->session(); // admin: check admin session
$this->admin(); // admin: render wirby
// returnvalue has to be an object ... return $this->render(); // content: render
}
/*****************************************************************************
* System
*/
static function test($debug){
echo "Wirby logger exits: \n";
print_r( $debug ? $debug : date('Y-m-d H:i:s') );
exit;
}
static function log(){
global $root, $debug;
if($debug == true){
$msg = "".date('Y-m-d H:i:s');
foreach (func_get_args() as $a) $msg .= "\t".$a;
error_log($msg."\n", 3, $root."/wirby/logs/wirby.log");
// https://docs.google.com/spreadsheet/ccc?key=<KEY>#gid=null
// $messages = '?logID=agtzfmxvZy1kcml2ZXILCxIDTG9nGLmCBww';
// foreach (func_get_args() as $a) $messages .= ("&m%5B%5D=".urlencode($a));
// $fp = fsockopen("log-drive.appspot.com", 80);
// $h = "GET /logd$messages HTTP/1.1\r\n";
// $h .= "Host: log-drive.appspot.com\r\n";
// $h.= "Connection: Close\r\n\r\n";
// fwrite($fp, $h);
// fclose($fp);
}
}
static function alternative($array, $key, $array2, $key2){
if(! $array) $array = $array2; // fallback if even the main array does not exist
if(! $array2) $array2 = $array; // alternative in another array, or in the same one
if(! $key2) $key2 = $key; // just use the same as within the main array
return a::get($array, $key, a::get($array2, $key2, false));
}
/**
* Language
*/
function language(){
//s::remove("language");
$lang = r::get("lang", c::get("language")); // l::current() ... if it's set try it, otherwise use default
l::change($lang); // checks if it's allowed and set it
// check it with l::current()
w::log("Language", $lang);
}
/**
* Database connect
*/
function database(){
if(! db::connect() ){
die("Wirby: database connection failed! check config file");
} else { c::set("db.password", "***"); } // delete it caz it's unnecessary now
return db::connection();
}
/**
* Routing
*/
function route(){
c::set("url", url::current() );
c::set("base_url", rtrim(url::strip_hash( url::strip_query(c::get("url")) ), "/") );
c::set("domain", url::short( c::get("url"), false, true, "") );
if( $domains = c::get("domains") ){ // all domains for several projects
foreach( $domains as $domain => $name ){
if( $domain == c::get("domain") ){ // if there is one matching the current one
c::set("site", $name); // this project's folder
}
}
if(!c::get("site") ){ // the folder info is necessary for Wirby
die("Wirby: the current domain '".c::get("domain")."' is not specified in your routes.php file.");
}
}
else { // there are no domains at all
die("Wirby: please create a routes.php file and specify domains over there.");
}
// set paths
global $root;
c::set("wirby_path", $root."/"."wirby/assets/"); // template dir for internal wirby dom
c::set("site_path", $root."/".c::get("site")."/" );
c::set("tmpls_path", c::get("site_path").c::get("tmpls_path")."/" ); // template dir in project folder
// include custom config
$config = c::get("site_path")."/config.php";
if($config) c::load( $config );
//else echo "Keine Einstellungen unter $config gefunden";
// prepare localized routes
$routes = c::get("routes"); // load all routes
if(! $routes){ die("Wirby: routes are not defined"); }
$i18n = $routes[c::get("site").".".l::current()]; // matched language
$fall = $routes[c::get("site").".".c::get("language")]; // default language fallback
if(!$fall) $fall = $routes[c::get("site")]; // (n)one language at all
if(!$fall && !$i18n){ die("Wirby: routes are missing for ".c::get("site")); } // nothing at all for this site
c::set("routes_i18n", $i18n, $fall);
// get internationalized page synonym (key)
$page_default = c::get("ajax") ? false : c::get("start_page"); // ajax: no startpage, but all pages
$page = r::get("page"); // alternative = no-ajax: startpage
if(!$page) $page = $page_default;
$route = self::alternative($i18n, $page, $fall, $page); // look for the given page
if($route) $page = $route; // if it's found, use it internally
c::set("page", $page); // eveything else is done in content
}
function pad($str, $i=20, $pad=" ", $dir=STR_PAD_RIGHT){
return "<b>".str_pad($str."", $i, $pad, $dir)."</b>"; //STR_PAD_LEFT
}
function forms(){
$request = r::get("type", "");
$ourself = c::get("mail.ourself", array("",""));
if( $request == "contact" && r::is_post() ){
if( $data = r::get("contact",false) ){
$msg = "<b>".$ourself[0]." Kontaktaufnahme</b><br>";
$msg .= "<i>Die Nachricht ist erfolgreich abgeschickt worden. Danke!</i>";
$msg .= "<p style='font-family: Courier New;'>";
$msg .= self::pad("Datum:").date("d.m.Y H:i:s")."<br>";
$msg .= self::pad("Name:").$data["name"]."<br>";
$msg .= self::pad("Telefon:").$data["number"]."<br>";
$msg .= self::pad("Email:").$data["email"]."<br>";
$msg .= self::pad("Computer:")."IP ".$_SERVER["REMOTE_ADDR"];//." (".$_SERVER["HTTP_USER_AGENT"].")";
$msg .= "</p>";
$msg .= "<p>Nachricht <i>'".$data["subject"]."'</i>:</p>";
$msg .= "<p><b>".$data["message"]."</b></p>";
$msg .= "<i>Ihr ".$ourself[0]." Team<br>".$ourself[1]."</i>";
$subject = $ourself[0]." Kontaktaufnahme von ".$data["name"];
}
}
elseif( $request == "order" && r::is_post() ){
if( $data = r::get("order",false) ){
$w = 20;
$s = " ";
$msg = "<b>".$ourself[0]." Online Bestellung</b><br>";
$msg .= "<i>Die Bestellung ist erfolgreich abgeschickt worden. Danke!</i>";
$msg .= "<p style='font-family: Courier New;'>";
$msg .= self::pad("Datum:").date("d.m.Y H:i:s")."<br>";
if(isset($data["name"])) $msg .= self::pad("Name:").$data["name"]."<br>";
if(isset($data["customer"])) $msg .= self::pad("Firma:").$data["customer"]."<br>";
if(isset($data["code"])) $msg .= self::pad("Adresse:").$data["code"]." ".$data["town"].", ".$data["street"]."<br>";
if(isset($data["number"])) $msg .= self::pad("Telefon:").$data["number"]."<br>";
if(isset($data["email"])) $msg .= self::pad("Email:").$data["email"]."<br>";
$msg .= self::pad("Computer:")."IP ".$_SERVER["REMOTE_ADDR"];//." (".$_SERVER["HTTP_USER_AGENT"].")";
$msg .= "</p>";
$msg .= "<i>Positionen der Bestellung:</i>";
$msg .= "<p style='font-family: Courier New;'>";
foreach($data["items"] as $i => $item){
$msg .= "<i>".str_pad($i+1,2,"0",STR_PAD_LEFT).".</i> ".self::pad($item[0],35).$item[1]." ".$item[2];
if($item[3]) $msg .= " um ".$item[3];
$msg .= "<br>";
}
$msg .= "</p>";
$msg .= "<i>Ihr ".$ourself[0]." Team<br>".$ourself[1]."</i>";
$subject = $ourself[0]." Bestellung von ".$data["name"];
}
}
if(isset($msg)){
$msg = str_replace(" ", " ", $msg);
$sent = self::mail($subject, $msg, $data["email"], $data["name"]);
if( r::is_ajax() ){
content::type("json");
content::start();
$info = array(
"type" => ($sent ? "success" : "error"),
"msg" => $msg,
"name" => $data["name"]
);
echo a::json($info);
content::end(false);
die();
}
else{
//c::set("has_info", $length." ".($length>1?"Einträge":"Eintrag")." neu");
//$track = track("content", $length.": ".$titles);
}
}
}
function mail($subject, $msg, $to, $to_name){
try {
require_once('libs/phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->AddAddress($to, $to_name);
if($addy = c::get("mail.to", false)) $mail->AddAddress($addy[0], $addy[1]);
if($addy = c::get("mail.to2", false)) $mail->AddAddress($addy[0], $addy[1]);
if($addy = c::get("mail.from", false)) $mail->SetFrom($addy[0], $addy[1]);
else $mail->SetFrom($to, $to_name);
$mail->AddReplyTo($to, $to_name);
$mail->Subject = $subject;
$mail->AltBody = $msg;
$mail->CharSet = "utf-8";
$mail->MsgHTML( $msg );
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = c::get("mail.debug", 1); // enables SMTP debug information (1 = errors and messages, 2 = errors only)
$mail->SMTPAuth = c::get("mail.auth"); // enable SMTP authentication
$mail->SMTPSecure = c::get("mail.secure");
$mail->Host = c::get("mail.host"); // SMTP server
$mail->Username = c::get("mail.user"); // SMTP account username
$mail->Password = c::get("mail.pwd"); // SMTP account password
self::log("Mail send");
$sent = $mail->Send();
self::log("Mail ".($sent?"":"not ")."sent");
return $sent;
} catch (Exception $e) {
self::log("Fehler"); //$e->getMessage());
echo a::json($json_encode( array("status" => "error", "msg" => "'".($e->getMessage())."'" ) ) );
content::end(false);
die();
};
}
/*****************************************************************************
* Administration
*/
function session(){
$request = r::get("type", "");
if( $request == "logout"){
s::remove("admin");
}
elseif( $request == "login" && r::is_post() ){
$name = r::get("user","");
$pass = r::get("pass","");
if( strlen($name) && strlen($pass) ){
$admin = db::row("users", array("name","user","lastip","lastlogin"), array("user"=>$name, "password"=>md5($pass)) );
if($admin){ s::set("admin", $admin); }
else{ c::set("has_error", "Benutzer und Passwort passen nicht zueinander."); }
}
else{ c::set("has_error", "Bitte gib einen Benutzernamen und ein Passwort ein."); }
}
c::set("in_admin", r::get("admin") || s::get("admin") ? true : false);
c::set("is_admin", s::get("admin") ? true : false);
}
/**
* Wirby CMS at all
*/
function admin(){
$request = r::get("type", "");
$lang = l::current(); if(!$lang) $lang = c::get("language");
if( $request == "update" && r::is_post() ){
if( $contents = r::get("contents",false) ){
$count = count($contents);
$updated = 0;
$inserted = 0;
$changed = array();
foreach($contents as $title => $content){
$existing = db::row( "contents_".c::get("site"), array("id"), array("title" => $title, "lang" => $lang) );
if($existing){
$update = db::update( "contents_".c::get("site"), array("content" => $content), array("id" => $existing["id"], "lang" => $lang) );
$updated ++;
}else{
$insert = db::insert( "contents_".c::get("site"), array("content" => $content, "title" => $title, "lang" => $lang) );
$inserted ++;
}
$changed[] = $title;
}
if( r::is_ajax() ){
content::type("json");
content::start();
$info = array(
"type" => "success",
"updated" => $updated,
"inserted" => $inserted,
"changed" => join(", ", $changed)
);
echo a::json($info);
content::end(false);
die();
}
else{
c::set("has_info", $length." ".($length>1?"Einträge":"Eintrag")." neu");
//$track = track("content", $length.": ".$titles);
}
}
}
elseif( $request == "upload" ){
content::type("text/plain");
content::start();
$target = c::get("site")."/files/";
// https://raw.github.com/valums/file-uploader/master/server/php.php
$allowedExtensions = array("jpg", "jpeg", "png", "gif");
$sizeLimit = 10 * 1024 * 1024; // max file size in bytes
$inputName = 'qqfile'; //the input name set in the javascript
// in lib_uploader (=fileuploader/server/php.php)
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit, $inputName);
// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload( $target );
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
content::end(false);
die();
}
}
/*****************************************************************************
* Content
*/
function render(){
global $root;
// c::set("cache_path", $root."/".c::get("cache_path")."/" ); // cache directory (default in wirby folder)
/**
* Array
*/
$contents_raw = db::select( "contents_".c::get("site"), array("title", "content", "lang") );
$contents = array();
foreach ($contents_raw as $content) { // map the result
$lang = $content["lang"]; if(!$lang) $lang = c::get("language"); // default language
$contents[$content["title"]][$lang] = $content["content"];
};
c::set("content", $contents); // push it to the c class
/**
* Render
*/
content::type("html");
content::start();
if(r::is_ajax() && r::get("type") == "content"){ // get whole page, not an admin call
wirby::load(c::get("tmpl_ajax"), false);
}
else {
wirby::load(c::get("tmpl_main"), false); // false: do not return, but echo
if(! c::get("function_head")) die("Wirby: you have to include Wirby's head in your templates, use this: {function='_head()'}");
if(! c::get("function_body")) die("Wirby: you have to include Wirby's body in your templates, use this: {function='_body()'}");
// _head and _body are executed inside the template inside this draw function above (everything is prozedural!)
};
return content::end(false); // true: return echoed
}
/**
* Helpers
*/
// wirby header template with meta, css, js
static function head(){
c::set("function_head", true);
self::load(c::get("tmpl_head"), c::get("wirby_path"));
}
// wirby body template after header with admin bar, js
static function body(){
c::set("function_body", true);
self::load(c::get("tmpl_body"), c::get("wirby_path"));
}
// wirby config getter
static function c($config, $child=false){
$val = c::get($config,false);
if(! $val) $val = s::get($config,false); // look for it in our session store
if($child) $val = $val[$child]; // http://lucdebrouwer.nl/stop-waiting-start-array-dereferencing-in-php-now/
return $val;
}
// return site/project name
static function site(){ return c::get("site"); }
static function page(){ return c::get("page"); }
// check url against a certain/current page
static function is($page, $class="active"){
return $page==c::get("page") ? $class : "";
}
// check if an admin successfully signed in
static function is_a(){ return c::get("is_admin"); }
// check if we are in the admin interface (not signed in for sure)
static function in_a(){ return c::get("in_admin"); }
// complete an url with language key (if it's not the default lang)
static function to($page){
$to = $page == "" ? "" : array_search($page, c::get("routes_i18n"));
$to = $to ? $to : $page; // maybe this page doesn't exist
$lang = l::current(); // also here it's necessary to avoid 2 urls for 1 content
return $lang == c::get("language") ? "/".$to : "/".$lang."/".$to;
}
// change language (find current page in the other lang)
static function to_lang($lang){
$lang = l::sanitize($lang); // check if it is "able"
$routes = c::get("routes"); // get the certain array
$routes = $routes[c::get("site").".".$lang];
if($routes) $to = array_search(c::get("page"), $routes); // try to get the local one
if(! $to) $to = array_search(c::get("page"), c::get("routes_i18n")); // fallback
return $lang == c::get("language") ? "/".$to : "/".$lang."/".$to; // avoid 2 urls for 1 content
}
// load certain template
static function load($name, $path=false){
$file = self::find($name, $path);
if($file) content::load( $file, false );
else echo "Error 404 '".$path.$name."' nicht gefunden";
}
// find template file
static function find($name, $path=false){
if(!$path) $path = c::get("tmpls_path");
$file = $path.$name; // probably it's a right filepath
if(! f::size($file) ) $file = $path.$name.".html";
if(! f::size($file) ) $file = $path.$name.".php";
if(! f::size($file) ) $file = $path."_".$name.".html";
if(! f::size($file) ) $file = $path."_".$name.".php";
return f::size($file) ? $file : false;
}
// complete path of an developed asset
static function asset($asset){
return self::path("assets/$asset");
}
// complete path of an uploaded file
static function file($file){
return self::path("files/$file");
}
// whole absolute path
static function path($ressource){
return "/".c::get("site")."/$ressource";
}
// whole url, e.g. url(asset("style.css"))
static function url($ressource){
if($ressource[0] != "/") $ressource = "/$ressource"; // check if there is a delimiter
return c::get("base_url") . $ressource; // just attach the path
}
// get the content of a db entry
static function get($content, $alt=false, $pre=false){
$contents = c::get("content");
$matching = $contents["$content"][l::current()]; // prefered lang
if(!$matching) $matching = $contents["$content"][c::get("language")]; // default lang
return $matching ? ($pre ? $pre : "").$matching : ($alt ? $alt : $content);
}
// elements with end tags
static function tag($tag, $content, $class, $attrs="", $inner=""){
if( self::is_a() AND in_array($tag, array("span", "button", "input", "label")) ) $tag = "p"; // CKeditor won't work with button/span
$closed = in_array($tag, array("input")) ? true : false;
$id = "id='$content'";
$class = $class ? "class='$class'" : "";
$attrs = $attrs . (($inner == "" AND self::is_a()) ? " data-wirby='$content'" : "");
$attrs = $attrs . ($tag == "input" ? " placeholder='" . self::get($content) . "'" : "");
return ( $closed ? "<$tag $id $class $attrs />" : "<$tag $id $class $attrs>$inner" . self::get($content) . "</$tag>" );
}
// image tag with fallback and dimensions, wrapper
static function img_tag($content, $w, $h, $class, $attrs=""){
$id = "id='$content-img'"; $id_box = "id='$content'";
$class = $class ? "class='$class'" : ""; $class_box = "class='$content img'";
$attrs = $attrs . (self::is_a() ? " data-wirby='$content'" : "");
$attrs = $attrs . ($w ? " width='$w'" : "") . ($h ? " height='$h'" : "");
$size = "style='".($w ? " width:".$w."px;":"").($h?" height:".$h."px;":"")."'";
$src = self::get($content, "http://placehold.it/".($w?"$w":"200").($h?"x$h":"")."&text=$content");
return "<div $id_box $class_box $size><img $id $class $attrs src='$src' /></div>";
}
static function h1($content, $class=null, $attrs=null){ return self::tag("h1", $content, $class, $attrs); }
static function h2($content, $class=null, $attrs=null){ return self::tag("h2", $content, $class, $attrs); }
static function h3($content, $class=null, $attrs=null){ return self::tag("h3", $content, $class, $attrs); }
static function h4($content, $class=null, $attrs=null){ return self::tag("h4", $content, $class, $attrs); }
static function h5($content, $class=null, $attrs=null){ return self::tag("h5", $content, $class, $attrs); }
static function h6($content, $class=null, $attrs=null){ return self::tag("h6", $content, $class, $attrs); }
static function p ($content, $class=null, $attrs=null){ return self::tag("p", $content, $class, $attrs); }
static function div($content, $class=null, $attrs=null){ return self::tag("div", $content, $class, $attrs); }
static function span($content, $class=null, $attrs=null){ return self::tag("span", $content, $class, $attrs); }
static function button ($content, $class=null, $attrs=null){ return self::tag("button", $content, $class, $attrs); }
static function a ($content, $url="#", $class=null, $attrs=""){ return self::tag("a", $content, $class, $attrs." href='$url'"); }
static function label ($for, $class=null, $attrs="", $inner=""){ return self::tag("label", $for."-label", $class, $attrs." for='$for'", $inner); }
static function input ($type, $content=null, $class=null, $attrs=""){ return self::tag("input", $content, $class, $attrs." type='$type'"); }
static function img ($content, $alt="", $w=null, $h=null, $class=null, $attrs=""){ return self::img_tag($content, $w, $h, $class, $attrs." alt='$alt'"); }
}
class w extends wirby {
// shorthand
}
?>
<file_sep><?= w::h1("fruits-h1") ?>
<?= w::p("fruits-p") ?>
<ul class="thumbnails">
<li class="span3">
<div class="thumbnail">
<?= w::img("fruits-1-img", "Kleiner Obst Korb") ?>
<?= w::h4("fruits-1-name") ?>
<?= w::p("fruits-1-details") ?>
</div>
</li>
<li class="span3">
<div class="thumbnail">
<?= w::img("fruits-2-img", "Mittlerer Obst Korb") ?>
<?= w::h4("fruits-2-name") ?>
<?= w::p("fruits-2-details") ?>
</div>
</li>
<li class="span3">
<div class="thumbnail">
<?= w::img("fruits-3-img", "Großer Obst Korb") ?>
<?= w::h4("fruits-3-name") ?>
<?= w::p("fruits-3-details") ?>
</div>
</li>
</ul>
<?= w::div("fruits-details") ?>
<file_sep><?php
c::set("mail.ourself", array("M&M", "+43 660 6522007") );
c::set("mail.to", array("<EMAIL>", "Bestellsystem") );
c::set("mail.to2", array("<EMAIL>", "Bestelldrucker") );
c::set("mail.from", array("<EMAIL>", "<NAME>") );
c::set("mail.host", "wp266.webpack.hosteurope.de");
c::set("mail.user", "wp10625343-bestellung");
c::set("mail.pwd", "<PASSWORD>");
?>
<file_sep><meta name="description" content="Celik ist" />
<meta name="DC.description" lang="de" content="Celik ist" />
<meta name="DC.description" lang="en" content="Celik is" />
<meta name="keywords" content="Gemüse,Obst,Wien,Großmarkt,Celik,MM" />
<meta name="DC.keywords" lang="de" content="Gemüse,Obst,Wien,Großmarkt,Celik,MM" />
<meta name="DC.keywords" lang="en" content="Fruits" />
<meta name="author" content="web architects - <NAME>" />
<meta name="DC.title" lang="de" content="M&M Obst und Gemüse Großhandel" />
<meta name="DC.title" lang="en" content="M&M Obst und Gemüse Großhandel" />
<!--link rel="stylesheet" href="{$site}/assets/style.css" type="text/css" media="screen" /-->
<link rel="shortcut icon" href="/favicon.ico">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="<?= wirby::asset('style.css'); ?>" />
<script type="text/javascript" src="<?= wirby::asset('script.js'); ?>"></script>
<file_sep>Backbone.Collection = Backbone.Collection.extend({
initialize: function() {
// Setzt die Abfrageverzögerung
this.autoRefreshInterval = 1 * 1000;
this.changeRefresh();
},
changeRefresh: function() {
if (this.autoRefresh) {
var that = this;
setTimeout(function() {
$.ajax({
url: that.url + "/_changes",
timeout: 2 * 60 * 1000,
global: false,
// ### Erfolgreich Daten empfangen
success: function(data) {
// Bestehende Models werden aktualisiert
if (that.get(data.id)) that.get(data.id).clear({silent:true}).set(data);
// ´changeRefresh´ geht in die nächste Runde
that.autoRefreshInterval = 1 * 1000;
that.changeRefresh();
},
error: function(er, e, es) {
// Bei Serverfehlern wird die Abfrageverzögerung erhöht.
if (!e || e != "timeout") that.autoRefreshInterval *= 2;
// ´changeRefresh´ geht in die nächste Runde
that.changeRefresh();
}
});
},
that.autoRefreshInterval);
}
}
});
<file_sep><?php
if(!isset($root)) die("Wirby: Please add '$root = dirname(__FILE__);' before you require Wirby's load.php");
if(floatval(phpversion()) < 5.2) die("Wirby: Please upgrade to PHP 5.2+ which is necessary for its dependencies");
$libs = $root."/wirby/libs";
require_once( $libs."/kirby-toolkit/kirby.php" );
/**
* Configs
*/
require_once( $root."/wirby/config.php" );
require_once( $root."/routes.php" );
/**
* Dependencies
*/
require_once( $libs."/".c::get("lib_mail") );
require_once( $libs."/".c::get("lib_uploader") );
/**
* Base logic
*/
require_once( $root."/wirby/wirby.php" );
?>
<file_sep><div class="tab-pane" id="start"><? wirby::load("start"); ?></div>
<div class="tab-pane" id="offer"><? wirby::load("offer"); ?></div>
<div class="tab-pane" id="order"><? wirby::load("order"); ?></div>
<div class="tab-pane" id="about"><? wirby::load("about"); ?></div>
<div class="tab-pane" id="where"><? wirby::load("where"); ?></div>
<file_sep>
<div class="container">
<div class="row">
<div class="span9">
<?= w::h2("contact-h2-form") ?>
<form id="contact" method="post">
<div class="controls controls-row">
<input id="contact-name" name="name" type="text" class="span3" placeholder="Name">
<input id="contact-email" name="email" type="email" class="span3" placeholder="Email Adresse">
<input id="contact-number" name="number" type="text" class="span3" placeholder="Telefonnummer">
</div>
<div class="controls controls-row">
<textarea id="contact-message" name="message" class="span6 pull-left" placeholder="Ihre Nachricht an das Mesh Team" rows="5"></textarea>
<input id="contact-subject" name="subject" type="text" class="span3" placeholder="Betreff der Nachricht">
<br><br><br>
<button id="contact-btn" type="submit" class="span3 btn btn-danger input-medium">Absenden</button>
</div>
</form>
</div>
<div class="span3">
<?= w::h2("contact-h2-info") ?>
<?= w::p("contact-info") ?>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="span12">
<div id="map"></div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="span4"><?= w::h2("contact-infos-1h") ?><?= w::div("contact-infos-1") ?></div>
<div class="span4"><?= w::h2("contact-infos-2h") ?><?= w::div("contact-infos-2") ?></div>
<div class="span4"><?= w::h2("contact-infos-3h") ?><?= w::div("contact-infos-3") ?></div>
</div>
</div>
<file_sep><?= w::h1("order-h1"); ?>
<?= w::p("order-p"); ?> <!--Wir freuen uns Sie als Kunde begrüßen zu dürfen. Stellen Sie direkt eine Anfrage an uns: Obst und Gemüse suchen, Menge eintragen, Kontaktdaten ausfüllen und abschicken. Im Anschluss wird alles automatisch in unserem Büro ausgedruckt und wir können Ihnen so bald als möglich eine Rückmeldung geben.-->
<div class="row-fluid" id="step1">
<div class="span12">
<?= w::h2("order-h2"); ?>
<? if(w::is_a()){ ?>
<script type="text/javascript">
window.no_dataTable = true;
</script>
<? } ?>
<div class="dataTable">
<?= w::div("order-articles"); ?>
</div>
</div>
<div class="clearfix center">
<?= w::button("step1-btn", "btn btn-large btn-danger", "", "id='step1-btn'") ?>
</div>
</div>
<? w::load("order2") ?>
<file_sep><?= w::h1("offer-h1") ?>
<?= w::p("offer-p") ?>
<div class="offer">
<?= w::img("offer-1-img", "Celik News", 100, 100) ?>
<?= w::h2("offer-1-h2") ?>
<?= w::p("offer-1") ?>
</div>
<div class="offer">
<?= w::img("offer-2-img", "Celik News", 100, 100) ?>
<?= w::h2("offer-2-h2") ?>
<?= w::p("offer-2") ?>
</div>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>M&M Celik - Obst und Gemüse - Großhandel in Wien</title>
<?= wirby::head(); ?>
<?= wirby::load('head'); ?>
</head>
<body class="<?= browser::css() ?> <?= "bg0".rand(1, 9) ?>" data-lang="<?= l::current() ?>">
<? if(w::is_a()){ ?><form id="wirby-form" method="post" accept-charset="utf-8" enctype="multipart/form-data"><? } ?>
<? wirby::body(); ?>
<noscript><div class="alert alert-error">Sie haben in ihrem Browser leider kein Javascript aktiviert. Es kann zu Anzeigeproblemen kommen!</div></noscript>
<img class="telefon" src="<?= wirby::asset('telefon.png'); ?>" alt="M&M Celik ist erreichbar unter +4316151800" />
<div id="header-border" class="scroll-elm">
<div id="header">
<div class="container">
<div id="logo"><?= w::img("start-logo", "Familienbetrieb Celik", 100) ?></div>
<div id="leap" class="leap">
<div>
<?= w::p("leap-text"); ?>
<?= w::p("leap-hidden", "hidden-phone") ?>
</div>
<?= w::a("leap-sub", w::to("about")) ?>
</div>
<ul id="tab-menu" class="horizontal scroll-to">
<li class='<?= w::is("start") ?> left'><?= w::a("tab-start", w::to("")) ?></li>
<li class='<?= w::is("news") ?>'><?= w::a("tab-news", w::to("news")) ?></li>
<li class='<?= w::is("order") ?>'><?= w::a("tab-order", w::to("order")) ?></li>
<li class='<?= w::is("fruits") ?>'><?= w::a("tab-fruits", w::to("fruits")) ?></li>
<li class='<?= w::is("about") ?>'><?= w::a("tab-about", w::to("about")) ?></li>
<li class='<?= w::is("contact")?>'><?= w::a("tab-contact", w::to("contact")) ?></li>
</ul>
</div>
</div>
</div>
<div class="container" id="container">
<div class="row-fluid" id="header-dummy">
<!--<img id="logo" src="gemuese/assets/logo.png" />-->
</div>
<div class="row-fluid scroll-from">
<div id="content-border" class="span12">
<div id="content" class="<?= w::page() ?>">
<? if(w::page()): ?>
<?= w::load(w::page()) ?>
<? else: ?>
<div class="tab-content">
<div class="tab-pane" id="start"><?= w::load(w::c("start")) ?></div>
</div>
<? endif; ?>
</div>
<div id="actions">
<div class="pull-left">
<!--a href="http://www.facebook.com/pages/MM-Celik-Obst-und-Gem%C3%BCse/453488338033651"><i class="icon-share-alt icon-white"></i></a-->
<iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FMM-Celik-Obst-und-Gem%25C3%25BCse%2F453488338033651&send=false&layout=box_count&show_faces=false&font=verdana&colorscheme=light&action=like&appId=517712251593236&width=90&height=75" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:75px;" allowTransparency="true"></iframe>
<?= w::p("footer-span1") ?>
</div>
<div class="span3">
<?= w::p("footer-span2") ?>
</div>
<div class="span3">
<?= w::p("footer-span3") ?>
<?= w::img("footer-img", "<NAME>", 100) ?>
</div>
<div class="span3">
<?= w::p("footer-span4") ?>
</div>
<div class="pull-right languages">
<?= w::a("Deutsch", w::to_lang("de")) ?>
<?= w::a("English", w::to_lang("en")) ?>
<?= w::a("Español", w::to_lang("es")) ?>
<img class="telefon" src="<?= wirby::asset('telefon.png'); ?>" alt="Telefonnummer von M&M Celik +4316151800" />
</div>
</div>
</div>
</div>
</div>
<?// if(w::page()=="imprint" OR w::page()=="order"): ?>
<?= w::load("terms") ?>
<?// endif; ?>
<div id="raster"></div>
<div id="author"><a href="http://www.webarchitects.at" target="_blank" data-toggle="tooltip" title="made with 'Wirby' and ♥ by <NAME>" data-placement="left" title="Feedback?">made by Flo</a></div>
<? if(w::is_a()){ ?><input name="type" type="hidden" value="update"></form><? } ?>
</body>
</html>
<file_sep><?php
/**
* Database
*/
c::set("db.host", "webarchitects.at");
c::set("db.name", "app_wirby");
c::set("db.user", "wirby");
c::set("db.password", "<PASSWORD>");
c::set("db.charset", "utf8");
c::set("languages", array("de", "en", "es", "fr", "it") );
c::set("language", "de"); // default used in toolkit:2148
/**
* System
*/
c::set("ajax", false); // async if page variable is false
c::set("debug", false); // only print debug
c::set("cache", true);
c::set("cache_path", "wirby/cache");
c::set("tmpls_path", "pages"); // in project folder
c::set("tmpl_main", "layout");
c::set("tmpl_ajax", "ajax"); // without a layout
c::set("tmpl_head", "head");
c::set("tmpl_body", "body");
c::set("start_page", "start"); // start page, set if ajax is false
/**
* Dependencies
* in "wirby/libs"
*/
c::set("lib_toolkit", "kirby-toolkit/kirby.php");
c::set("lib_tmpl", "raintpl/inc/rain.tpl.class.php");
c::set("lib_mail", "phpmailer/class.phpmailer.php");
c::set("lib_db", "meekrodb/db.class.php");
c::set("lib_uploader", "fileuploader/server/php/php.php");
c::set("js_lib_headjs", "headjs/dist/head.load.min.js");
c::set("js_lib_editor", "ckeditor3/ckeditor.js");
c::set("js_lib_tmpl", "icanhaz/ICanHaz.min.js");
/**
* Assets
*/
c::set("assets_loader", "/wirby/libs/".c::get("js_lib_headjs")); // library async loader
c::set("assets_callback", "site_ready"); // afterwards execute this js-callback-function
c::set("assets_mapscallback", "maps_ready"); // after loading maps execute this one
c::set("assets_js", array( // js libraries used always
"http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js",
"http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=".c::get("assets_mapscallback"),
"http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js",
"/wirby/libs/jquery-address/jquery.address-1.6.min.js",
"/wirby/libs/".c::get("js_lib_tmpl"),
"/wirby/libs/bootstrap/js/bootstrap.min.js",
"/wirby/assets/datatable.bootstrap.js",
"/wirby/assets/datatable.tabletools.min.js"
));
c::set("assets_admin", array( // js libraries used when logged in
//"/wirby/libs/ckeditor/ckeditor.js",
"/wirby/libs/fileuploader/client/js/jquery-plugin.js",
//"/wirby/libs/jquery.jeditable.js",
//"/wirby/libs/".c::get("js_lib_editor"),
//"/wirby/libs/ckeditor3/adapters/jquery.js",
"/wirby/assets/script.js"
));
/**
* Stuff
*/
c::set("microsoft_verification", false);
c::set("google_analytics", false); // "UA-7082989-19");
c::set("google_plus", false);
c::set("adminbar_position", "bottom");
?>
<file_sep><meta name="description" content="Pizza Pasta Liefer Service in Wien" />
<meta name="DC.description" lang="de" content="Pizza Pasta Liefer Service in Wien" />
<meta name="DC.description" lang="en" content="Pizza Pasta Liefer Service in Wien" />
<meta name="keywords" content="Pizza,Pasta,Wien" />
<meta name="DC.keywords" lang="de" content="Pizza,Pasta,Wien" />
<meta name="DC.keywords" lang="en" content="Pizza,Pasta,Vienna" />
<meta name="author" content="web architects - <NAME>" />
<meta name="DC.title" lang="de" content="Pastolore" />
<meta name="DC.title" lang="en" content="Pastolore" />
<!--link rel="stylesheet" href="{$site}/assets/style.css" type="text/css" media="screen" /-->
<link rel="shortcut icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" href="<?= wirby::asset('css/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?= wirby::asset('css/style.css'); ?>" type="text/css">
<link rel="stylesheet" href="<?= wirby::asset('css/lightbox.css'); ?>">
<script src="<?= wirby::asset('js/modernizr-2.6.2.min.js'); ?>"></script>
<link type="text/css" rel="stylesheet" href="<?= wirby::asset('style.css'); ?>" />
<script type="text/javascript" src="<?= wirby::asset('script.js'); ?>"></script>
| 053954cb4a9840ed3e8ddf3f23b2d664e6652ef5 | [
"JavaScript",
"PHP"
] | 30 | PHP | trigger121/wirby-cms | 788ebb629476c592d2d473cd57a24d22eb82551f | 28a77961b9b983dd078ec43aa49b7b32e0cf61fb |
refs/heads/master | <file_sep># jwt-test
<file_sep><?php
// показывать сообщения об ошибках
// Установить в 0 на продакшене
ini_set('display_errors', 1);
error_reporting(E_ALL);
// установить часовой пояс по умолчанию
date_default_timezone_set('Europe/Moscow');
// переменные, используемые для JWT
$key = '';
$iss = '';
$aud = '';
$iat = 1356999524;
$nbf = 1357000000;
<file_sep>CREATE TABLE `users`
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(256) NOT NULL,
`lastname` VARCHAR(256) NOT NULL,
`email` VARCHAR(256) NOT NULL,
`password` VARCHAR(2048) NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE = InnoDB; | a3fd313931118b2bebfe8079f2daa28c8bc8eb2a | [
"Markdown",
"SQL",
"PHP"
] | 3 | Markdown | ASKazin/jwt-test | 7fd06125c90d1987b81fcc180d7ac7109dc63cde | 1a71e9e0db2702593af30e8d8dcfeb9ff67dfabd |
refs/heads/master | <repo_name>jacderida/doom-stuff<file_sep>/generate_game_data.sh
#!/usr/bin/env bash
declare -a maps=( \
"Exodus" \
"Cashews" \
"Island of Mystery" \
"Pure Hate" \
"Fortress of Damnation" \
"Trifling" \
"Simply Dead" \
"Tingsryd" \
"Core Annihilation" \
"Total Recall" \
"Warborn" \
"Damnation" \
"Unleash the Fire" \
"Damned Legion" \
"Doomherolandia" \
"Twobox" \
"Electric Wizard" \
"Last Cup of Sorrow" \
"Split Wide Open" \
"True Grit" \
"Walk With Me in Hell" \
"Royale Arena" \
"Castle Lava" \
"Bane's Atrium" \
"Fourtress" \
"Crimson" \
"Decimal Error" \
"Slaughterstein" \
"Degrassi" \
"Anathema" \
"sworf" \
"Brookhaven Hospital" \
"BoomTown" \
"Hard Contact" \
"KSP" \
)
rm csv
map_num=1
for map in "${maps[@]}"
do
printf "Slaugherfest 2012,DOOM2.WAD,SF2012_final.wad,2,2013-07-30,Episode 1,1,%s,%d,%d,false\n" \
"$map" $map_num $map_num >> csv
((map_num++))
done
<file_sep>/README.md
# Doom Stuff
Little repository for my setup for playing Doom. It contains some utility scripts and also serves as a place I can document things I want to remember.
## Scripts
There are scripts here that will setup a Windows machine for playing Doom and will generate 'launchers' for starting each level in a game with a pistol.
### Prerequisites
For running these scripts:
* Install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10)
* Install [Powershell Core](https://github.com/PowerShell/PowerShell/releases)
* Install the AWS tools for Powershell: `Install-Module -Name AWSPowerShell.NetCore`
* Use the module: `Import-Module -Name AWSPowerShell.NetCore`
* Setup AWS credentials for S3: `Set-AWSCredential -AccessKey <key> -SecretKey <key> -StoreAs s3`
* In WSL use your shell to set a `WINDOWS_DOOM_HOME` environment variable to a Windows style path of where you want the Doom home directory to be, e.g. `C:\\Users\\Chris\\doom`.
* In WSL use your shell to set a `UNIX_DOOM_HOME` environment variable to a Windows style path of where you want the Doom home directory to be, e.g. `/c/Users/Chris/doom`.
### Run Scripts
After this is done, you can run `doom\bootstrap.ps1`. This script will:
* Create a `doom` directory in `%USERPROFILE%` with self explanatory sub-directories
* Install various source ports
* Download source port configuration files from this repo
* Download `DOOM.WAD` and `DOOM2.WAD` iwad files
* Download various pwad files
* Download various modifications
Once that's been done, there's a little Python script that can generate the launchers. Launchers are just a set of batch files for each game, one for each mission (note: a 'game' here really refers to a WAD, e.g. SIGIL.WAD, not Doom or Doom 2 (though both of those happen to be a game too)). These batch files allow you to quickly start any level in the game with a pistol.
To run the script you need to use WSL, which should have an Ubuntu environment that comes with a Python installation. Run the `generate-launchers.py` script and follow the prompts.
## Recording Demos for YouTube
### Setup
There are some steps required for software to install and configure:
* Install [OBS Studio](https://obsproject.com/)
* Install [HitFilm Express](https://fxhome.com/hitfilm-express)
* Configure OBS to record videos at 1080p:
- Click on Settings -> Video
- Set `Base (Canvas) Resolution` to `3840x2160`
- Set `Output (Scaled) Resolution` to `1920x1080`
- Set `Downscale Filter` to `Bicubic`
- Set `Common FPS Values` to `60`
* Configure OBS to record mp4 by going to Settings -> Video and setting `Recording Format` to `mp4`
* Add a recording source:
- Run GZDoom in window mode and leave it running
- Click on the `+` button in the `Sources` section in the GUI and select `Game Capture`
- Set `Mode` to `Capture specific window`
- Set `Window` to entry beginning `[gzdoom.exe]`
- Set `Window Match Priority` to `Match title, otherwise find window of same executable`
- Make sure `Limit capture framerate` and `Capture Cursor` are unticked
### Recording the Demo
You can't immediately launch into the demo using a batch file because there's an issue with OBS recording a blank screen for the first 10 seconds or so. I searched on Google for many hours trying to find a resolution to this, but nothing worked.
With this in mind, here are the instructions for recording the demo 'manually':
* Copy the demo file to the source port directory and rename it to remove the timestamp from the file (the timestamp is generated by a script that records the demo)
* Set the volume on the audio source to 100%
* Launch OBS
* Click on the `Start Recording` button in OBS
* Use the `start.bat` file which will launch the game without the `-playdemo` option or warping to a particular map
* Leave the game running for 10 or 15 seconds to allow OBS to 'catch up' (this is where the blank screen occurs in the resulting video)
* Use the console to start the demo with `playdemo <name>.lmp`
* Wait until the demo completes
* Exit GZDoom and click on `Stop Recording` in OBS
### Edit the Demo Video
Use HitFilm to trim the beginning and end from the video. As a one time step, you need to edit the YouTube exporting preset to use 60FPS. See [this](https://www.youtube.com/watch?v=ybKZVT5Fm18) video for a guide.
Just create a new project, import the video OBS created and then [trim](https://fxhome.com/reference-manuals/hitfilm-express) it by using `Set In and Out Points`. Once the in and out points have been set, click and drag the video from the asset list on the left side to the video track. After that, just export the video to get a new MP4.
### Upload to YouTube
Finally, the video can be uploaded to YouTube. This is a really straight forward process that can be done through their GUI. There is a `youtube-video-description.txt` file in this repository that can be used to provide a description that can be copied and pasted.
<file_sep>/generate-launchers.py
#!/usr/bin/env python3
import csv
import glob
import operator
import os
import shutil
import sys
from abc import ABC
from collections import namedtuple
class SourcePort(ABC):
def __init__(
self, name, friendly_name,
config_name, exe_name, install_path,
version, doom_config, misc_config):
self.friendly_name = friendly_name
self.name = name
self.config_name = config_name
self.install_path = install_path
self.exe_name = exe_name
self.exe_path = '{0}\\{1}'.format(install_path, self.exe_name)
self.version = version
self.doom_config = doom_config
self.configurations = ['music', 'nomusic', 'nomonsters']
self.misc_config = misc_config
def get_configurations(self):
return self.configurations
def get_playdemo_batch_commands(self, game, demo_path):
commands = []
[commands.append(x) for x in self.get_pre_launch_config_commands(None)]
commands.append(self._get_playdemo_command(game, demo_path))
return commands
def get_viddump_batch_commands(self, game, demo_path, win_demo_path):
commands = []
[commands.append(x) for x in self.get_pre_launch_config_commands('viddump')]
commands.append(self._get_viddump_command(game, demo_path, win_demo_path))
[commands.append(x) for x in self.get_post_game_config_commands(game, 'viddump')]
return commands
def get_launch_batch_commands(self, game, configuration):
commands = []
[commands.append(x) for x in self.get_pre_launch_config_commands(configuration)]
commands.append(self._get_game_launch_command(game, None, None, configuration))
[commands.append(x) for x in self.get_post_game_config_commands(game, configuration)]
return commands
def get_d2all_record_batch_commands(self, game, configuration):
commands = []
[commands.append(x) for x in self._get_pre_launch_record_commands(game, 'D2All')]
[commands.append(x) for x in self.get_pre_launch_config_commands(configuration)]
mission = Mission('D2All', 1, 'D2All', game.pwad)
commands.append(self._get_game_launch_command(game, None, mission, configuration))
[commands.append(x) for x in self.get_post_game_config_commands(game, configuration, 'D2All')]
return commands
def get_map_launch_batch_commands(self, game, episode, mission, configuration):
commands = []
map_padded = 'MAP{0}'.format(str(mission.level).zfill(2))
if configuration == 'record':
[commands.append(x) for x in self._get_pre_launch_record_commands(game, map_padded)]
[commands.append(x) for x in self.get_pre_launch_config_commands(configuration)]
commands.append(self._get_game_launch_command(game, episode, mission, configuration))
[commands.append(x) for x in self.get_post_game_config_commands(game, configuration, map_padded)]
return commands
def get_mod_options(self, configuration):
return ''
def get_pre_launch_config_commands(self, configuration):
commands = []
commands.append('set start=%cd%')
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.doom_config.config_path,
self.config_name,
self.install_path,
self.config_name))
if configuration == 'viddump':
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.doom_config.utils_path, 'ffmpeg.exe', self.install_path, 'ffmpeg.exe'))
commands.append('cd {0}'.format(self.install_path))
if configuration in ['music', 'nomusic']:
commands.append('start AutoHotkeyU64.exe {0}\\mb3quickload.ahk'.format(self.doom_config.utils_path))
return commands
def get_post_game_config_commands(self, game, configuration, mission=None):
commands = []
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.install_path,
self.config_name,
self.doom_config.config_path,
self.config_name))
commands.append('del {0}'.format(self.config_name))
commands.append('cd %start%')
if configuration in ['music', 'nomusic', 'nomonsters']:
commands.append('taskkill /f /im AutoHotkeyU64.exe')
return commands
def get_game_options(self, game, mission, configuration):
"""
There are a couple of hard coded cases here for rare exceptions. The first is for
Back to Saturn X, which for some reason has an additional WAD file. The second is
for the 'Master Levels' compilation, which distributes each map as a separate WAD file.
"""
options = ''
if self.misc_config.use_config_arg:
options += '-config {0} '.format(self.config_name)
if configuration in ['music', 'nomusic']:
save_path = self._get_save_path(game, mission)
options += '-{0} {1} '.format(self.misc_config.save_arg_name, save_path)
options += '-iwad {0}\\{1} '.format(self.doom_config.iwad_path, game.iwad)
options += '-file '
options += self.get_low_priority_wads(game)
if game.pwad:
options += '{0}\\{1} '.format(self.doom_config.wad_path, game.pwad)
if game.pwad == 'btsx_e1a.wad':
options += self._get_wad_option('btsx_e1b.wad')
elif game.pwad == 'sunlust.wad':
options += self._get_wad_option('D2SPFX19-sunlust.WAD')
if game.name == 'Master Levels for Doom II':
options += self._get_wad_option(mission.wad)
return options
def get_misc_options(self, configuration, game):
options = '-fullscreen '
if configuration == 'nomusic':
options += '-nomusic '
elif configuration == 'nomonsters':
options += '-nomonsters '
return options
def get_skill_option(self):
return '-skill 4 '
def get_warp_option(self, game, episode, mission):
if game.name == 'Master Levels for Doom II':
return '-warp 01 '
elif game.iwad == 'DOOM2.WAD' or game.iwad == 'TNT.WAD' or game.iwad == 'PLUTONIA.WAD':
return '-warp {0} '.format(str(mission.level).zfill(2))
elif game.iwad == 'DOOM.WAD':
return '-warp {0} {1} '.format(episode.number, mission.number)
raise ValueError('iwad {0} not supported yet'.format(game.iwad))
def get_low_priority_wads(self, game):
options = ''
# Some WADs aren't compatible with the sprite fix WAD
if game.pwad not in ['ANTA_REQ.WAD', 'Eviternity.wad', 'sunlust.wad']:
if game.iwad == 'DOOM.WAD':
options += self._get_wad_option('D1SPFX19.WAD')
else:
options += self._get_wad_option('D2SPFX19.WAD')
if game.pwad != 'ANTA_REQ.WAD':
options += self._get_wad_option('DSPLASMA.wad')
return options
def _get_game_launch_command(self, game, episode, mission, configuration):
launch_command = '{0} '.format(self.exe_name)
launch_command += self.get_game_options(game, mission, configuration)
mod_options = self.get_mod_options(configuration)
if mod_options:
launch_command += mod_options
launch_command += self.get_misc_options(configuration, game)
if episode and mission:
launch_command += self._get_map_specific_options(game, episode, mission)
if configuration == 'record':
launch_command += self.get_recording_options(game, episode, mission)
return launch_command.strip()
def _get_playdemo_command(self, game, demo_path):
launch_command = '{0} '.format(self.exe_name)
launch_command += self.get_game_options(game, None, None)
launch_command += self.get_misc_options('none', game)
launch_command += '-playdemo "{0}"'.format(demo_path)
return launch_command.strip()
def _get_viddump_command(self, game, demo_path, win_demo_path):
launch_command = '{0} '.format(self.exe_name)
launch_command += self.get_game_options(game, None, None)
launch_command += self.get_misc_options('viddump', game)
launch_command += '-timedemo "{0}"'.format(win_demo_path)
demo_file_name = "{0}.mp4".format(os.path.basename(demo_path).split('.')[0])
path = '{0}\\{1}'.format(self.doom_config.viddump_path, demo_file_name)
launch_command += ' -viddump "{0}"'.format(path)
return launch_command.strip()
def _get_pre_launch_record_commands(self, game, mission=None):
commands = []
commands.append(
'For /f "tokens=1-4 delims=/ " %%a in (\'date /t\') do (set mydate=%%c-%%b-%%a)')
commands.append(
'For /f "tokens=1-2 delims=/:" %%a in (\'time /t\') do (set mytime=%%a%%b)')
commands.append(
'set datetime=%mydate%-%mytime%')
return commands
def _get_map_specific_options(self, game, episode, mission):
map_options = self.get_skill_option()
map_options += self.get_warp_option(game, episode, mission)
return map_options
def _get_wad_option(self, wad_file):
if self.misc_config.use_single_file_arg:
return '{0}\\{1} '.format(self.doom_config.wad_path, wad_file)
return '-file {0}\\{1} '.format(self.doom_config.wad_path, wad_file)
def _get_save_path(self, game, mission):
if mission:
return '"{0}\\{1}\\{2}\\MAP{3}"'.format(
self.doom_config.saves_path,
game.get_directory_friendly_name(),
self.name,
str(mission.level).zfill(2))
return '"{0}\\{1}\\{2}\\D2All"'.format(
self.doom_config.saves_path,
game.get_directory_friendly_name(),
self.name)
class CrispyDoomSourcePort(SourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'crispy', 'Crispy Doom', 'crispy-doom.cfg',
'crispy-doom.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=True, use_config_arg=False, save_arg_name='savedir'))
def get_pre_launch_config_commands(self, configuration):
commands = []
commands.append('set start=%cd%')
commands.append('cd {0}'.format(self.install_path))
return commands
def get_post_game_config_commands(self, game, configuration, mission=None):
commands = []
commands.append('cd %start%')
return commands
class DoomRetroSourcePort(SourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'retro', 'Doom Retro', 'doomretro.cfg',
'doomretro.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=True, use_config_arg=True))
def get_misc_options(self, configuration, game):
options = '-fullscreen '
options += '-pistolstart '
if configuration == 'nomusic':
options += '-nomusic '
return options
def get_warp_option(self, game, episode, mission):
return '-warp E{0}M{1} '.format(episode.number, mission.number)
class BoomSourcePort(SourcePort):
def get_misc_options(self, configuration, game):
options = '-complevel {0} '.format(game.complevel)
options += '-nowindow -noaccel '
if configuration == 'nomusic':
options += '-nomusic '
return options
class DsdaSourcePort(BoomSourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'dsda', 'dsda', 'dsda-doom.cfg',
'dsda-doom.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=True, use_config_arg=True))
self.configurations = ['music', 'nomusic', 'nomonsters', 'record']
def _get_pre_launch_record_commands(self, game, mission):
commands = []
commands.append('move "{0}\\{1}\\{2}\\*.lmp" "{3}"'.format(
self.doom_config.demos_path,
game.get_directory_friendly_name(),
mission,
self.install_path))
return commands
def get_misc_options(self, configuration, game):
options = ''
if configuration in ['record', 'viddump'] and game.complevel not in [9, 11]:
# When recording, apply complevel for all values except 9 or 11.
# For some reason, those values force the use of `-shorttics` when recording demos.
options = '-complevel {0} '.format(game.complevel)
elif configuration not in ['record', 'viddump']:
options = '-complevel {0} '.format(game.complevel)
options += '-nowindow -noaccel '
if configuration == 'nomusic':
options += '-nomusic '
elif configuration == 'nomonsters':
options += '-nomonsters '
if configuration != 'viddump':
options += '-analysis -track_100k -time_keys -time_secrets '
return options
def get_recording_options(self, game, episode, mission):
if mission.level == 'D2All':
return '-skill 4 -record D2All -longtics'
return '-record MAP{0} -longtics'.format(str(mission.level).zfill(2))
def get_post_game_config_commands(self, game, configuration, mission=None):
commands = []
if configuration == 'viddump':
commands.append('del *.txt')
commands.append('del ffmpeg.exe')
return commands
if configuration == 'record':
demo_path = '{0}\\{1}\\{2}'.format(
self.doom_config.demos_path, game.get_directory_friendly_name(), mission)
commands.append('if not exist "{0}\\" mkdir "{1}"'.format(demo_path, demo_path))
commands.append('move *.lmp "{0}"'.format(demo_path))
commands.append('cd %start%')
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.install_path,
self.config_name,
self.doom_config.config_path,
self.config_name))
commands.append('cd %start')
if configuration in ['music', 'nomusic']:
commands.append('taskkill /f /im AutoHotkeyU64.exe')
return commands
class PrBoomSourcePort(BoomSourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'prboom', 'PRBoom-plus', 'prboom-plus.cfg',
'prboom-plus.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=True, use_config_arg=True))
class GlBoomSourcePort(BoomSourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'glboom', 'GLBoom-plus', 'glboom-plus.cfg',
'glboom-plus.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=True, use_config_arg=True))
self.configurations = ['music', 'nomusic', 'nomonsters', 'record']
def get_recording_options(self, game, episode, mission):
return '-record MAP{0}-%datetime%.lmp '.format(str(mission.level).zfill(2))
def get_post_game_config_commands(self, game, configuration, mission=None):
commands = []
if configuration == 'record':
commands.append('move *.lmp "{0}\\{1}"'.format(
self.doom_config.demos_path, game.get_directory_friendly_name()))
commands.append('cd %start%')
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.install_path,
self.config_name,
self.doom_config.config_path,
self.config_name))
commands.append('del {0}'.format(self.config_name))
commands.append('cd %start')
return commands
class GzDoomSourcePort(SourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'gzdoom', 'GZDoom', 'gzdoom-Chris.ini',
'gzdoom.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=False, use_config_arg=True))
self.configurations = [
'music', 'nomusic', 'smooth', 'beautiful', 'nomonsters', 'record']
def get_mod_options(self, configuration):
options = ''
if configuration == 'smooth':
options += '-file {0}\\{1} '.format(self.doom_config.mod_path, 'SmoothDoom.pk3')
elif configuration == 'beautiful':
options += '-file {0}\\{1} '.format(self.doom_config.mod_path, 'BDoom632.pk3')
options += '-file {0}\\{1} '.format(self.doom_config.mod_path, 'idclever-starter.pk3')
options += '-file {0}\\{1} '.format(self.doom_config.mod_path, 'fullscrn_huds.pk3')
return options
def get_recording_options(self, game, episode, mission):
return '-record MAP{0}-%datetime%.lmp '.format(str(mission.level).zfill(2))
def get_post_game_config_commands(self, game, configuration, mission=None):
commands = []
if configuration == 'record':
commands.append('move *.lmp "{0}\\{1}"'.format(
self.doom_config.demos_path, game.get_directory_friendly_name()))
commands.append('cd %start%')
commands.append('copy {0}\\{1} {2}\\{3} /Y'.format(
self.install_path,
self.config_name,
self.doom_config.config_path,
self.config_name))
commands.append('del {0}'.format(self.config_name))
commands.append('cd %start')
return commands
class ZDoomSourcePort(SourcePort):
def __init__(self, install_path, version, doom_config):
SourcePort.__init__(
self, 'zdoom', 'ZDoom', 'zdoom-Chris.ini',
'zdoom.exe', install_path, version, doom_config,
MiscConfig(use_single_file_arg=False, use_config_arg=True))
class Game(object):
def __init__(self, name, iwad, pwad, complevel, release_date, source_ports, doom_config):
self.name = name
self.iwad = iwad
self.pwad = pwad
self.complevel = complevel
self.release_date = release_date
self.episodes = []
self.source_ports = source_ports
self.doom_config = doom_config
def add_episode(self, episode):
self.episodes.append(episode)
def get_directory_friendly_name(self):
return '{0} -- {1}'.format(self.release_date, self.name.replace(':', ' --'))
def create_demo_directories(self):
game_demo_path = os.path.join(
self.doom_config.unix_demos_path, self.get_directory_friendly_name())
if not os.path.exists(game_demo_path):
os.makedirs(game_demo_path)
external_path = os.path.join(game_demo_path, 'external')
if not os.path.exists(external_path):
os.makedirs(external_path)
highlights_path = os.path.join(game_demo_path, 'highlights')
if not os.path.exists(highlights_path):
os.makedirs(highlights_path)
d2all_path = os.path.join(game_demo_path, 'D2All')
if not os.path.exists(d2all_path):
os.makedirs(d2all_path)
def create_save_directories(self):
saves_path = os.path.join(
self.doom_config.unix_saves_path, self.get_directory_friendly_name())
missions = []
[missions.append(m) for e in self.episodes for m in e.missions]
for sp in self.source_ports:
for mission in missions:
path = os.path.join(saves_path, sp.name, 'MAP{}'.format(str(mission.level).zfill(2)))
if not os.path.exists(path):
os.makedirs(path)
d2all_path = os.path.join(saves_path, sp.name, 'D2All')
if not os.path.exists(d2all_path):
os.makedirs(d2all_path)
def generate_demo_launchers(self):
full_demo_paths = self._get_full_demo_paths()
demo_launchers_path = self._get_demo_launchers_path_for_game()
win_demos_path = self._get_win_demos_path_for_game()
dsda_source_port = next(x for x in self.source_ports if x.name == 'dsda')
for demo_path in full_demo_paths:
win_demo_path = self._get_win_demo_path(demo_path, win_demos_path)
commands = dsda_source_port.get_playdemo_batch_commands(self, win_demo_path)
path = self._get_demo_launcher_path(demo_launchers_path, demo_path)
with open(path, 'w') as f:
print('Writing {0}'.format(path))
for command in commands:
f.write(command + os.linesep)
def generate_viddump_launchers(self):
full_demo_paths = self._get_full_demo_paths()
viddump_launchers_path = self._get_viddump_launchers_path_for_game()
win_demos_path = self._get_win_demos_path_for_game()
dsda_source_port = next(x for x in self.source_ports if x.name == 'dsda')
for demo_path in full_demo_paths:
win_demo_path = self._get_win_demo_path(demo_path, win_demos_path)
commands = dsda_source_port.get_viddump_batch_commands(
self, demo_path, win_demo_path)
path = self._get_demo_launcher_path(viddump_launchers_path, demo_path)
with open(path, 'w') as f:
print('Writing {0}'.format(path))
for command in commands:
f.write(command + os.linesep)
def generate_launch_batch_files(self):
for source_port in self.source_ports:
for config in source_port.get_configurations():
if config == 'record':
continue
commands = source_port.get_launch_batch_commands(self, config)
path = os.path.join(self._get_game_launch_path(source_port, config), 'start.bat')
with open(path, 'w') as f:
print('Writing {0}'.format(path))
for command in commands:
f.write(command + os.linesep)
def generate_d2all_record_batch_file(self):
for source_port in self.source_ports:
if source_port.name == 'dsda':
commands = source_port.get_d2all_record_batch_commands(self, 'record')
path = os.path.join(self._get_game_launch_path(source_port, 'record'), 'd2all.bat')
with open(path, 'w') as f:
print('Writing {0}'.format(path))
for command in commands:
f.write(command + os.linesep)
def generate_map_launch_batch_files(self):
for episode in self.episodes:
for mission in episode.missions:
for source_port in self.source_ports:
for config in source_port.get_configurations():
commands = source_port.get_map_launch_batch_commands(
self, episode, mission, config)
path = self._get_map_batch_file_path(episode, mission, source_port, config)
with open(path, 'w') as f:
print('Writing {0}'.format(path))
f.write('@echo off')
f.write(os.linesep)
f.write('echo "Playing {0} MAP{1}: E{2}M{3} - {4}"{5}'.format(
self.name,
str(mission.level).zfill(2),
str(episode.number).zfill(2),
str(mission.number).zfill(2),
mission.name,
os.linesep))
for command in commands:
f.write(command + os.linesep)
def _get_map_batch_file_path(self, episode, mission, source_port, config):
game_launcher_path = os.path.join(
self.doom_config.unix_launchers_path,
self.get_directory_friendly_name(),
source_port.name,
config)
if not os.path.exists(game_launcher_path):
os.makedirs(game_launcher_path)
# SIGIL is a strange special case: they've called it Episode 5 of Doom,
# but for some reason it appears in place of episode 3, meaning the warp
# option needs to use 3 X. For that reason, the data file needs to specify
# it as episode 3, but I still want the batch files to use episode 5.
episode_number = episode.number if self.name != "SIGIL" else 5
batch_file_name = 'MAP{0} -- E{1}M{2} -- {3}.bat'.format(
str(mission.level).zfill(2),
str(episode_number).zfill(2),
str(mission.number).zfill(2),
mission.get_name_for_path())
return os.path.join(game_launcher_path, batch_file_name)
def _get_full_demo_paths(self):
full_demo_paths = []
game_demo_path = os.path.join(
self.doom_config.unix_demos_path, self.get_directory_friendly_name())
for root, dirs, files in os.walk(game_demo_path):
for file in [x for x in files if x.endswith('lmp')]:
full_demo_paths.append(os.path.join(root, file))
return full_demo_paths
def _get_win_demo_path(self, demo_path, win_demos_path):
demo_file_name = os.path.basename(demo_path)
demo_sub_dir_name = os.path.basename(os.path.dirname(demo_path))
return '{0}\\{1}\\{2}'.format(win_demos_path, demo_sub_dir_name, demo_file_name)
def _get_demo_launcher_path(self, demo_launchers_path, demo_path):
demo_file_name = os.path.basename(demo_path)
demo_sub_dir_name = os.path.basename(os.path.dirname(demo_path))
batch_file_name = '{0}.bat'.format(demo_file_name.split('.')[0])
path = os.path.join(demo_launchers_path, demo_sub_dir_name, batch_file_name)
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
return path
def _get_game_launch_path(self, source_port, config):
game_launcher_path = os.path.join(
self.doom_config.unix_launchers_path,
self.get_directory_friendly_name(),
source_port.name,
config)
if not os.path.exists(game_launcher_path):
os.makedirs(game_launcher_path)
return game_launcher_path
def _get_win_demos_path_for_game(self):
demo_launcher_path = os.path.join(
self.doom_config.unix_demo_launchers_path, self.get_directory_friendly_name())
if not os.path.exists(demo_launcher_path):
os.makedirs(demo_launcher_path)
win_demo_launcher_path = '{0}\\{1}'.format(
self.doom_config.demos_path, self.get_directory_friendly_name())
return win_demo_launcher_path
def _get_demo_launchers_path_for_game(self):
demo_launchers_path = os.path.join(
self.doom_config.unix_demo_launchers_path, self.get_directory_friendly_name())
if not os.path.exists(demo_launchers_path):
os.makedirs(demo_launchers_path)
return demo_launchers_path
def _get_viddump_launchers_path_for_game(self):
viddump_launchers_path = os.path.join(
self.doom_config.unix_viddump_launchers_path, self.get_directory_friendly_name())
if not os.path.exists(viddump_launchers_path):
os.makedirs(viddump_launchers_path)
return viddump_launchers_path
class Episode(object):
def __init__(self, name, number):
self.name = name
self.number = number
self.missions = []
def add_mission(self, mission):
self.missions.append(mission)
class Mission(object):
def __init__(self, name, number, level, wad, is_secret_level=False):
self.name = name
self.number = number
self.level = level
self.wad = wad
self.is_secret = is_secret_level
def get_name_for_path(self):
return self.name.replace('/', '').replace('!', '').replace("'", '')
class GameParser(object):
def __init__(self, csv_path, doom_config):
self.csv_path = csv_path
self.doom_config = doom_config
def parse_game(self, source_ports):
game_data = self.get_game_data_from_csv()
episode_boundaries = self.get_episode_boundaries(game_data)
game = Game(
game_data[0].game_name,
game_data[0].iwad,
game_data[0].pwad,
int(game_data[0].complevel),
game_data[0].release_date,
source_ports,
self.doom_config)
for _, value in episode_boundaries.items():
start = value[0]
end = value[1]
episode = Episode(
game_data[start].episode_name,
game_data[start].episode_number)
for i in range(start, end + 1):
is_secret_level = True if game_data[i].is_secret == 'true' else False
episode.add_mission(Mission(
game_data[i].mission_name,
int(game_data[i].mission_number),
int(game_data[i].level_number),
game_data[i].pwad,
is_secret_level=is_secret_level))
game.add_episode(episode)
return game
def get_game_data_from_csv(self):
game_data = []
with open(self.csv_path, 'r') as f:
reader = csv.reader(f)
GameCsvItem = namedtuple("GameCsv", next(reader))
[game_data.append(x) for x in map(GameCsvItem._make, reader)]
return game_data
def get_episode_boundaries(self, game_data):
episode_boundaries = {}
episode = 1
start = 0
level_count = len(game_data)
for index, item in enumerate(game_data):
if int(item.episode_number) != episode:
episode_boundaries[episode] = (start, index - 1)
start = index
episode += 1
if index == level_count - 1:
episode_boundaries[episode] = (start, index)
return episode_boundaries
class DoomConfig(object):
def __init__(self, windows_home_directory_path, unix_home_directory_path):
self.windows_home_directory_path = windows_home_directory_path
self.unix_home_directory_path = unix_home_directory_path
self.unix_source_ports_path = os.path.join(unix_home_directory_path, 'source-ports')
self.unix_launchers_path = os.path.join(unix_home_directory_path, 'launchers')
self.unix_demo_launchers_path = os.path.join(unix_home_directory_path, 'demo-launchers')
self.unix_viddump_launchers_path = os.path.join(unix_home_directory_path, 'viddump-launchers')
self.unix_demos_path = os.path.join(unix_home_directory_path, 'demos')
self.unix_saves_path = os.path.join(unix_home_directory_path, 'saves')
self.config_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'config')
self.source_ports_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'source-ports')
self.launchers_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'launchers')
self.demo_launchers_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'demo-launchers')
self.iwad_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'iwads')
self.wad_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'wads')
self.mod_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'mods')
self.demos_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'demos')
self.saves_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'saves')
self.viddump_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'viddump')
self.utils_path = '{0}\\{1}'.format(self.windows_home_directory_path, 'utils')
class MiscConfig(object):
def __init__(self, use_single_file_arg=True, use_config_arg=True, save_arg_name='save'):
self.use_single_file_arg = use_single_file_arg
self.use_config_arg = use_config_arg
self.save_arg_name = save_arg_name
class SourcePortBuilder(object):
def __init__(self, doom_config):
self.doom_config = doom_config
def get_source_ports(self):
source_ports = []
source_port_directories = next(os.walk(self.doom_config.unix_source_ports_path))[1]
port_version_pairs = [
tuple(directory.split('-')) for directory in source_port_directories
]
for port_name, version in port_version_pairs:
install_path = '{0}\\{1}-{2}'.format(
self.doom_config.source_ports_path,
port_name,
version)
if port_name == 'crispy_doom':
source_ports.append(
CrispyDoomSourcePort(install_path, version, self.doom_config))
elif port_name == 'doom_retro':
source_ports.append(
DoomRetroSourcePort(install_path, version, self.doom_config))
elif port_name == 'gzdoom':
source_ports.append(
GzDoomSourcePort(install_path, version, self.doom_config))
elif port_name == 'zdoom':
source_ports.append(
ZDoomSourcePort(install_path, version, self.doom_config))
elif port_name == 'prboom':
source_ports.append(
PrBoomSourcePort(install_path, version, self.doom_config))
elif port_name == 'glboom':
source_ports.append(
GlBoomSourcePort(install_path, version, self.doom_config))
elif port_name == 'dsda':
source_ports.append(
DsdaSourcePort(install_path, version, self.doom_config))
elif port_name == 'zandronum':
pass
else:
raise ValueError('{0} not supported. Please extend to support'.format(port_name))
return source_ports
class CliMenu(object):
def __init__(self, game_data_path, doom_config):
self.game_data_path = game_data_path
self.doom_config = doom_config
def display_source_ports(self):
builder = SourcePortBuilder(self.doom_config)
source_ports = builder.get_source_ports()
print('Found the following source ports:')
for source_port in source_ports:
print('{0} v{1}'.format(source_port.friendly_name, source_port.version))
print()
def get_user_game_selection(self):
self._display_banner()
builder = SourcePortBuilder(self.doom_config)
source_ports = builder.get_source_ports()
games = self._get_game_list(source_ports)
games_sorted_by_date = sorted(games, key=operator.attrgetter('release_date'))
print('The following games were found:')
for n, game in enumerate(games_sorted_by_date, start=1):
print('{0}. {1} -- {2}'.format(n, game.release_date, game.name))
all_option = len(games) + 1
print('{0}. All'.format(all_option))
print('Please select the game to generate batch files for:')
selection = self._get_valid_input(len(games) + 1)
if selection == all_option:
return games_sorted_by_date
return [games_sorted_by_date[selection - 1]]
def _display_banner(self):
print('=========================')
print('Doom Batch File Generator')
print('=========================')
print('This utility will generate batch files for each mission in a game.')
print('They are intended to be used as a quick way to pistol start any given mission.')
print()
def _get_game_list(self, source_ports):
games = []
os.chdir(self.game_data_path)
for game_file in glob.glob('*.csv'):
parser = GameParser(game_file, self.doom_config)
games.append(parser.parse_game(source_ports))
return games
def _get_valid_input(self, length):
while True:
selection = input()
try:
numeric_selection = int(selection)
if numeric_selection < 1 or numeric_selection > length:
raise ValueError
return numeric_selection
except ValueError:
print('Please enter a value between 1 and {0}.'.format(length))
def get_doom_config():
windows_doom_home_path = os.getenv('WINDOWS_DOOM_HOME')
unix_doom_home_path = os.getenv('UNIX_DOOM_HOME')
windows_usernames = next(os.walk('/mnt/c/Users'))[1]
windows_username = next(
username for username in windows_usernames if username not in ['Default', 'Public'])
if not windows_doom_home_path:
windows_doom_home_path = 'C:\\Users\\{0}\\{1}'.format(windows_username, 'doom')
if not unix_doom_home_path:
unix_doom_home_path = os.path.join('/c/Users', windows_username, 'doom')
return DoomConfig(windows_doom_home_path, unix_doom_home_path)
def main():
doom_config = get_doom_config()
menu = CliMenu('./game-data', doom_config)
menu.display_source_ports()
games = menu.get_user_game_selection()
for game in games:
game.generate_launch_batch_files()
game.generate_d2all_record_batch_file()
game.generate_map_launch_batch_files()
game.create_demo_directories()
game.create_save_directories()
game.generate_demo_launchers()
game.generate_viddump_launchers()
if __name__ == '__main__':
sys.exit(main())
| ac6e0afee0e58c61ede17fd21694e65c1334d4d6 | [
"Markdown",
"Python",
"Shell"
] | 3 | Shell | jacderida/doom-stuff | 025e622158aff94de1453270b59f4dff789eded5 | adb3cfa3c87454e47441e2d4d6310382b8dc3c7e |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Challenge.Models;
namespace Challenge.Services
{
public interface IChallengesService
{
Task<IList<ChallengeDB.Models.Challenge>> GetAllChallenges();
Task<JDoodleResponse> ExecuteAndValidateChallenge(ChallengeEntry challengeEntry);
Task<TopResults> GetTop3ByChallengeId(int challengeId);
}
}<file_sep>using Challenge.Models;
using Challenge.Services;
using ChallengeDB;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace Challenge
{
public class Startup
{
private readonly string _corsPolicyName = "CorsPolicy";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "Challenge", Version = "v1"}); });
services.AddCors(options =>
{
options.AddPolicy(_corsPolicyName,
builder =>
{
builder.WithOrigins("http://localhost:3000").AllowAnyMethod().AllowAnyHeader();
});
});
services.AddDbContext<ChallengeContext>(options =>
{
var context = Configuration.GetConnectionString("ChallengeContext");
options.UseSqlServer(context, o => o.EnableRetryOnFailure());
});
services.Configure<JDoodleOptions>(Configuration.GetSection("JDoodle"));
services.AddTransient<IJDoodleService, JDoodleService>();
services.AddHttpClient<JDoodleService>();
services.AddTransient<IChallengeStore, ChallengeStore>();
services.AddTransient<IChallengesService, ChallengesService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Challenge v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors(_corsPolicyName);
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}<file_sep>namespace Challenge.Models
{
public class JDoodleOptions
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Language { get; set; }
public int VersionIndex { get; set; }
public string ExecuteEndpoint { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Challenge.Models;
using ChallengeDB;
using ChallengeDB.Models;
namespace Challenge.Services
{
public class ChallengesService : IChallengesService
{
private readonly IChallengeStore _challengeStore;
private readonly IJDoodleService _jDoodleService;
public ChallengesService(IChallengeStore challengeStore, IJDoodleService jDoodleService)
{
_challengeStore = challengeStore;
_jDoodleService = jDoodleService;
}
public Task<IList<ChallengeDB.Models.Challenge>> GetAllChallenges()
{
return _challengeStore.GetAllChallenges();
}
public async Task<JDoodleResponse> ExecuteAndValidateChallenge(ChallengeEntry challengeEntry)
{
var challenge = await _challengeStore.GetChallengeById(challengeEntry.ChallengeId);
if (challenge == default) throw new Exception("Wrong challenge id");
var result = await _jDoodleService.CompileAndExecuteCode(challengeEntry.Script, challenge.Input);
if (result.Output != challenge.Output) throw new Exception("Wrong output was generated");
await _challengeStore.SaveChallengeResult(challenge, challengeEntry.Script, challengeEntry.Name, int.Parse(result.Memory),
float.Parse(result.CpuTime, CultureInfo.InvariantCulture.NumberFormat));
return result;
}
public async Task<TopResults> GetTop3ByChallengeId(int challengeId)
{
return new TopResults()
{
ByCpuTime = await _challengeStore.GetTopResultsByCpuTime(challengeId),
ByMemory = await _challengeStore.GetTopResultsByMemory(challengeId)
};
}
}
}<file_sep>import React, {useEffect, useState} from 'react';
import {TextField, Grid, Typography, Button, makeStyles} from '@material-ui/core';
import {Autocomplete} from '@material-ui/lab';
import {Formik, Form, Field} from 'formik';
import * as Yup from 'yup';
import {getAllChallenges, submitTask} from '../api/Challenge';
import {useCustomSnackbar} from '../hooks/useCustomSnackbar';
const useStyles = makeStyles(() => {
const centerHorizontally = {
display: 'flex',
justifyContent: 'center',
};
return {
TaskForm: {
...centerHorizontally,
},
TaskForm__grid: {
maxWidth: 600,
},
TaskForm__submit: {
...centerHorizontally,
},
};
});
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required.'),
script: Yup.string().required('Name is required.'),
challengeId: Yup.number().required('Challenge not selected'),
});
const SubmitTask = () => {
const classes = useStyles();
const [tasks, setTasks] = useState([]);
const [selectedTask, setSelectedTask] = useState({name: ''});
const {showSuccess, showError} = useCustomSnackbar();
useEffect(() => {
getAllChallenges()
.then(response => {
setTasks(response.data);
setSelectedTask(response.data[0]);
})
.catch(error => {
showError(error.message);
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const onTaskChange = task => {
setSelectedTask(task);
};
return (
<Formik
initialValues={{
name: '',
script: 'using System;\n\nclass Program\n{\n\tstatic void Main(string[] args)\n\t{\n\t}\n}',
challengeId: 0,
}}
validationSchema={validationSchema}
onSubmit={form => {
submitTask({...form, challengeId: form.challengeId || selectedTask?.id}).then(
() => showSuccess('Code was successfully uploaded!'),
err => showError(err?.response?.data?.message)
);
}}
>
{({errors, touched, setFieldValue}) => (
<Form className={classes['TaskForm']}>
<Grid container spacing={2} className={classes['TaskForm__grid']}>
<Grid item xs={12}>
<Field
as={TextField}
name="name"
label="Name"
variant="outlined"
size="small"
fullWidth
error={errors.name && touched.name}
helperText={errors.name && touched.name ? errors.name : undefined}
/>
</Grid>
<Grid item xs={12}>
<Autocomplete
options={tasks}
getOptionLabel={option => option.name}
variant="outlined"
renderInput={params => (
<TextField
{...params}
label="Select task"
error={!!errors.challengeId}
helperText={errors.challengeId ? errors.challengeId : undefined}
/>
)}
size="small"
onChange={(_, value) => {
setFieldValue('challengeId', value?.id);
onTaskChange(value);
}}
value={selectedTask}
getOptionSelected={option => option.id}
/>
</Grid>
<Grid item xs={12}>
<Typography variant="subtitle1">{selectedTask?.description}</Typography>
</Grid>
<Grid item xs={12}>
<Field
as={TextField}
name="script"
label="Solution code"
multiline
rows={12}
variant="outlined"
size="small"
fullWidth
error={errors.script && touched.script}
helperText={errors.script && touched.script ? errors.script : undefined}
/>
</Grid>
<Grid item xs={12} className={classes['TaskForm__submit']}>
<Button variant="contained" color="primary" type="submit">
Submit
</Button>
</Grid>
</Grid>
</Form>
)}
</Formik>
);
};
export default SubmitTask;
<file_sep>namespace Challenge.Models
{
public class ChallengeEntry
{
public string Name { get; set; }
public string Script { get; set; }
public int ChallengeId { get; set; }
}
}<file_sep>using ChallengeDB.Models;
using Microsoft.EntityFrameworkCore;
namespace ChallengeDB
{
public class ChallengeContext : DbContext
{
public ChallengeContext(DbContextOptions<ChallengeContext> options) : base(options)
{
}
public virtual DbSet<Challenge> Challenges { get; set; }
public virtual DbSet<ChallengeResult> ChallengeResults { get; set; }
}
}<file_sep>using System.Text.Json.Serialization;
namespace Challenge.Models
{
public class JDoodleResponse
{
[JsonPropertyName("output")] public string Output { get; set; }
[JsonPropertyName("memory")] public string Memory { get; set; }
[JsonPropertyName("cpuTime")] public string CpuTime { get; set; }
}
}<file_sep>import React, {useEffect, useState} from 'react';
import {getAllChallenges, getTop3} from '../api/Challenge';
import {useCustomSnackbar} from '../hooks/useCustomSnackbar';
import TopTable from '../components/TopTable';
const TopThree = () => {
const [top3, setTop3] = useState([]);
const {showError} = useCustomSnackbar();
useEffect(() => {
getAllChallenges().then(challenges => {
const promises = [];
for (const challenge of challenges.data) {
promises.push(
getTop3(challenge.id).then(
response => ({...response.data, challenge}),
error => showError(error.message)
)
);
}
Promise.all(promises).then(x => setTop3(x));
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<>
{top3.map(({challenge, byMemory, byCpuTime}, index) => {
return (
<div key={index}>
<h2>{challenge.name}</h2>
<h3>By cpu time</h3>
<TopTable rows={byCpuTime} />
<h3>By memory</h3>
<TopTable rows={byMemory} />
</div>
);
})}
</>
);
};
export default TopThree;
<file_sep>using System.Collections.Generic;
using ChallengeDB.Models;
namespace Challenge.Models
{
public class TopResults
{
public IList<ChallengeResult> ByMemory { get; set; }
public IList<ChallengeResult> ByCpuTime { get; set; }
}
}<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace ChallengeDB.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Challenges",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Input = table.Column<string>(type: "nvarchar(max)", nullable: true),
Output = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Challenges", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ChallengeResults",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Script = table.Column<string>(type: "nvarchar(max)", nullable: true),
ChallengeId = table.Column<int>(type: "int", nullable: false),
Memory = table.Column<int>(type: "int", nullable: false),
CpuTime = table.Column<float>(type: "real", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChallengeResults", x => x.Id);
table.ForeignKey(
name: "FK_ChallengeResults_Challenges_ChallengeId",
column: x => x.ChallengeId,
principalTable: "Challenges",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ChallengeResults_ChallengeId",
table: "ChallengeResults",
column: "ChallengeId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChallengeResults");
migrationBuilder.DropTable(
name: "Challenges");
}
}
}
<file_sep>using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Challenge.Models;
using Microsoft.Extensions.Options;
namespace Challenge.Services
{
public class JDoodleService : IJDoodleService
{
private readonly HttpClient _httpClient;
private readonly JDoodleOptions _options;
public JDoodleService(HttpClient httpClient, IOptions<JDoodleOptions> jDoodleOptions)
{
_httpClient = httpClient;
_options = jDoodleOptions.Value;
}
public async Task<JDoodleResponse> CompileAndExecuteCode(string script, string stdIn = null)
{
var jDoodleEntry = new JDoodleEntry
{
ClientId = _options.ClientId,
ClientSecret = _options.ClientSecret,
Language = _options.Language,
VersionIndex = _options.VersionIndex,
Script = script,
StdIn = stdIn
};
var @string = JsonSerializer.Serialize(jDoodleEntry);
using var content = new StringContent(@string, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_options.ExecuteEndpoint, content);
var result = await response.Content.ReadFromJsonAsync<JDoodleResponse>();
return result;
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ChallengeDB.Models
{
public class ChallengeResult
{
[Key] public int Id { get; set; }
public string Name { get; set; }
public string Script { get; set; }
[ForeignKey("ChallengeId")] public Challenge Challenge { get; set; }
public int ChallengeId { get; set; }
public int Memory { get; set; }
public float CpuTime { get; set; }
}
}<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {makeStyles} from '@material-ui/core';
import TopAppBar from '../components/TopAppBar';
const useStyles = makeStyles(() => ({
MainLayout: {
display: 'flex',
height: '100%',
},
MainLayout__wrapper: {
display: 'flex',
flex: '1 1 auto',
paddingTop: 64,
},
MainLayout__container: {
display: 'flex',
flex: '1 1 auto',
},
MainLayout__content: {
flex: '1 1 auto',
height: '100%',
padding: '20px',
},
}));
const MainLayout = ({children}) => {
const classes = useStyles();
return (
<div className={classes['MainLayout']}>
<TopAppBar />
<div className={classes['MainLayout__wrapper']}>
<div className={classes['MainLayout__container']}>
<div className={classes['MainLayout__content']}>{children}</div>
</div>
</div>
</div>
);
};
MainLayout.propTypes = {
children: PropTypes.node,
};
export default MainLayout;
<file_sep>import React from 'react';
import {Toolbar, AppBar, makeStyles, ButtonGroup, Button} from '@material-ui/core';
import {useLocation, useHistory} from 'react-router-dom';
const useStyles = makeStyles(theme => ({
AppBar: {
backgroundColor: theme.palette.background.dark,
position: 'fixed',
boxShadow: 'none',
},
AppBar__logo: {
flexGrow: 1,
},
AppBar__logoButton: {
color: 'white',
},
}));
const TopAppBar = () => {
const classes = useStyles();
const location = useLocation();
const history = useHistory();
return (
<AppBar className={classes['AppBar']}>
<Toolbar>
<div className={classes['AppBar__logo']}>
<Button
className={classes['AppBar__logoButton']}
onClick={() => {
history.push('/submitTask');
}}
>
COGNIZANT CHALLENGE
</Button>
</div>
<ButtonGroup disableElevation variant="contained" color="primary">
<Button
onClick={() => {
history.push('/submitTask');
}}
disabled={location.pathname === '/submitTask' || location.pathname === '/'}
>
Solve
</Button>
<Button
onClick={() => {
history.push('/topThree');
}}
disabled={location.pathname === '/topThree'}
>
Top 3
</Button>
</ButtonGroup>
</Toolbar>
</AppBar>
);
};
export default TopAppBar;
<file_sep>using System.Text.Json.Serialization;
namespace Challenge.Models
{
public class JDoodleEntry
{
[JsonPropertyName("clientId")] public string ClientId { get; set; }
[JsonPropertyName("clientSecret")] public string ClientSecret { get; set; }
[JsonPropertyName("language")] public string Language { get; set; }
[JsonPropertyName("versionIndex")] public int VersionIndex { get; set; }
[JsonPropertyName("script")] public string Script { get; set; }
[JsonPropertyName("stdin")] public string StdIn { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace ChallengeDB.Models
{
public class Challenge
{
[Key] public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Input { get; set; }
public string Output { get; set; }
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChallengeDB.Models;
using Microsoft.EntityFrameworkCore;
namespace ChallengeDB
{
public class ChallengeStore : IChallengeStore
{
private readonly ChallengeContext _context;
public ChallengeStore(ChallengeContext context)
{
_context = context;
}
public async Task<IList<Challenge>> GetAllChallenges()
{
return await _context.Challenges.AsNoTracking().ToListAsync();
}
public Task<Challenge> GetChallengeById(int id)
{
return _context.Challenges.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<IList<ChallengeResult>> GetTopResultsByMemory(int challengeId)
{
return await _context.ChallengeResults.AsNoTracking()
.Where(x => x.ChallengeId == challengeId)
.OrderBy(x => x.Memory)
.Take(3)
.ToListAsync();
}
public async Task<IList<ChallengeResult>> GetTopResultsByCpuTime(int challengeId)
{
return await _context.ChallengeResults.AsNoTracking()
.Where(x => x.ChallengeId == challengeId)
.OrderBy(x => x.CpuTime)
.Take(3)
.ToListAsync();
}
public async Task SaveChallengeResult(Challenge challenge, string script, string name, int memory, float cpuTime)
{
await using (_context)
{
_context.ChallengeResults.Add(new ChallengeResult()
{
ChallengeId = challenge.Id,
Script = script,
Name = name,
Memory = memory,
CpuTime = cpuTime
});
await _context.SaveChangesAsync();
}
}
}
}<file_sep>import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
const TopTable = ({rows}) => {
return (
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Script</TableCell>
<TableCell>Cpu time</TableCell>
<TableCell>Memory</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, key) => (
<TableRow key={key}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell>{row.script}</TableCell>
<TableCell>{row.cpuTime}</TableCell>
<TableCell>{row.memory}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
};
export default TopTable;
<file_sep>import React from 'react';
import {useSnackbar} from 'notistack';
import {Slide} from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
const Alert = React.forwardRef((props, ref) => <MuiAlert elevation={6} variant="filled" {...props} ref={ref} />);
function transitionLeft(props) {
return <Slide {...props} direction="right" />;
}
export function useCustomSnackbar() {
const {enqueueSnackbar, closeSnackbar} = useSnackbar();
function showSnackbar(text, severity) {
enqueueSnackbar(text, {
autoHideDuration: 6000,
TransitionComponent: transitionLeft,
content: (key, message) => (
<Alert
onClose={() => {
closeSnackbar(key);
}}
severity={severity}
id={key}
>
{message}
</Alert>
),
});
}
function showError(text) {
showSnackbar(text, 'error');
}
function showSuccess(text) {
showSnackbar(text, 'success');
}
return {
showSnackbar,
showError,
showSuccess,
};
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Challenge.Models;
using Challenge.Services;
using Microsoft.AspNetCore.Mvc;
namespace Challenge.Controllers
{
[ApiController]
[Route("challenges")]
public class ChallengesController : ControllerBase
{
private readonly IChallengesService _challengeService;
public ChallengesController(IChallengesService challengeService)
{
_challengeService = challengeService;
}
[HttpGet]
public async Task<IEnumerable<ChallengeDB.Models.Challenge>> GetAllChallenges()
{
return await _challengeService.GetAllChallenges();
}
[HttpGet]
[Route("{challengeId}/top3")]
public Task<TopResults> GetTopResults(int challengeId)
{
return _challengeService.GetTop3ByChallengeId(challengeId);
}
[HttpPost]
[Route("submitTask")]
public async Task<ActionResult<JDoodleResponse>> SubmitTask([FromBody] ChallengeEntry challengeEntry)
{
try
{
var result = await _challengeService.ExecuteAndValidateChallenge(challengeEntry);
return new OkObjectResult(result);
}
catch (Exception e)
{
return new BadRequestObjectResult(new {message = e.Message});
}
}
}
}<file_sep>using System.Threading.Tasks;
using Challenge.Models;
namespace Challenge.Services
{
public interface IJDoodleService
{
Task<JDoodleResponse> CompileAndExecuteCode(string script, string stdIn = null);
}
}<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using ChallengeDB.Models;
namespace ChallengeDB
{
public interface IChallengeStore
{
Task<IList<Challenge>> GetAllChallenges();
Task<Challenge> GetChallengeById(int id);
Task SaveChallengeResult(Challenge challenge, string script, string name, int memory, float cpuTime);
Task<IList<ChallengeResult>> GetTopResultsByMemory(int challengeId);
Task<IList<ChallengeResult>> GetTopResultsByCpuTime(int challengeId);
}
} | e44041f60457f18e39955e7daf833e110bb2108b | [
"JavaScript",
"C#"
] | 23 | C# | elsc3814/Challenge | 8e2ea42ed35317abf4197c7f2524e255bbb33c9f | 576a15f4a5c9401f1baae00900998e95a248d6a8 |
refs/heads/master | <file_sep># school-attendance-required-finder
<a href="https://ci.appveyor.com/project/shaneilahi/school-present-required-finder" rel="nofollow"><img src="https://camo.githubusercontent.com/d89145a88733edb86677921b04a1df9857af7b92/68747470733a2f2f63692e6170707665796f722e636f6d2f6170692f70726f6a656374732f7374617475732f756264636e6e333875616e616f7169633f7376673d74727565" alt="Build status" data-canonical-src="https://ci.appveyor.com/api/projects/status/ubdcnn38uanaoqic?svg=true" style="max-width:100%;"></a></p>
<a href="https://github.com/shaneilahi/school-present-required-finder/releases">Visit Releases</a>
<img src="https://i.imgur.com/TKZjQP2.pngs">
Ever wondered How many days you need to go to school for getting 75% attendance?
if you would like to find out
i have coded this program to find it days you need to go :).
i did this for me because i was curious to find out how many days i need to head to shool.
<file_sep>#include <iostream>
using namespace std;
// We are going to Design our program bit by bit
// like one function doing one job
// and other one taking arguments and doing calculation
// for fiding reqquired days to be present in school
// we need to get the user total days he went to school
// or his current present percentage.
int userInput()
{
cout << "Enter your percentage: ";
int x{};
cin >> x;
return x;
}
void findDaysRequired(double x)
{
double converPerToDecimal{ x / 100 };
double doMath{ converPerToDecimal * 365 }; // so it will find Perctange of 365 days for eg 50% of 365 days.
if (doMath < 273.75)
{
cout << "You Need " << 273.75 - doMath << " Days Required to go.\n\n";
}
else
{
cout << "You Already have achieved more than 75% " << doMath - 273.75 << "+ Days\n\n";
}
}
int main()
{
//get user percentage
//userInput()
//find the days required for getting 75%
//findDaysRequired()
while (true)
{
int input{ userInput() };
findDaysRequired(input);
}
return 0;
} | 7a59a98b3105940f3047b05812c474f978138005 | [
"Markdown",
"C++"
] | 2 | Markdown | shaneilahi/school-present-required-finder | a530e51eab4ce38f1a02881ed850d6c9bc4fb9e1 | ed4231cb547400e831221819bd267dd81572df7a |
refs/heads/master | <file_sep># DATECS LP-50 Thermal Printer Client
Utility to assist print labels from DATECS LP 50 Thermal Line Printer. You can print barcodes and text from a saved form in the printers memory
<file_sep>using System.Timers;
public class SerialTimer {
public const int DEFAULT_TIMEOUT = 1000;
System.Timers.Timer timer = new System.Timers.Timer();
public bool timedout = false;
public SerialTimer(){
timedout = false;
timer.AutoReset = false;
timer.Enabled = false;
timer.Interval = DEFAULT_TIMEOUT;
timer.Elapsed += new ElapsedEventHandler(OnTimeout);
}
/// <summary>
/// Called by ElapsedEventHandler when counter runs down.
/// </summary>
/// <param name="source">Even source</param>
/// <param name="e">Event args</param>
private void OnTimeout(object source, ElapsedEventArgs e)
{
Console.WriteLine("Timed out");
timedout = true;
timer.Stop();
}
/// <summary>
/// Resets timer and starts count-down to specified timeout
/// </summary>
/// <param name="timeout"></param>
public void Start(double timeout)
{
timer.Interval = timeout; //time to time out in milliseconds
timer.Stop();
timedout = false;
timer.Start();
}
}<file_sep>using CsvHelper;
using CsvHelper.Configuration;
using System.Text;
using System.IO.Ports;
namespace ThermalPrinter
{
/// <summary>
/// Simple application that sends commands to a DATECS LP-50 Thermal printer to print out a label from a saved form
/// in the printers memory.
///
/// http://www.datecs.bg/en/products/53
///
/// It requires command line arg file_name which should be a CSV with format:
/// <code>FORM_NAME,Variable_count,V00,V01,..,Vnn</code>
/// <para>Note that graphics are supposed to be preloaded in the printer. The DATECS label editor is best for this task.</para>
/// </summary>
class Program
{
private const int PORT_READ_TIMEOUT = 10000;
private const int PORT_WRITE_TIMEOUT = 10000;
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting program...");
if (args.Length == 0)
{
throw new Exception("Usage: Please include file name as an argument to this program.");
}
else
{
Program bridge = new Program();
Console.WriteLine("Reading file {0}...", args[0]);
List<string> variables = bridge.ReadValues(args[0]);
Console.WriteLine("Acquired data: {0}", string.Join(",", variables.ToArray()));
string LP_50_PORT = "COM5"; //fetch port from config
Console.WriteLine("Configured port is {0}", LP_50_PORT);
List<String> ports = bridge.getAllPorts();
Console.WriteLine("Enumerating available ports...");
bool targetPortFound = false;
foreach (string port in ports)
{
if (port.ToLower().Equals(LP_50_PORT.ToLower()))
{ //select the configured port
targetPortFound = true;
SerialPort serialPort = null;
try
{
serialPort = new SerialPort(port);
if (serialPort.IsOpen == false)
{ //if not open, open the port
Console.WriteLine("Openning the port...");
serialPort.Open();
serialPort.ReadTimeout = PORT_READ_TIMEOUT;
serialPort.WriteTimeout = PORT_WRITE_TIMEOUT;
Console.WriteLine("Communicating through {0}", port);
Console.WriteLine("Element count: {0}", variables.Count());
bridge.ConverseWithPrinter(serialPort, variables[0], variables.GetRange(1, variables.Count() - 1));
}
else
{
Console.WriteLine("Port is open");
throw new Exception(string.Format("Serial port {0} is already in use by another program.", LP_50_PORT));
}
}
finally
{
if (serialPort != null)
{ //always close port unconditionally
Console.WriteLine("Closing port..");
serialPort.Close();
}
}
//done with the LP-50 port communication, ignore any other ports
break;
}
}
if (targetPortFound)
{
Console.WriteLine("\n\npExiting.");
}
else
{
throw new Exception(String.Format("Printer not found on port {0}. Please connect printer on correct USB port.", LP_50_PORT));
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("{0}\n\nENTER to exit", e.Message);
Console.ReadLine(); //wait for user to press any button
}
}
/// <summary>
/// Reads the CSV file, expected to be a single line of data in format:
/// FORM_NAME,Variable_count,V00,V01,..,Vnn
/// </summary>
/// <param name="filePath">Absolute path of target file which should be ready to be openned for read operation</param>
/// <returns>Arraylist with order: FORM_NAME,Variable_count,V00,V01,..,Vnn</returns>
/// <exception cref="Exception">IO errors and other malfunctions will be wrapped under generic exception</exception>
public List<string> ReadValues(string filePath)
{
TextReader streamReader = null;
try
{
List<string> values = new List<string>();
Console.WriteLine("Reading data {0}", filePath);
var config = new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture)
{
HasHeaderRecord = false,
Encoding = Encoding.UTF8, // Our file uses UTF-8 encoding.
Delimiter = "," // The delimiter is a comma.
};
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var textReader = new StreamReader(fs, Encoding.UTF8))
using (var csv = new CsvReader(textReader, config))
{
// csv.Read();
var data = csv.GetRecords<string>();
string value;
while(csv.Read()) {
for(int i=0; csv.TryGetField<string>(i, out value); i++) {
Console.WriteLine("Item = {0}", value);
values.Add(value);
}
}
}
}
return values;
}
catch (Exception e)
{
throw new Exception("Error reading file. " + e.Message);
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
}
/// <summary>
/// Fetch available COM ports.
/// </summary>
/// <returns>List of available Serial ports</returns>
public List<string> getAllPorts()
{
List<String> allPorts = new List<String>();
foreach (String portName in System.IO.Ports.SerialPort.GetPortNames())
{
allPorts.Add(portName);
}
Console.WriteLine("Available ports = {0}", string.Join(",", allPorts.ToArray()));
return allPorts;
}
/// <summary>
/// Communicate with Datecs LP-50 Thermal printer using the printer commands detailed in the documentation at
///
/// http://www.datecs.bg/en/products/53
/// </summary>
/// <param name="port">Openned port that is ready for read/write ops</param>
/// <param name="targetForm">The form to activate, it must exist in the printer or nothing happens</param>
/// <param name="variables">the values to substitute in the form variables, they SHOULD be exact NUMBER as in form for best results. The variables SHOULD ALSO be IN THE ORDER they are declared in the forms e.g from V00,V01...Vnn</param>
public void ConverseWithPrinter(SerialPort port, string targetForm, List<String> variables)
{
try
{
//Read installed forms in printer memory and confirm if required form is available
//Us UF command to list forms
Console.WriteLine("Reading available forms...");
port.WriteLine("UF");
List<String> forms = ReadPortResponse(port, PORT_READ_TIMEOUT * 2, true);
//forms are listed starting with the form count as first item e.g
//002
//L0
//L1
//means there are 2 forms named L0,L1
Console.WriteLine("Available forms: {0}", string.Join(",", forms.ToArray()));
bool targetFormAvailable = false;
foreach (string form in forms)
{
Console.WriteLine(form);
if (form.ToLower().Equals(targetForm.ToLower()))
{ //Form names are case insensitive
targetFormAvailable = true;
}
}
if (!targetFormAvailable)
{
Console.WriteLine("WARNING Form {0} not found in printer memory, printer may not be properly configured.", targetForm);
}
//Load & activate target form, user FR command
port.WriteLine(string.Format("FR\"{0}\"", targetForm));
//read all form prompts and respond till no more prompts, then print label
//It is very important that the variable be equal number with the prompts, otherwise
//printer will remain in prompt mode and won't take other commands with expected behavior
port.WriteLine("?"); //prompt printer to start variable & counter prompts.
//Write out variables to substitute each prompt.
foreach (string variable in variables)
{
port.WriteLine(variable);
}
//flush out any bytes
port.BaseStream.Flush();
//Print one label out of the above variables. Uses athe P command.
port.WriteLine("P1,1");
Console.WriteLine("Completed");
}
finally
{
port.BaseStream.Flush();
port.Close();
}
}
///Read printer output as unique lines. The CR character is stripped out at the end.
///Open serial port to read from
///Timeout in milliseconds after which read is abandoned
///multiple - whether only a single-line response is expected. multiple lines will take longer
///as we have to wait for the printer to write every line and can't establish the exact rows to wait for
///This forces a wait, max the timeout period to wait for the next line
///
///Returns an array list of the individual lines read out
private List<string> ReadPortResponse(SerialPort port, int timeout, bool multiple)
{
Console.WriteLine("Reading printer response...");
this.FlushPortBuffers(port);
SerialTimer timer = new SerialTimer();
timer.Start(timeout);
while (port.BytesToRead == 0 && !timer.timedout) ; //wait for inbound buffer until timeout
List<String> response = new List<String>();
if (port.BytesToRead > 0)
{
try
{
int c;
StringBuilder b = new StringBuilder();
//read line by line
while ((c = port.ReadByte()) != '\n' || port.BytesToRead > 0)
{
if (c == '\r')
{ //a line of input has been read
response.Add(b.ToString());
b.Clear();
//if multiple lines are expected, we wait for a while for next bytes to be written to buffer if any
if (multiple)
{
timer.Start(PORT_READ_TIMEOUT);
while (port.BytesToRead == 0 && !timer.timedout) ;
}
}
else if (c == '\n')
{
continue; //Continue to new line
}
else
{
b.Append((char)c);
}
}
}
catch (TimeoutException e)
{
Console.Error.WriteLine("Read timed out. {0}", e.Message);
}
}
else
{
Console.WriteLine("Read timed out");
}
return response;
}
/// <summary>
/// Discards anything in the IO buffers of the serial port.
/// </summary>
/// <param name="port">Target port to flush buffers. It should be open.</param>
private void FlushPortBuffers(SerialPort port)
{
port.DiscardInBuffer();
port.DiscardOutBuffer();
}
}
}
| ca1f3abeab7b48838f3be2033ec36e6df270aa6c | [
"Markdown",
"C#"
] | 3 | Markdown | kipkosgeik/thermal-client-lp50 | bc11ac41ef81a913538524780f75092e340e98bd | 8ed32a30c737b376cf6a3284148297f874b38be4 |
refs/heads/master | <file_sep>using ShopCartFramework.Api.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopCartFramework.Api.Dtos;
using System.Linq;
namespace ShopCartFramework.Api
{
public sealed class ShoppingBasket
{
private readonly IShopCartService shopCartService;
public int? Id { get; private set; }
/// <summary>
/// Initialize the Shopping Basket with an Instance of IShopCartService.
/// </summary>
/// <param name="shopCartService"></param>
public ShoppingBasket(IShopCartService shopCartService)
{
this.shopCartService = shopCartService;
}
/// <summary>
/// Creates a new Shopping Basket in the ShopCartService and assigns the Id.
/// </summary>
/// <returns></returns>
public async Task CreateNewBasket()
{
this.Id = await this.shopCartService.CreateBasket();
}
/// <summary>
/// Retrieves an existing Shopping Basket from the ShopCartService.
/// </summary>
/// <param name="basketId"></param>
/// <returns></returns>
public async Task<IEnumerable<ShoppingItem>> GetExistingBasket(int basketId)
{
this.Id = basketId;
return await this.shopCartService.GetBasketItems(basketId);
}
/// <summary>
/// Returns all items in this Basket.
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<ShoppingItem>> GetShoppingItems()
{
if (this.Id == null)
throw new InvalidOperationException("Basket must be created before Items can be retrieved.");
return await this.shopCartService.GetBasketItems(this.Id.Value);
}
/// <summary>
/// Adds a Shopping Item to this basket.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
/// <returns></returns>
public async Task AddShoppingItem(string name, string description)
{
if (this.Id == null)
await this.CreateNewBasket();
var request = new AddShoppingItemRequest(this.Id.Value)
{
Name = name,
Description = description
};
await this.shopCartService.AddItemToBasket(request);
}
/// <summary>
/// Deletes an Item from this Basket using the Item Id. Use GetShoppingItems to determine the Id.
/// </summary>
/// <param name="itemId"></param>
/// <returns></returns>
public async Task DeleteShoppingItem(int? itemId)
{
if (this.Id == null)
throw new InvalidOperationException("Basket must be created before Items can be removed.");
if (itemId == null)
throw new InvalidOperationException($"Item with Id {itemId} does not exist in this Basket!");
var items = await this.shopCartService.GetBasketItems(this.Id.Value);
if (items.Any(x => x.Id == itemId))
{
var request = new DeleteShoppingItemRequest(this.Id.Value) { ShoppingItemId = itemId.Value };
await this.shopCartService.DeleteItemFromBasket(request);
}
}
/// <summary>
/// Deletes a single Item from this Basket using the Item's Name. Will only Delete a single instance of the Item - call multiple times to Delete many.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public async Task DeleteShoppingItem(string name)
{
if (this.Id == null)
throw new InvalidOperationException("Basket must be created before Items can be removed.");
var deleteItem = (await this.shopCartService.GetBasketItems(this.Id.Value)).First(x => x.Name == name);
await this.DeleteShoppingItem(deleteItem.Id);
}
/// <summary>
/// Clears all Items from the current Basket. The Id of the Items is not reset.
/// </summary>
/// <returns></returns>
public async Task ClearBasketItems()
{
if (this.Id == null)
throw new InvalidOperationException("Basket must be created before Items can be cleared.");
await this.shopCartService.ClearAllItems(this.Id.Value);
}
/// <summary>
/// Updates the Quantity of an Item by Name. Will Remove or Add instances of the Item depending on the amount relative to the current amount.
/// </summary>
/// <param name="name"></param>
/// <param name="updatedQuantity"></param>
/// <returns></returns>
public async Task UpdateItemQuantity(string name, int updatedQuantity)
{
if (this.Id == null)
throw new InvalidOperationException("Basket must be created before Items can be updated.");
var updateItem = (await this.shopCartService.GetBasketItems(this.Id.Value)).First(x => x.Name == name);
if (updateItem == null)
throw new InvalidOperationException("This item does not exist in the current Basket");
await this.shopCartService.UpdateItemQuantity(
new UpdateShoppingItemQuantityRequest(this.Id.Value) {ItemName = updateItem.Name, UpdatedQuantity = updatedQuantity});
}
}
}<file_sep>using Newtonsoft.Json;
namespace ShopCartFramework.Api.Dtos
{
public class UpdateShoppingItemQuantityRequest
{
public int BasketId { get; }
[JsonProperty("name")]
public string ItemName { get; set; }
[JsonProperty("updatedQuantity")]
public int UpdatedQuantity { get; set; }
public UpdateShoppingItemQuantityRequest(int basketId)
{
this.BasketId = basketId;
}
}
}
<file_sep>using Newtonsoft.Json;
namespace ShopCartFramework.Api.Dtos
{
public class ShoppingBasketResponse
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("items")]
public ShoppingItem[] Items { get; set; }
}
}<file_sep># DMOC.ShopCartFramework
Checkout.com Submission - Part 2 (Framework)
This Class Library can be used to create and manage a basket of items in [DMOC.ShopCart](https://github.com/DMOCoder/DMOC.ShopCart/blob/master/README.md).
The following actions are available:
1. Create a Basket
2. Retrieve a Basket and its Items
3. Change the Quantity of Items
4. Delete an Item
5. Clear a Basket.
## Setup
### Requirements
This Library requires .NET Core 2.1 and Visual Studio 2017. An instance of DMOC.ShopCart running on an accessible server is also required.
### Installation
The Library can be added to a project by first building the Library in Visual Studio. The output .dlls can then be added to your project as a Reference.
## Using the Library
Ensure that the DMOC.ShopCart service is running on your server before using this library.
### Initialising
The library is very simple to use. Create an Instance of `ShoppingBasket` in your code and Initialize it with a new instance of ShopCartService.
ShopCartService will require the Base Url of the DMOC.ShopCart service you will be consuming.
e.g.
```C#
var shopCartService = new ShopCartService("http://my-service-url.com");
var shoppingBasket = new ShoppingBasket(shopCartService);
//call this method to initialize the basket:
shoppingBasket.CreateNewBasket();
//alternatively, if you have created a Basket previously and wish to recall it:
int myBasketId = 42;
shoppingBasket.GetExistingBasket(myBasketId);
```
### Adding an Item
To Add an Item, call the `AddShoppingItem` method, providing Name and Description arguements.
e.g.
```C#
//add a new Item
shoppingBasket.AddShoppingItem("Bananas", "Big Yellow Fruit");
```
### Viewing your Basket Items
To View the Items in the Basket, call the `GetShoppingItems` method on the ShoppingBasket.
e.g.
```C#
//get items
var myItems = shoppingBasket.GetShoppingItems();
```
### Delete Items
Items can be deleted by their Item Id or by Name. The latter will delete a single Item matching that Name from the basket.
e.g
```C#
//delete by Id
shoppingBasket.DeleteShoppingItem(12);
//delete by Name
shoppingBasket.DeleteShoppingItem("Bananas");
```
### Update Item Quantity
An Item's Quantity can be updated by providing the Item Name and the Requested Quantity. This will Delete or Add instances of the Item depending on the Requested Quantity and Current Quantity.
It will only update Items that currently Exist in the Basket and will not accept negative Quantities.
e.g.
```C#
//update quantity
shoppingBasket.UpdateItemQuantity("Bananas", 5);
```
### Clear Basket
All Items can be quickly removed from the Basket by calling `ClearBasketItems`.
e.g.
```C#
//clear all items
shoppingBasket.ClearBasketItems()
```
<file_sep>using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using ShopCartFramework.Api.Concretes;
using ShopCartFramework.Api.Dtos;
using Shouldly;
namespace ShopCartFramework.Api.Tests
{
[TestFixture]
public class ShopCartServiceIntegrationTests
{
private ShopCartService subject;
[SetUp]
public void SetUp()
{
this.subject = new ShopCartService($"http://localhost:44001");
}
[Test]
[ExcludeFromCodeCoverage]
public async Task ShouldCreateBasket()
{
var result = await this.subject.CreateBasket();
}
[Test]
[ExcludeFromCodeCoverage]
public async Task ShouldGetExistingBasketItems()
{
var basketId = await this.subject.CreateBasket();
var itemFirst = new AddShoppingItemRequest(basketId) { Name = "coolHat", Description = "cool and breezy"};
var itemSecond = new AddShoppingItemRequest(basketId) { Name = "captainsHat", Description = "for captains only"};
await this.subject.AddItemToBasket(itemFirst);
await this.subject.AddItemToBasket(itemSecond);
var basket = await this.subject.GetBasketItems(basketId);
basket.ShouldContain(x => x.Name == itemFirst.Name && x.Description == itemFirst.Description);
basket.ShouldContain(x => x.Name == itemSecond.Name && x.Description == itemSecond.Description);
}
[Test]
[ExcludeFromCodeCoverage]
public async Task ShouldDeleteItem()
{
var basketId = await this.subject.CreateBasket();
var itemFirst = new AddShoppingItemRequest(basketId) { Name = "catHat", Description = "dr seuss?" };
var itemSecond = new AddShoppingItemRequest(basketId) { Name = "witchHat", Description = "gender neutral" };
var deleteId = await this.subject.AddItemToBasket(itemFirst);
await this.subject.AddItemToBasket(itemSecond);
await this.subject.DeleteItemFromBasket(new DeleteShoppingItemRequest(basketId) { ShoppingItemId = deleteId });
var basketItems = await this.subject.GetBasketItems(basketId);
basketItems.ShouldNotContain(x => x.Id == deleteId);
}
[Test]
[ExcludeFromCodeCoverage]
public async Task ShouldUpdateItemQuantity()
{
var basketId = await this.subject.CreateBasket();
var updateQty = 5;
var updateName = "reallyBigHat";
var itemFirst = new AddShoppingItemRequest(basketId) { Name = updateName, Description = "causes crippling neck damage" };
var itemSecond = new AddShoppingItemRequest(basketId) { Name = "secretCameraHat", Description = "5 days from retirement" };
var itemDuplicate = new AddShoppingItemRequest(basketId) { Name = updateName, Description = "causes crippling neck damage" };
await this.subject.AddItemToBasket(itemFirst);
await this.subject.AddItemToBasket(itemSecond);
await this.subject.AddItemToBasket(itemDuplicate);
await this.subject.UpdateItemQuantity(new UpdateShoppingItemQuantityRequest(basketId)
{
ItemName = updateName,
UpdatedQuantity = updateQty
});
var items = await this.subject.GetBasketItems(basketId);
items.Where(x => x.Name == updateName).Count().ShouldBe(updateQty);
}
[Test]
[ExcludeFromCodeCoverage]
public async Task ShouldResetBasket()
{
var basketId = await this.subject.CreateBasket();
await this.subject.AddItemToBasket(new AddShoppingItemRequest(basketId) { Name = "boringItemOne"});
await this.subject.AddItemToBasket(new AddShoppingItemRequest(basketId) { Name = "boringItemTwo" });
await this.subject.AddItemToBasket(new AddShoppingItemRequest(basketId) { Name = "boringItemThree" });
var basketItems = await this.subject.GetBasketItems(basketId);
basketItems.Count().ShouldBe(3);
await this.subject.ClearAllItems(basketId);
basketItems = await this.subject.GetBasketItems(basketId);
basketItems.Count().ShouldBe(0);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using ShopCartFramework.Api.Dtos;
using ShopCartFramework.Api.Interfaces;
using Newtonsoft.Json;
namespace ShopCartFramework.Api.Concretes
{
public sealed class ShopCartService : IShopCartService
{
private string baseUri;
public ShopCartService(string baseUri)
{
this.baseUri = baseUri;
}
public async Task<int> CreateBasket()
{
var endpoint = "api/basket";
var requestTask = this.GetClientResultAsJson(HttpMethod.Post, endpoint, null);
var basket = JsonConvert.DeserializeObject<ShoppingBasketResponse>(await requestTask);
return basket.Id;
}
public async Task<ICollection<ShoppingItem>> GetBasketItems(int basketId)
{
var endpoint = $"api/basket/{basketId}";
var requestTask = this.GetClientResultAsJson(HttpMethod.Get, endpoint, null);
var basket = JsonConvert.DeserializeObject<ShoppingBasketResponse>(await requestTask);
return basket.Items.ToArray();
}
public async Task<int> AddItemToBasket(AddShoppingItemRequest addItemRequest)
{
var endpoint = $"api/basket/{addItemRequest.BasketId}";
var httpContent = new StringContent(JsonConvert.SerializeObject(addItemRequest), Encoding.UTF8, "application/json");
var requestTask = this.GetClientResultAsJson(HttpMethod.Post, endpoint, httpContent);
var item = JsonConvert.DeserializeObject<ShoppingItem>(await requestTask);
return item.Id;
}
public async Task DeleteItemFromBasket(DeleteShoppingItemRequest deleteItemRequest)
{
var endpoint = $"api/basket/{deleteItemRequest.BasketId}";
var httpContent = new StringContent(JsonConvert.SerializeObject(deleteItemRequest), Encoding.UTF8, "application/json");
var requestTask = this.GetClientResultAsJson(HttpMethod.Delete, endpoint, httpContent);
await requestTask;
}
public async Task UpdateItemQuantity(UpdateShoppingItemQuantityRequest updateItemRequest)
{
var endpoint = $"api/basket/{updateItemRequest.BasketId}";
var httpContent = new StringContent(JsonConvert.SerializeObject(updateItemRequest), Encoding.UTF8, "application/json");
var requestTask = this.GetClientResultAsJson(HttpMethod.Patch, endpoint, httpContent);
await requestTask;
}
public async Task ClearAllItems(int basketId)
{
var endpoint = $"api/basket/{basketId}/items";
var requestTask = this.GetClientResultAsJson(HttpMethod.Delete, endpoint, null);
await requestTask;
}
private async Task<string> GetClientResultAsJson(HttpMethod method, string endpoint, HttpContent body)
{
var httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(this.baseUri);
var request = new HttpRequestMessage(method, endpoint);
request.Content = body;
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
}<file_sep>using ShopCartFramework.Api.Dtos;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ShopCartFramework.Api.Interfaces
{
public interface IShopCartService
{
Task<int> CreateBasket();
Task<ICollection<ShoppingItem>> GetBasketItems(int basketId);
Task<int> AddItemToBasket(AddShoppingItemRequest addItemRequest);
Task DeleteItemFromBasket(DeleteShoppingItemRequest deleteItemRequest);
Task UpdateItemQuantity(UpdateShoppingItemQuantityRequest updateItemRequest);
Task ClearAllItems(int basketId);
}
}<file_sep>using Newtonsoft.Json;
namespace ShopCartFramework.Api.Dtos
{
public class AddShoppingItemRequest
{
public int BasketId { get; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
public AddShoppingItemRequest(int basketId)
{
this.BasketId = basketId;
}
}
}
<file_sep>using Newtonsoft.Json;
namespace ShopCartFramework.Api.Dtos
{
public class DeleteShoppingItemRequest
{
public int BasketId { get; }
[JsonProperty("id")]
public int ShoppingItemId { get; set; }
public DeleteShoppingItemRequest(int basketId)
{
this.BasketId = basketId;
}
}
}<file_sep>using Moq;
using NUnit.Framework;
using ShopCartFramework.Api.Dtos;
using ShopCartFramework.Api.Interfaces;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ShopCartFramework.Api.Tests
{
[TestFixture]
public sealed class ShoppingBasketTests
{
private ShoppingBasket subject;
private int? basketId;
private Mock<IShopCartService> mockShopCartService;
[SetUp]
public async Task SetUp()
{
this.basketId = 0;
this.mockShopCartService = new Mock<IShopCartService>();
this.mockShopCartService.Setup(x => x.CreateBasket()).Returns(Task.FromResult(this.basketId.Value));
ICollection<ShoppingItem> items = new List<ShoppingItem>();
this.mockShopCartService.Setup(x => x.GetBasketItems(this.basketId.Value)).Returns(Task.FromResult(items));
this.subject = new ShoppingBasket(this.mockShopCartService.Object);
await this.subject.CreateNewBasket();
}
[Test]
public async Task ShouldCallServiceToCreateBasket()
{
//setup & act
await this.subject.CreateNewBasket();
//assert
this.mockShopCartService.Verify(x => x.CreateBasket());
}
[Test]
public async Task ShouldCallServiceToAddItemToBasket()
{
//setup
var name = "Cheese";
var description = "Exceptional Cheese";
//act
await this.subject.AddShoppingItem(name, description);
//assert
this.mockShopCartService.Verify(x => x.AddItemToBasket(
It.Is<AddShoppingItemRequest>(p => p.BasketId == this.subject.Id
&& p.Name == name
&& p.Description == description)));
}
[Test]
public async Task ShouldCreateNewBasketIfAddItemCalledBeforeBasketCreated()
{
//setup & act
await this.subject.AddShoppingItem("name", "description");
//assert
this.mockShopCartService.Verify(x => x.CreateBasket());
}
[Test]
public async Task ShouldDeleteItemById()
{
//setup
var itemId = 12;
this.SetupServiceToReturnShoppingItem(new ShoppingItem { Id = itemId});
//act
await this.subject.DeleteShoppingItem(itemId);
//assert
this.mockShopCartService.Verify(x => x.DeleteItemFromBasket(
It.Is<DeleteShoppingItemRequest>(p => p.BasketId == this.subject.Id && p.ShoppingItemId == itemId)));
}
[Test]
public async Task DeleteByNameShouldDeleteUsingItemId()
{
//setup
var itemId = 942;
var itemName = "unwantedThing";
this.SetupServiceToReturnShoppingItem(new ShoppingItem { Id = itemId, Name = itemName });
//act
await this.subject.DeleteShoppingItem(itemName);
//assert
this.mockShopCartService.Verify(x => x.DeleteItemFromBasket
(It.Is<DeleteShoppingItemRequest>(p => p.BasketId == this.basketId && p.ShoppingItemId == itemId)));
}
[Test]
public async Task ShouldCheckItemExistsBeforeDelete()
{
//setup
var itemId = 13;
//act
await this.subject.DeleteShoppingItem(itemId);
//assert
this.mockShopCartService.Verify(x => x.GetBasketItems(this.subject.Id.Value));
this.mockShopCartService.Verify(x => x.DeleteItemFromBasket(It.IsAny<DeleteShoppingItemRequest>()), Times.Never);
}
[Test]
public async Task ShouldGetExistingBasketById()
{
//setup & act
await this.subject.GetExistingBasket(this.basketId.Value);
//assert
this.mockShopCartService.Verify(x => x.GetBasketItems(this.basketId.Value));
}
[Test]
public async Task ShouldClearAllItems()
{
//setup & act
await this.subject.ClearBasketItems();
//assert
this.mockShopCartService.Verify(x => x.ClearAllItems(this.basketId.Value));
}
[Test]
public async Task ShouldUpdateItemToNewQuantity()
{
//setup
int updateQuantity = 5;
string itemName = "programmersHandbook";
int itemId = 10;
this.SetupServiceToReturnShoppingItem(new ShoppingItem {Id = itemId, Name = itemName});
//act
await this.subject.UpdateItemQuantity(itemName, updateQuantity);
//assert
this.mockShopCartService.Verify(x =>
x.UpdateItemQuantity(It.Is<UpdateShoppingItemQuantityRequest>(p =>
p.ItemName == itemName && p.UpdatedQuantity == updateQuantity)));
}
[Test]
public async Task ShouldGetItemsFromService()
{
//setup
var basketId = 49;
this.mockShopCartService.Setup(x => x.CreateBasket()).Returns(Task.FromResult(basketId));
await this.subject.CreateNewBasket();
//act
await this.subject.GetShoppingItems();
//assert
this.mockShopCartService.Verify(x => x.GetBasketItems(basketId));
}
private void SetupServiceToReturnShoppingItem(ShoppingItem item)
{
ICollection<ShoppingItem> returnItems = new List<ShoppingItem>{item};
this.mockShopCartService.Setup(x => x.GetBasketItems(this.basketId.Value))
.Returns(Task.FromResult(returnItems));
}
}
} | 9a1ad52a2ab1b72acc5ba295753a7c64a48af4d2 | [
"Markdown",
"C#"
] | 10 | C# | DMOCoder/DMOC.ShopCartFramework | 692336ce7df950221e52d51c523d8bf13cb83f1e | 49e8ca02637290866fd5ce4ed6ee9b7ba3d7568c |
refs/heads/master | <repo_name>baiangali/ling-c-<file_sep>/database.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace zadacha1
{
class database
{
//public static database _dbInstance;
//private static Guid _guid;
//database() { }
//public List<string> subjects = new List<string>();
//public List<student> students { get; set; }
//public List<teacher> teachers { get; set; }
//public Guid Guid { get { return _guid; } }
//public static database GetInstance() {
// if (_dbInstance == null)
// {
// _dbInstance = new database();
// _guid = Guid.NewGuid();
// }
// return _dbInstance;
//}
}
}
<file_sep>/student.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace zadacha1
{
class Student:human
{
public List<string> subject { get; set; }
public Student()
{
subject = new List<string>();
}
}
}
<file_sep>/subject.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace zadacha1
{
class subject
{
public string Name { get; set; }
public string teacher { get; set; }
}
}
<file_sep>/Program.cs
using System;
using System.Linq;
using System.Collections.Generic;
namespace zadacha1
{
class Program
{
static void Main(string[] args)
{
database db = database.GetInstance();
List<Student> students = new List<Student>
{
new Student {Name="Том", subject = new List<string> {"Aнглийский", "Немецкий" }},
new Student {Name="Боб", subject = new List<string> {"Aнглийский", "Французский" }},
new Student {Name="Михаил", subject = new List<string> {"Aнглийский", "Испанский" }},
new Student {Name="Элис", subject= new List<string> {"Испанский", "Немецкий" }}
};
List<teacher> teachers = new List<teacher>
{
new teacher { Name = "Иван", subject = new List<string>{ "Aнглийский" } },
new teacher { Name = "Михаил", subject = new List<string>{ "Французский" } },
new teacher { Name = "Стефан", subject = new List<string>{ "Немецкий" } },
new teacher { Name = "Стивен", subject = new List<string>{ "Испанский" } }
};
var selectedAll = from stud in students
from sub in stud.subject
group sub by sub;
foreach (var student in selectedAll)
Console.WriteLine(student.Key + " " + student.Count() + "students");
Console.WriteLine("-----------------------------");
var selected = from x in (from s in students
from sub in s.subject
select new { sub, s.Name })
group x by x.sub;
foreach (var sub in selected)
{
Console.WriteLine(sub.Key);
foreach (var item in sub)
{
Console.WriteLine(" " + item.Name);
}
}
Console.WriteLine("-----------------------------");
var res = from t in (from t in teachers
from s in students
from st in s.subject
from st1 in t.subject
where st == st1
select new { tachname = t.Name, staname = s.Name, st2 = st })
group t by t.st2;
foreach (var i in res)
{
Console.WriteLine($"Subject : {i.Key}");
foreach (var item in i)
{
Console.WriteLine("Teacher name: " + item.tachname);
foreach (var item1 in i)
{
Console.WriteLine(" Student name: " + item1.staname);
}
}
}
Console.WriteLine("-----------------------------");
//var result = from s in students
// from tt in teachers
// from subc in s.subject
// group subc by s.subject into g
// select new
// {
// t = g.Key,
// c = g.Count(),
// u = from tt in g select tt
// };
//foreach (var item in result)
//{
// Console.WriteLine($"{item.t}{item.c}");
// foreach (teacher named in item.u)
// {
// Console.WriteLine(named.Name);
// }
//}
}
}
}
| 526dd11c9d33573135a7f69e9477ff062258bbd5 | [
"C#"
] | 4 | C# | baiangali/ling-c- | 62c0e336b8f03a800c159b31d1483a94ed3ad5ff | d45672d561870fccbd7ab7bfcc26aee99588e474 |
refs/heads/master | <file_sep>package easy.string;
public class LongestUncommonSubsequenceI521 {
public int findLUSlength(String a, String b) {
return a.equals(b)?-1:Math.max(a.length(),b.length());
}
}
<file_sep>package easy.hashtable;
public class FindtheDifference389 {
public static void main(String[] args) {
String s = "abcd";
String t = "abcde";
System.out.println(findTheDifference(s, t));
}
public static char findTheDifference(String s, String t) {
int res = 0, tres = 0;
for (int i = 0; i < s.length(); i++) {
res += (int)s.charAt(i);
}
for (int i = 0; i < t.length(); i++) {
tres += (int)t.charAt(i);
}
return (char)(tres-res);
}
}<file_sep>package easy.math;
public class SetMismatch645 {
public static void main(String[] args) {
int[] nums = { 1,1};
int[] is = findErrorNums(nums);
for (int i : is) {
System.out.print(i + "\t");
}
}
public static int[] findErrorNums(int[] nums) {
int[] res = new int[2];
for (int i : nums) {
if (nums[Math.abs(i) - 1] < 0)
res[0] = Math.abs(i);
else
nums[Math.abs(i) - 1] *= -1;
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0)
res[1] = i + 1;
}
return res;
}
public static int[] findErrorNums1(int[] nums) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
while (nums[i] - 1 != i && nums[nums[i] - 1] != nums[i]) {
swap(nums, i, nums[i] - 1);
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] - 1 != i) {
result[0] = nums[i];
result[1] = i + 1;
break;
}
}
return result;
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
<file_sep>package easy.array;
/**
*
* @author Administrator Suppose you have a long flowerbed in which some of the
* plots are planted and some are not. However, flowers cannot be
* planted in adjacent plots - they would compete for water and both
* would die.
*
* Given a flowerbed (represented as an array containing 0 and 1, where
* 0 means empty and 1 means not empty), and a number n, return if n new
* flowers can be planted in it without violating the
* no-adjacent-flowers rule.
*
*
* Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: True Example
* 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: False
*/
public class CanPlaceFlowers605 {
public static boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length && count < n; i++) {
if (flowerbed[i] == 0) {
// get next and prev flower bed slot values. If i lies at the
// ends the next and prev are considered as 0.
int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1];
int prev = (i == 0) ? 0 : flowerbed[i - 1];
if (next == 0 && prev == 0) {
flowerbed[i] = 1;
count++;
}
}
}
return count == n;
}
public static void main(String[] args) {
int[] flowerbed = { 1, 0, 0, 0, 0,0,0, 0, 1 };
boolean flowers = canPlaceFlowers1(flowerbed, 2);
System.out.println(flowers);
}
private static boolean canPlaceFlowers1(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length ; i++) {
if(flowerbed[i]==0){
int next = i==flowerbed.length-1?0:flowerbed[i+1];
int prev= i==0?0:flowerbed[i-1];
if(next ==0 && prev==0){
flowerbed[i]=1;
count++;
}
}
}
return n<=count;
}
public boolean canPlaceFlowers2(int[] flowerbed, int n) {
int count = 1;
int result = 0;
for(int i=0; i<flowerbed.length; i++) {
if(flowerbed[i] == 0) {
count++;
}else {
result += (count-1)/2;
count = 0;
}
}
if(count != 0) result += count/2;
return result>=n;
}
}
<file_sep>package easy.array;
/**
*
* @author Administrator Given a sorted array, remove the duplicates in place
* such that each element appear only once and return the new length.
*
* Do not allocate extra space for another array, you must do this in
* place with constant memory.
*
* For example, Given input array nums = [1,1,2],
*
* Your function should return length = 2, with the first two elements
* of nums being 1 and 2 respectively. It doesn't matter what you leave
* beyond the new length.
* 给定排序的数组中,移除所述重复的每一个元素都只出现一次并返回新的长度。不分配额外的空间用于另�?��数组,你必须这样做,在恒定的存储器�?例如�?
* 给定阵列输入比丘�?&bra;2&ket;,您函数应该返回长度�?,与第一元件的两个数值分别为1�?。这没有关系你离�?��后的新长度�?
*/
public class RemoveDuplicatesfromSortedArray26 {
private static final int[] A = {};
public static void main(String[] args) {
int removeDuplicates = removeDuplicates(A);
System.out.println(removeDuplicates);
}
public static int removeDuplicates(int[] A) {
try {
if (A.length == 0||A==null)
throw new Exception("输入数据错误");
} catch (Exception e) {
e.printStackTrace();
}
int j = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] != A[j])
A[++j] = A[i];
}
return ++j;
}
}
<file_sep>package easy.hashtable;
import java.util.HashMap;
import java.util.Map;
public class WordPattern290 {
public static boolean wordPattern1(String pattern, String str) {
String[] split = str.split(" ");
if (split.length != pattern.length())
return false;
Map map = new HashMap();
for (Integer i = 0; i < split.length; i++) {
// 上次放的值是上一个下标为i的值res,这一次返回的值就是res (key不同,但是value相同)
// map.put()返回上一次放入的value
if (map.put(pattern.charAt(i), i) != map.put(split[i], i))
return false;
}
return true;
}
}
<file_sep>package easy.math;
public class ArrangingCoins441 {
public static void main(String[] args) {
System.out.println(arrangeCoins(2147483647));
}
public static int arrangeCoins(int n) { return (int) ((Math.sqrt(1+8.0*n)-1)/2);}
}
<file_sep>package easy.array;
import java.util.Arrays;
public class MissingNumber268 {
public static void main(String[] args) {
/*int[] num = { 0, 3, 2,1,5 };
System.out.println(missingNumber1(num));*/
int a=6^2;
System.out.println(a);
}
public static int missingNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if((nums[i]+1)!=nums[i+1])
return nums[i]+1;
}
return 0;
}
public static int missingNumber1(int[] nums) {
int xor = 0, i = 0;
for (i = 0; i < nums.length; i++) {
xor = xor ^ i ^ nums[i];
}
return xor ^ i;
}
}<file_sep>package easy.array;
/**
* Image Smoother ?????
*
* @author LQL
* @create 2017-09-21 21:59
**/
public class ImageSmoother661 {
private static final int[][] M = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
public static void main(String[] args) {
int[][] ints = imageSmoother(M);
for (int[] intss : ints
) {
for (int res : intss
) {
System.out.print(res + "\t");
}
System.out.println();
}
}
public static int[][] imageSmoother(int[][] M) {
if (M == null) return null;
int rows = M.length;
if (rows == 0) return new int[0][];
int cols = M[0].length;
int result[][] = new int[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int count = 0;
int sum = 0;
for (int incR : new int[]{-1, 0, 1}) {
for (int incC : new int[]{-1, 0, 1}) {
if (isValid(row + incR, col + incC, rows, cols)) {
count++;
sum += M[row + incR][col + incC];
}
}
}
result[row][col] = sum / count;
}
}
return result;
}
private static boolean isValid(int x, int y, int rows, int cols) {
return x >= 0 && x < rows && y >= 0 && y < cols;
}
}
<file_sep>package easy.stack;
import java.util.LinkedList;
public class ImplementStackusingQueues225 {
LinkedList<Integer> queue;
public ImplementStackusingQueues225() {
this.queue = new LinkedList<>();
}
public void push(int x){
queue.add(x);
for (int i = 0; i < queue.size()-1; i++) {
queue.add(queue.poll());
}
}
public int pop(){
return queue.poll();
}
public int top(){
return queue.peek();
}
public boolean empty(){
return queue.isEmpty();
}
}
<file_sep>package easy.twopointers;
public class ReverseString344 {
public static void main(String[] args) {
System.out.println(reverseString("hello"));
}
public static String reverseString(String s) {
char[] charArray = s.toCharArray();
int start = 0, end = charArray.length - 1;
while (end > start) {
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;
end--;
start++;
}
return new String(charArray);
}
}
<file_sep>package easy.twopointers;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ReverseVowelsofaString345 {
public String reverseVowels(String s) {
Set<Character> set = new HashSet<>(
Arrays.asList(new Character[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }));
char[] cs = s.toCharArray();
for (int i = 0, j = cs.length - 1; i < j;) {
if (!set.contains(cs[i])) {
i++;
continue;
}
if (!set.contains(cs[j]))
{
j--;
continue;
}
char temp = cs[i];
cs[i] = cs[j];
cs[j] = temp;
i++;
j--;
}
return String.valueOf(cs);
}
}
<file_sep>package easy.array;
public class PlusOne66 {
public static void main(String[] args) {
int[] digits = { 9, 9, 9 };
int[] plusOne = plusOne1(digits);
for (int i = 0; i < plusOne.length; i++) {
System.out.print(plusOne[i] + "\t");
}
}
public static int[] plusOne1(int[] digits) {
int len = digits.length;
for (int i = len - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int nums[] = new int[len + 1];
nums[0] = 1;
return nums;
}
public static int[] plusOne(int[] digits) {
int n = digits.length;
for (int i = n - 1; i >= 0; i--) {
if (digits[i] < 9) {
// 2<9
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newNumber = new int[n + 1];
newNumber[0] = 1;
return newNumber;
}
}
<file_sep>package easy.math;
public class Sqrt_x69 {
public static void main(String[] args) {
System.out.println(sqrt(10));
}
public static int sqrt(int x) {
long r = x;
while(r*r>x){
r = (r+x/r)/2;
}
return (int) r;
}
}
<file_sep>package easy.math;
public class ValidPerfectSquare367 {
public static void main(String[] args) {
System.out.println(isPerfectSquare(99));
}
public static boolean isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
public static boolean isPerfectSquare1(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
}
<file_sep>package easy.array;
/**
* Maximum Average Subarray I
*
* @author LQL
* @create 2017-09-21 21:19
**/
public class MaximumAverageSubarrayI643 {
public static void main(String[] args) {
int[] nums = {1, 12, -5, -6, 50, 3};
System.out.println(findMaxAverage1(nums, 4));
}
public static double findMaxAverage(int[] nums, int k) {
double max = 0;
for (int i = 0; i < nums.length - k; i++) {
max = Math.max(nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3], max);
}
return max / k;
}
public static double findMaxAverage1(int[] nums, int k) {
double sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
double max = 0;
for (int i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k];
max = Math.max(max, sum);
}
return max / k;
}
}
<file_sep>package easy.array;
import java.util.Arrays;
/**
* test1
* @author Administrator Input: [1,4,3,2]
*
* Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 =
* min(1, 2) + min(3, 4).
*/
public class ArrayPartitionI561 {
public static void main(String[] args) {
int[] nums = { 1, 16, 9, 2 };
int sum = arrayPairSum(nums);
System.err.println(sum);
}
private static int arrayPairSum(int[] nums) {
Arrays.sort(nums);
//1 2 9 16
int result = 0 ;
for (int i = 0; i < nums.length; i+=2) {
result+=nums[i];
}
return result;
}
}
<file_sep>package com.zuochengyun;
import java.util.Stack;
public class Stack2 {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
Stack reverse = reverse(stack);
System.out.println(reverse.pop());
System.out.println(reverse.pop());
System.out.println(reverse.pop());
System.out.println(reverse.pop());
System.out.println(reverse.pop());
}
public static int getAmdRemoveLastElement(Stack<Integer> stack) {
Integer result = stack.pop();
if (stack.empty())
return result;
else {
int lastElement = getAmdRemoveLastElement(stack);
stack.push(result);
return lastElement;
}
}
public static int fact(int n){
int res = n+n;
if(n==1)
return 1;
else{
int a = fact(n-1)*n;
System.out.println(res);
return a;
}
}
public static Stack reverse(Stack<Integer> stack){
if(stack.empty()){
return null;
}
int push = getAmdRemoveLastElement(stack);
reverse(stack);
stack.push(push);
return stack;
}
}
<file_sep>package easy.math;
public class PowerofThree326 {
public static void main(String[] args) {
System.out.println(isPowerOfThree(1));
}
public static boolean isPowerOfThree(int n) {
return (Math.pow(3, 19)%n==0&&n>0);
}
}
<file_sep>package com.zuochengyun.video;
class GetUpMedian {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 4, 5, 6 };
System.out.println(getUpMedian(arr1, arr2));
}
public static int getUpMedian(int[] arr1, int[] arr2) {
int start1 = 0, end1 = arr1.length - 1, start2 = 0, end2 = arr2.length - 1, offset = 0, mid1 = 0, mid2 = 0;
while (end1 > start1) {
// 6->1 5->0
offset = (end1 - start1 + 1) & 1 ^ 1;
mid1 = (end1 + start1) / 2;
mid2 = (end2 + start2) / 2;
if (arr1[mid1] > arr2[mid2]) {
end1 = mid1;
start2 = mid2 + offset;
} else if (arr1[mid1] < arr2[mid2]) {
start1 = mid1 + offset;
end2 = mid2;
} else {
return arr1[mid1];
}
}
return Math.min(arr1[start1], arr2[start2]);
}
}
<file_sep>package com.zuochengyun;
import java.util.Stack;
public class SortStackByStack {
public static void sort(Stack<Integer> stack) {
Stack<Integer> help = new Stack<Integer>();
while (!stack.empty()) {
Integer pop = stack.pop();
while (!help.empty()&&pop>help.peek()) {
stack.push(help.pop());
}
help.push(pop);
}
while(!help.empty())
stack.push(help.pop());
}
}
<file_sep>package com.zuochengyun.catDog;
public class Cat extends Pet{
public Cat(String type) {
super(type);
}
}
<file_sep>package com.zuochengyun.Findthesizeofthelargestmatrix;
public class Findthesizeofthelargestmatrix26 {
}
<file_sep>package easy.string;
public class NumberofSegmentsinaString434 {
public static void main(String[] args) {
System.out.println(countSegments2("Hello, my name is John"));
}
public static int countSegments(String s) {
return s.trim().split(" ").length;
}
public static int countSegments2(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
res++;
return res;
}
public static int countSegments4(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))
res++;
}
return res;
}
}
<file_sep>package easy.linkedList;
public class MergeTwoSortedLists21 {
}
<file_sep>package easy.array;
public class LongestContinuousIncreasingSubsequence674 {
public static void main(String[] args) {
int[] a = { 1, 3, 5, 6, 4, 7,1,2,3,4,5,6 };
int ofLCIS = findLengthOfLCIS(a);
System.out.println(ofLCIS);
}
private static int findLengthOfLCIS(int[] a) {
int rs = 0, len = 0;
for (int i = 0; i < a.length; i++) {
if (i == 0 || a[i] <= a[i - 1]) {
len = 0;
}
rs = Math.max(rs, ++len);
}
return rs;
}
public static int findLengthOfLCIS1(int[] a) {
int mx = 0;
for (int i = 0, j = 0; j < a.length; i = (j == 0 || a[j] <= a[j - 1]) ? j
: i, mx = Math.max(mx, j - i + 1), j++) {
}
return mx;
}
}
<file_sep>package easy.array;
import java.util.Iterator;
import java.util.LinkedList;
public class RemoveElement27 {
public static void main(String[] args) {
int elem = 3;
int[] A = { 3, 2, 1, 2, 3, 2, 2, 3 };
System.out.println(removeElement(A, elem));
}
public static int removeElement(int[] A, int elem) {
int m = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] != elem) {
A[m] = A[i];
m++;
}
}
return m;
}
public static int removeElement1(int[] A, int elem) {
LinkedList<Integer> list = new LinkedList<Integer>();
if (A.length == 0)
return 0;
for (int i = 0; i < A.length; i++) {
list.add(A[i]);
}
Iterator<Integer> it = list.iterator();
try {
while (it.hasNext()) {
if (it.next() == elem) {
it.remove();
}
}
} catch (Exception e) {
System.out.println("No such element");
}
return list.size();
}
}
<file_sep>package easy.array;
public class MaximumSubarray53 {
private static final int[] A = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
public static void main(String[] args) {
int array = maxSubArray1(A);
System.out.println(array);
}
public static int maxSubArray(int[] A) {
int n = A.length;
int[] dp = new int[n];// dp[i] means the maximum subarray ending with
// A[i];
dp[0] = A[0];
int max = dp[0];
for (int i = 1; i < n; i++) {
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
public static int maxSubArray1(int[] A) {
int[] dp = new int[A.length];
dp[0] = A[0];
int max = 0;
for (int i = 1; i < A.length; i++) {
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
}<file_sep>package easy.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ContainsDuplicateII219 {
public static void main(String[] args) {
int k = 5;
int[] nums = { 5, 9, 4, 6, 3, 8, 4 };
System.out.println(containsNearbyDuplicate(nums, k));
}
public static boolean containsNearbyDuplicate(int[] nums, int k) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j] && j - i == k) {
return true;
}
}
}
return false;
}
public static int findMaxConsecutiveOnes(int[] nums) {
int pro = 0;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if(nums[i]==1){
list.add(++pro);
}
else {
pro=0;
}
}
Object[] array = list.toArray();
Arrays.sort(array);
return (int) array[array.length-1];
}
public static boolean containsNearbyDuplicate1(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (i > k)
set.remove(nums[i - k - 1]);
if (!set.add(nums[i]))
return true;
}
return false;
}
}
<file_sep>package easy.hashtable;
public class SingleNumber136 {
public static void main(String[] args) {
int[] nums = { 2, 2, 1 };
System.out.println(singleNumber1(nums));
}
// 错误
public static int singleNumber(int[] nums) {
if (nums.length == 1)
return nums[0];
for (int i = 0; i < nums.length - 1; i++) {
boolean flage = false;
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j])
flage = true;
}
if (!flage)
return nums[i];
}
return 0;
}
// 零亦或任何人数为任何数
public static int singleNumber1(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
}
<file_sep>package easy.array;
public class MergeSortedArray88 {
public static void main(String[] args) {
int n=4 ;
int[] nums1={1,2,3,5,6,8,0,0,0,0};
int[] nums2 = {4,5,8,9};
int m = 6;
int[] merge = merge(nums1, m, nums2 , n );
for (int i = 0; i < merge.length; i++) {
System.out.print(merge[i]+"\t");
}
}
public static int[] merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (i > -1 && j > -1) {
nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
}
while(j>-1){
nums1[k--]=nums2[j--];
}
return nums1;
}
}
<file_sep>package easy.array;
import java.util.Arrays;
public class MaximumProductofThreeNumbers628 {
public static void main(String[] args) {
int[] nums={9,2,4,3};
int maximumProduct = maximumProduct1(nums);
System.out.println(maximumProduct);
}
public static int maximumProduct(int[] nums) {
int product = 1;
for (int i : nums) {
if(i!=0)
product*=i;
}
return product;
}
public static int maximumProduct1(int[] a) {
Arrays.sort(a);
int len = a.length;
return Math.max(a[0] * a[1] * a[len-1], a[len-1] * a[len-2] * a[len-3]);
}
}
<file_sep>package easy.twopointers;
public class ValidPalindrome125 {
public boolean isPalindrome1(String s) {
if (s.isEmpty()) {
return true;
}
int head = 0, tail = s.length() - 1;
char cHead, cTail;
while (head <= tail) {
cHead = s.charAt(head);
cTail = s.charAt(tail);
if (!Character.isLetterOrDigit(cHead)) {
head++;
} else if (!Character.isLetterOrDigit(cTail)) {
tail--;
} else {
if (Character.toLowerCase(cHead) != Character
.toLowerCase(cTail)) {
return false;
}
head++;
tail--;
}
}
return true;
}
public boolean isPalindrome2(String s) {
if (s.isEmpty())
return true;
int end = s.length() - 1;
int start = 0;
char sChar, eChar;
while (end >= start) {
sChar = s.charAt(start);
eChar = s.charAt(end);
if (!Character.isLetterOrDigit(sChar)) {
start++;
} else if (!Character.isLetterOrDigit(eChar)) {
end--;
} else {
if (Character.toLowerCase(sChar) != Character
.toLowerCase(eChar)) {
return false;
}
start++;
end--;
}
}
return true;
}
}
| 592ea8b2abc37673d183d61c78f6e24c3cf30ed0 | [
"Java"
] | 33 | Java | Luoqinglong123/arithmetic | e728b5451c65d117f77f25bca3bdde7b11b40c26 | 22ff0b388ddddd78c912193e035f2f7ada0166c2 |
refs/heads/master | <repo_name>charmainpdrgl/Labs<file_sep>/Programming Lab #12/4NumberGuessing/4NumberGuessing/Guess 7 Numbers.cs
/***********************************************************
* Guess 7 Numbers
* Author: <NAME>
* Date: 31 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4NumberGuessing
{
class Program
{
static void Main()
{
Random rand = new Random();
int[] seven = new int[8];
for (int i = 0; i = 8; i++)
{
Console.WriteLine(marks[i]);
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #7/1RugbyGame/1RugbyGame/Rugby.cs
/***********************************************************
* Rugby Game Scoring
* Author: <NAME>
* Date: 14 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1RugbyGame
{
class Rugby
{
static void Main()
{
string team1, team2;
Random rand = new Random();
int score;
score = rand.Next(7);
Console.WriteLine("Team 1 has the ball!");
switch (score)
{
case 3:
Console.WriteLine("Team 1 has kicked a goal!");
break;
case 5:
Console.WriteLine("Team 1 has scored a try!");
break;
case 7:
Console.WriteLine("Team 1 has scored a try and converted!");
break;
default:
score = 0;
score = 1;
score = 2;
score = 4;
score = 6;
team1 = 0;
break;
}
Console.ReadLine();
}
}
}
<file_sep>/Deal or No Deal/Deal or No Deal/Program.cs
/********************************
* Deal or No Deal
* <NAME>
* Due: 19 November 2018
* ******************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Deal_or_No_Deal
{
class Program
{
static void Main()
{
Console.WriteLine("Welcome to the Deal or No Deal game.");
}
}
}
<file_sep>/Programming Lab #11/Animation Example 2/Animation Example 2/RocketLaunch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Animation_Example_2
{
class RocketLaunch
{
static void Main()
{
Console.WriteLine("/ \\ ");
Console.WriteLine("| |");
Console.WriteLine("| |");
Console.WriteLine("| |");
Thread.Sleep(500);
Console.WriteLine(" .");
Thread.Sleep(100);
Console.WriteLine(" .");
Thread.Sleep(100);
Console.WriteLine(" .");
Thread.Sleep(100);
Console.WriteLine(" .");
Thread.Sleep(100);
Console.WriteLine(" .");
Thread.Sleep(100);
Console.WriteLine(" .");
}
}
}
<file_sep>/Programming Lab #8/1Sauna Program/1Sauna Program/Sauna.cs
/***********************************************************
* The Sauna Program
* Author: <NAME>
* Date: 17 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1Sauna_Program
{
class Sauna
{
static void Main()
{
string t;
int count = 1;
Random rand = new Random();
double tempInc, temp;
Console.WriteLine("What is your temp?: ");
t = Console.ReadLine();
temp = Convert.ToDouble(t);
while (temp <= 38)
{
tempInc = rand.NextDouble();
temp = temp + tempInc;
count = count + 1;
Console.WriteLine("You have been in the sauna {0} minutes. Your temp is {1:###.##}", count, temp);
}
Console.WriteLine("You are too hot for the sauna!");
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #2/2addingNumbers/2addingNumbers/addingNumbers.cs
/**********************************************************
* Asking user for 2 numbers and adding them together
* Author: <NAME>
* Date: 27 July 2018
* ********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2addingNumbers
{
class addingNumbers
{
static void Main()
{
int num1, num2, sum;
string name, answer2, answer1;
Console.Write("What is your name? ");
name = Console.ReadLine();
Console.Write("Choose any number ");
answer1 = Console.ReadLine();
num1 = Convert.ToInt32(answer1);
Console.Write("Choose another number ");
answer2 = Console.ReadLine();
num2 = Convert.ToInt32(answer2);
sum = num1 + num2;
Console.WriteLine("The sum of both number you picked is " + sum);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #9/2Guessing Game/2Guessing Game/Guess.cs
/***********************************************************
* Guessing Game Part 1 & 2
* Author: <NAME>
* Date: 21 August 2018
* Programming 1
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2Guessing_Game
{
class Program
{
static void Main()
{
int guess, num = 1, secret, attempt = 0;
string temp;
Random rand = new Random();
Console.WriteLine("This is a Guessing Game");
Console.WriteLine("You will guess the number.");
Console.WriteLine("");
secret = rand.Next(101);
do
{
Console.WriteLine("Please guess a number between 1 to 100: ");
temp = Console.ReadLine();
guess = Convert.ToInt32(temp);
num = num + 1;
Console.WriteLine("");
if (((guess < secret) || (guess > secret) || (guess == secret)))
{
if (guess < secret)
{
Console.WriteLine("Clue: You're guess is too low.");
attempt = attempt + 1;
}
else
{
Console.WriteLine("Clue: You're guess is too high.");
attempt = attempt + 1;
}
}
else
{
Console.WriteLine("You have guessed the number correctly!!!");
attempt = attempt + 1;
Console.WriteLine("You have attempted {0} times!", attempt);
}
} while (num < 7);
if (num < 7)
{
Console.WriteLine("You have attempted to guess way too many times. You need a more systematic approach to your number guessing...");
attempt = attempt + 1;
}
else
{
Console.WriteLine("You have attempted to guess way too many times. You need a more systematic approach to your number guessing...");
Console.WriteLine("Your total attempts are: {0}", attempt);
Console.WriteLine("Better luck next time.");
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #4/5ExchangeRatesProgram/5ExchangeRatesProgram/Exchange Rate.cs
/***********************************************************
* Exchange Rates Program
* Author: <NAME>
* Date 1 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5ExchangeRatesProgram
{
class Program
{
static void Main()
{
const double AUD = 0.8085, USD = 0.8272, Pound = 0.5457, Yen = 76.23, Euro = 0.6297;
string temp;
double NZD, ToAUD, ToUSD, ToPound, ToYen, ToEuro;
Console.Write("Enter an amount in NZD: ");
temp = Console.ReadLine();
NZD = Convert.ToDouble(temp);
ToAUD = NZD / AUD;
ToUSD = NZD / USD;
ToPound = NZD / Pound;
ToYen = NZD / Yen;
ToEuro = NZD / Euro;
Console.WriteLine("The NZD Dollars you entered is converted to: ");
Console.WriteLine("Australian Dollars: {0:c}", ToAUD);
Console.WriteLine("US Dollars: {0:c}", ToUSD);
Console.WriteLine("Pound Sterling: ₤{0}", ToPound);
Console.WriteLine("Japanese Yen: ¥{0}", ToYen);
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Euro: €{0}", ToEuro);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #4/1MilesKilometresConversion/1MilesKilometresConversion/Miles to Kilometres.cs
/***********************************************************
* Miles and Kilometres Conversion
* Author: <NAME>
* Date: 3 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1MilesKilometresConversion
{
class Program
{
static void Main()
{
const double FACTOR = 1.609344;
string temp;
double miles, kilometres;
Console.Write("Enter a number of Miles: ");
temp = Console.ReadLine();
miles = Convert.ToDouble(temp);
kilometres = miles * FACTOR;
Console.WriteLine("Your entered Miles is converted to Kilometres: {0:D2}", kilometres);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #10/NotesExample/NotesExample/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NotesExample
{
class Program
{
static void Main(string[] args)
{
int i;
Console.WriteLine("Counting Up");
for (i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("Counting Down");
for (i = 10; i > 0; i--)
{
Console.WriteLine(i);
}
Console.WriteLine("for loops with chars");
for (char j = 'a'; j < 'g'; j++)
{
Console.WriteLine(j);
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #3/6DaysandHours/6DaysandHours/DaysHours.cs
/***********************************************************
* Days and Hours
* Author: <NAME>
* Date: 31 July 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _6DaysandHours
{
class DaysHours
{
static void Main()
{
string Hours;
int totalHours, hours, days;
Console.Write("Please enter a total number of hours: ");
Hours = Console.ReadLine();
totalHours = Convert.ToInt32(Hours);
days = totalHours / 24;
hours = totalHours % days;
Console.WriteLine("The total hours input is converted to hours and days which resulted to: {0:F0} days {1} hours", days, hours);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #10/5Dice Roll/5Dice Roll/Dice.cs
/***********************************************************
* Dice Roll
* Author: <NAME>
* Date: 31 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5Dice_Roll
{
class Dice
{
static void Main(string[] args)
{
Random rand = new Random();
int thrown, one = 1;
thrown = rand.Next(6001);
Console.WriteLine(thrown);
for (thrown = 1; thrown <= rand.Next(6000); thrown++)
{
while (thrown <= 6)
{
if (thrown == 1)
{
one = one + 1;
Console.WriteLine(one);
}
}
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #3/3PercentageIncrease/3PercentageIncrease/PercentIncrease.cs
/***********************************************************
* Percentage Increase
* Author: <NAME>
* Date: 31 July 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3PercentageIncrease
{
class PercentIncrease
{
static void Main()
{
String origPrice, newP;
double originalPrice, newPrice, percentageIncrease;
Console.Write("What's the original price of the item? ");
origPrice = Console.ReadLine();
originalPrice = Convert.ToDouble(origPrice);
Console.Write("What is the new price of the item? ");
newP = Console.ReadLine();
newPrice = Convert.ToDouble(newP);
percentageIncrease = (newPrice - originalPrice) / originalPrice;
Console.WriteLine("The percentage increase of the item is {0:P}.", percentageIncrease);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #2/1WhoAreYou/1WhoAreYou/WhoRU.cs
/**********************************************************
* Reading in data from a user
* Author: <NAME>
* Date: 1 February 2018
* ********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1WhoAreYou
{
class WhoRU
{
static void Main()
{
//declare all your variables
int dunedinTime;
string temp, name;
//ask for and read in the data
//note I used WRITE so that the user's answer appears on the same line
Console.Write("Who are you? ");
name = Console.ReadLine();
Console.Write("How many years have you lived in Dunedin for? ");
temp = Console.ReadLine();
//convert temp which is a string to an int
dunedinTime = Convert.ToInt32(temp);
//show that you have data in your variables by writing them to the screen
Console.WriteLine("Hello " + name);
Console.WriteLine(dunedinTime + " years is long enough to get a feel for the place");
Console.WriteLine("I hope you like it ");
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #3/1 Milk Prices/1 Milk Prices/MilkPrices.cs
/***********************************************************
* Milk Prices
* Author: <NAME>
* Date: 31 July 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1_Milk_Prices
{
class MilkPrices
{
static void Main()
{
double m1, m2, m3, milkAverage;
string milk1, milk2, milk3;
int count;
Console.Write("What's the price of Milk 1? ");
milk1 = Console.ReadLine();
m1 = Convert.ToDouble(milk1);
Console.Write("What's the price of Milk 2? ");
milk2 = Console.ReadLine();
m2 = Convert.ToDouble(milk2);
Console.Write("What's the price of Milk 3? ");
milk3 = Console.ReadLine();
m3 = Convert.ToDouble(milk3);
milkAverage = (m1 + m2 + m3) / (double)3;
Console.WriteLine("The average total of the 3 milk prices is {0:C}.", milkAverage);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #2/5AgeCalculator/5AgeCalculator/AgeCalc.cs
/***********************************************************
* Calculate how many days hours a person had lived for
* Author: <NAME>
* Date: 27 July 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5AgeCalculator
{
class AgeCalc
{
static void Main()
{
int number, hournum, daysnum, days, hours;
string age;
Console.Write("What is your age? ");
age = Console.ReadLine();
number = Convert.ToInt32(age);
days = 365;
daysnum = number * days;
hours = 8760;
hournum = number * hours;
Console.WriteLine("At your age right now, you have lived a total number of days of " + daysnum);
Console.WriteLine("At the same time, you lived a total number of hours of " + hournum);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #6/1AscendingNumbers/1AscendingNumbers/AscDesc.cs
/*******************************************************
* Ascending or Descending Numbers
* Author: <NAME>
* Date: 10 August 2018
* *****************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1AscendingNumbers
{
class AscDesc
{
static void Main()
{
string temp;
Random rand = new Random();
int num1, num2, num3;
num1 = rand.Next(10);
num2 = rand.Next(10);
num3 = rand.Next(10);
if ((num1 > num2) > num3) || ((num1 == num2 ) > num3)
{
}
}
}
}
<file_sep>/Programming Lab #5/1Hoard It Banks/1Hoard It Banks/Hoard It Banks.cs
/*******************************************************
* Hoard-It Banks
* Author: <NAME>
* Date: 7 August 2018
* *****************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1Hoard_It_Banks
{
class Program
{
static void Main(string[] args)
{
int posBal, interestbal, balInt, balance;
double interest = 0.3;
Random rand = new Random();
balance = rand.Next(1001);
Convert.ToDouble(balance);
posBal = rand.Next(2);
if (posBal == 0)
{
interestbal = balance * interest;
balInt = balance + interestbal;
Console.WriteLine("You're balance with interest is now {0:C}: ", balInt);
}
else
{
balance = balance - 20;
Console.WriteLine("Warning: You're bank balance is negative. We have taken an overdraft fee of $20. No interest has been given.");
}
Console.ReadLine();
}
}
}
<file_sep>/Intro Lab 1/1/1/HelloWorld.cs
// This is traditionally the first program written.
/* Sample Program to illustrate C# syntax
* Author: <NAME>
* Date: 20 February 2018
* */
using System; //console definition
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1 // Name of Program
{
class HelloWorld // Solution explorer
{
static void Main()
{
Console.WriteLine("Hello World");
Console.WriteLine("");
Console.WriteLine(2.3456 + 1);
Console.Write("what goes\nup \nmust come \tdown\n");
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #4/Example/Example/Creating Constants.cs
/***********************************************************
* Creating Constants
* Author: <NAME>
* Date: 1 February 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
class Program
{
static void Main()
{
const double GST_FACTOR = 1.15;
double preGST, fullPrice;
string temp;
Console.Write("How much is the pre GST price: ");
temp = Console.ReadLine();
//Convert temp which is a string to a double
preGST = Convert.ToDouble(temp);
fullPrice = preGST * GST_FACTOR;
//Show final price and display it with the currency format
Console.WriteLine("The full GST inclusive price is {0:C}", fullPrice);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #7/3RPS part2/3RPS part2/Part2.cs
/***********************************************************
* Rock Paper Scissors PART 2
* Author: <NAME>
* Date: 14 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2RPS_part1
{
class Program
{
static void Main()
{
int comp1;
string user, comp2 = "";
Random rand = new Random();
Console.WriteLine("This is a game of ROCK PAPER SCISSORS! You VS Computer!!!");
Console.WriteLine("\n");
Console.WriteLine("ROCK, PAPER or SCISSORS???: ");
user = Console.ReadLine();
comp1 = rand.Next(3);
switch (comp1)
{
case 0:
comp2 = "ROCK";
Console.WriteLine("Computer picked ROCK");
break;
case 1:
comp2 = "PAPER";
Console.WriteLine("Computer picked PAPER");
break;
case 2:
comp2 = "SCISSORS";
Console.WriteLine("Computer picked SCISSORS");
break;
default:
Console.WriteLine("Default case");
break;
}
if (((user == "ROCK") && (comp2 == "SCISSOR") || (user == "SCISSORS") && (comp2 == "PAPER") || (user == "PAPER") && (comp2 == "ROCK")))
{
if (((user == "ROCK") && (comp2 == "SCISSOR") || (user == "SCISSORS") && (comp2 == "PAPER") || (user == "PAPER") && (comp2 == "ROCK")))
{
Console.WriteLine("You have won against the computer!!!");
}
else
{
Console.WriteLine("The computer has won against you!!!");
}
}
else
{
Console.WriteLine("It's a DRAW!");
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #6/4SoccerGame/4SoccerGame/SoccerScore.cs
/***********************************************************
* Soccer Game Scoring
* Author: <NAME>
* Date: 10 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4SoccerGame
{
class Program
{
static void Main()
{
Random rand = new Random();
int team1, team2;
Console.WriteLine("Soccer Game Team 1 VS Team 2");
team1 = rand.Next(10);
team2 = rand.Next(10);
Console.WriteLine("Team 1 scores {0}", team1);
Console.WriteLine("Team 2 scores {0}", team2);
{
if (team2 < team1)
{
Console.WriteLine("Congratulations! Team 1 has WON!!!");
Console.WriteLine("Unfortunately, Team 2 has LOST. Better Luck next time!");
}
else
{
Console.WriteLine("Congratulations! Team 2 has WON!!!");
Console.WriteLine("Unfortunatley, Team 1 has LOST. Better Luck next time!");
}
}
if (team1 == team2)
Console.WriteLine("Both Teams has the same score! It's a DRAW!!!");
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #8/4ChaseProgram/4ChaseProgram/Chase.cs
/***********************************************************
* The Chase Program
* Author: <NAME>
* Date: 17 August 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _4ChaseProgram
{
class Chase
{
static void Main()
{
Random rand = new Random();
int surferDFS, sharkDFS, shark;
surferDFS = rand.Next(31);
shark = rand.Next(11);
sharkDFS = surferDFS + shark;
Console.WriteLine("Surfer is {0} metres from shore.", surferDFS);
Console.WriteLine("Shark is {0} metres from surfer.", sharkDFS - surferDFS);
while ((surferDFS > 0) && (sharkDFS - surferDFS > 0))
{
surferDFS = surferDFS - rand.Next(6);
sharkDFS = sharkDFS - rand.Next(6);
Console.WriteLine("");
Console.WriteLine("Surfer is {0} metres from shore.", surferDFS);
Console.WriteLine("Shark is {0} metres from surfer.", sharkDFS - surferDFS);
Thread.Sleep(3000);
}
if (surferDFS <= 0)
{
Console.WriteLine("Surfer made it to shore!!!");
}
else
{
Console.WriteLine("Shark had eaten the surfer!!!");
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #5/3Heads or Tails/3Heads or Tails/Game of Heads or Tails.cs
/*******************************************************
* Heads or Tails Game
* Author: <NAME>
* Date: 7 August 2018
* *****************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3Heads_or_Tails
{
class Program
{
static void Main()
{
string temp;
Random rand = new Random();
int computer;
char coin, h, t, guess;
Console.WriteLine("This is a game of Heads or Tails");
Console.WriteLine("Enter 'h' for Heads");
Console.Write("Or enter 't' for Tails: ");
temp = Console.ReadLine();
guess = Convert.ToChar(temp);
computer = rand.Next(2);
if (computer == 0)
{
coin = 'h';
Console.WriteLine("Computer tossed a Head");
}
else
{
coin = 't';
Console.WriteLine("Computer tossed a Tails");
}
if (coin == guess)
{
Console.WriteLine("You Won!!!");
}
else
{
Console.WriteLine("You have Lost!!! Better luck next time.");
}
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #11/Animation Examples/Animation Examples/PauseReDraw.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Animation_Examples
{
class PauseReDraw
{
static void Main(string[] args)
{
Console.WriteLine("|");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("/");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("-");
Thread.Sleep(500);
Console.Clear();
Console.WriteLine("\\");
Thread.Sleep(500);
Console.Clear();
}
}
}
<file_sep>/Programming Lab #24/4/4/Program.cs
/********************************************
* Bubble Struct using names.txt
* <NAME>
* 30 October 2018
* ******************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace _4
{
public struct names
{
public string firstName;
public string lastName;
}
class Program
{
static void Record(ref names[] clients)
{
{
int count = 0;
StreamReader sr = new StreamReader(@"H:\names.txt");
while (!sr.EndOfStream)
{
clients[count].firstName = sr.ReadLine();
clients[count].lastName = sr.ReadLine();
Console.WriteLine(clients);
count++;
}
sr.Close();
sort(ref clients);
}
}
static void Main()
{
names[] client = new names[21];
Record(ref client);
Console.ReadLine();
}
static void sort(ref names[] clients)
{
names[] clients = new names[21];
Record(ref clients);
for (int i = 0; i < clients.Length - 1; i++)
{
for (int pos = 0; pos < clients.Length - 1; pos++)
{
if (clients[pos + 1].firstName.CompareTo(clients[pos].firstName) < 0)
{
string temp = clients[pos + 1].firstName;
clients[pos + 1].firstName = clients[pos].firstName;
clients[pos].firstName = temp;
}
}
}
}
}
}
<file_sep>/Programming Lab #19/Word Jumble/Word Jumble/JumblingWords.cs
/******************************************************
* Word Jumble
* <NAME>
* 28 September 2018
* Programming 1
* ****************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Word_Jumble
{
class JumblingWords
{
static void Main(string[] args)
{
PickWord();
Console.ReadLine();
}
public static string PickWord()
{
string[] myWords = { "apple", "blueberries", "coconut", "grapefruit", "lemon", "mango", "papaya", "watermelon", "pomegranate", "pineapple" };
Random rand = new Random();
int pick = rand.Next(10);
return myWords[pick];
}
public static string JumbleWords(string myWords)
{
Random rand = new Random();
char[] characters = myWords.ToCharArray();
for (int c = 1; c <= myWords.Length; c++)
{
int num1 = rand.Next(10);
int num2 = rand.Next(myWords.Length);
char temp = characters[num1];
characters[num1] = characters[num2];
characters[num2] = temp;
}
string jumbled = new string(characters);
Console.WriteLine(jumbled);
return jumbled;
}
}
}
<file_sep>/Charmain/pedrc1/YourUserName/NoahProblem.cs
/**********************************************************
* The Noah Problem
* <NAME>
* 21 September 2018
* ********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YourUserName
{
class NoahProblem
{
static void Main(string[] args)
{
string inp, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; //Declaring string variables.
int days = mon, tues, wed, thurs, fri, sat, sun; //Declaring int variables.
Console.WriteLine("Enter the rain measurements for the days:"); //Asking for user input.
Console.WriteLine("Monday: ");
Monday = Console.ReadLine(); //Stores user input.
mon = Convert.ToInt32(Monday); //Converts string type to int.
Console.WriteLine("Tuesday: ");
Tuesday = Console.ReadLine();
tues = Convert.ToInt32(Tuesday);
Console.WriteLine("Wednesday: ");
Wednesday = Console.ReadLine();
wed = Convert.ToInt32(Wednesday);
Console.WriteLine("Thursday: ");
Thursday = Console.ReadLine();
thurs = Convert.ToInt32(Thursday);
Console.WriteLine("Friday: ");
Friday = Console.ReadLine();
fri = Convert.ToInt32(Friday);
Console.WriteLine("Saturday: ");
Saturday = Console.ReadLine();
sat = Convert.ToInt32(Saturday);
Console.WriteLine("Sunday: ");
Sunday = Console.ReadLine();
sun = Convert.ToInt32(Sunday);
if (days >= 0)
int rainfall = 0;
int[] days = { mon, tues, wed, thurs, fri, sat, sun };
foreach (int value in days)
{
rainfall = rainfall + value;
Console.WriteLine("Average rainfall per day over the period is " + rainfall);
}
Console.WriteLine("Type 9999 to end the program...");
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #3/4CelsiusToFahrenheit/4CelsiusToFahrenheit/CelsFah.cs
/***********************************************************
* Celsius to Fahrenheit
* Author: <NAME>
* Date: 31 July 2018
* *********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4CelsiusToFahrenheit
{
class CelsFah
{
static void Main()
{
int Celsius, Fahrenheit;
string cels;
Console.Write("Enter a temperature number: ");
cels = Console.ReadLine();
Celsius = Convert.ToInt32(cels);
Fahrenheit = (Celsius * 9) / 5 + 32;
Console.WriteLine("The temperature from Celsius to Fahrenheit is ", Fahrenheit);
Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #14/4/4/ey.cs
/*
* 'e' to 'y'
* <NAME>
* 2 November 2018
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4
{
class ey
{
static void Main()
{
Console.WriteLine("Please enter a sentence. Make sure the letter 'e' is included: ");
string sentence = Console.ReadLine();
}
}
}
<file_sep>/Programming Lab #14/1/1/Splitting.cs
/*
* Write a program that asks for a sentence then writes that sentences out one word per line
* Use the Split method to do this.
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1
{
class Splitting
{
static void Main()
{
Console.WriteLine("Please enter a phrase: ");
string phrase = Console.ReadLine();
string[] split = phrase.Split(' ');
Console.WriteLine("");
foreach (string item in split)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
| 3922816d6a19d76bb02720c757492017f716acb2 | [
"C#"
] | 31 | C# | charmainpdrgl/Labs | c31154ab260c1bca80e01c7b58a261d50c673e56 | c8643d0290cfd935d172c1f9c8a6623339e6bc3c |
refs/heads/master | <repo_name>Kannoken/Trash<file_sep>/mat.log/mlita.cpp
#include <stdio.h>
#include <iostream>
//#include <conio.h>
using namespace std;
struct arr{
int a,b;
} ;
int main()
{
int i,k,min1,min2,j,m;
bool s = true;
printf("Enter count of detail\n");
cin >> k;
struct arr mass[k];
struct arr ans[k];
int l=k;
printf("enter t\n");
for (i=0;i<k;i++)
{
printf("for a:\t");
cin >> mass[i].a;
cout << "for b:\t" ;
cin >> mass[i].b;
}
min1 = mass[0].a;
min2 = mass[0].b;
m=0;
int anss[k];
int p = k/2;
l=k;
for (i=0;i<p;i++)
{ m = 0;
for (j=0;j<k;j++)
{
if (min1>=mass[j].a)
{
min1=mass[j].a;
m=j;
}
}
ans[i]=mass[m];
anss[i]=m+1;
k=k-1;
for (j=m;j<k;j++)
{
mass[j]=mass[j+1];
}
min1=mass[0].a;
min2=mass[0].b;
m=0;
for (j=0;j<k;j++)
{
if (min2>=mass[j].b)
{
min2=mass[j].b;
m = j;
}
}
ans[l-i-1]=mass[m];
anss[l-i-1]=m+1;
k=k-1;
for (j=m;j<k;j++)
{
mass[j]=mass[j+1];
}
}
if ((l%2)!=0)
{
anss[p]=p;
ans[p]=mass[0];
}
for (i=0;i<l;i++)
{
printf("%d\n", anss[i]);
/* cout<< ans[i].a;
printf("\t");
cout<< ans[i].b;
printf("\n"); */
}
return 0;
}
<file_sep>/Шум и изменение глубины цвета/WindowsFormsApplication1/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Bitmap pic1, picorig;
Bitmap cpy;
Bitmap bmp1;
int y = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Файл BMP|*.bmp";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pic1 = new Bitmap(Image.FromFile(openFileDialog1.FileName));
// = picorig;
comboBox2.Enabled = true;
pictureBox1.Image = pic1;
bmp1 = new Bitmap(pictureBox1.Image);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBox2.SelectedIndex)
{
case 0: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format32bppArgb); break;
case 1: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format24bppRgb); break;
case 2: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format16bppArgb1555); break;
case 3: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format8bppIndexed); break;
case 4: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format4bppIndexed); break;
case 5: cpy = pic1.Clone(new Rectangle(0, 0, pic1.Width, pic1.Height), PixelFormat.Format1bppIndexed); break;
}
pictureBox1.Image = cpy;
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
int k = 0;
int w0 = -1;
int h0 = -1;
int w1 = 2;
int h1 = 2;
int h = bmp1.Height;
int w = bmp1.Width;
int Green = 0;
int Blue = 0;
int Red = 0;
for (int i = 0; i < w - 1; i++)
for (int j = 0; j < h - 1; j++)
{
if (bmp1.GetPixel(i, j) == Color.FromArgb(255, 0, 0, 0))
{
if (i == 0)
{
w0 = 0;
}
if (j == 0)
{
h0 = 0;
}
if (i == w-1)
{
w1 = 1;
}
if (j == h-1)
{
h1 = 1;
}
for (int n = w0; n < w1; n++)
for (int m = h0; m < h1; m++)
{
if ((i + n) != 0 && (j + m) != 0 && (bmp1.GetPixel(i + n, j + m) != Color.FromArgb(255, 0, 0, 0)))
{
Red += bmp1.GetPixel(i + n, j + m).R;
Green += bmp1.GetPixel(i + n, j + m).G;
Blue += bmp1.GetPixel(i + n, j + m).B;
k++;
}
}
w0 = -1;
h0 = -1;
w1 = 2;
h1 = 2;
if (k != 0)
{
Red /= k;
Green /= k;
Blue /= k;
bmp1.SetPixel(i, j, Color.FromArgb(255, Red, Green, Blue));
}
}
k = Red = Green = Blue = 0;
}
pictureBox1.Image = bmp1;
}
private void button3_Click(object sender, EventArgs e)
{
int h = pic1.Height;
int w = pic1.Width;
int x = h*w/100 * 30;
Random r = new Random();
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++)
{
int n = r.Next(0, h*w);
if (n < x)
bmp1.SetPixel(i, j, Color.FromArgb(255, 0, 0, 0));
}
pictureBox1.Image = bmp1;
}
}
}
<file_sep>/list/labb.cpp
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>
#include <cstring>
using namespace std;
struct Node
{
char str[50];
Node *Next,*Pred;
};
Node *Head=NULL, *Tail=NULL;
void push(Node **pos, char *str)
{ Node *new_elem = new Node;
strcpy(new_elem->str,str);
if (Head==NULL)
{ new_elem->Pred=NULL;
Head = Tail = new_elem;
}
else
{
new_elem->Pred = Tail;
Tail->Next = new_elem;
Tail = new_elem;
}
}
char* pop(Node **poss)
{
Node *new_elem = new Node;
new_elem = *poss;
char *name;
strcpy(name,(*poss)->str);
*poss = (*poss)->Pred;
delete(new_elem);
return name;
}
bool IsEmpty(Node **poss)
{
if ((*poss)==NULL)
return true;
else return false;
}
int main()
{ int k;
char *name;
Node *pos = NULL;
char str[50];
FILE *f = fopen("s.txt","r");
while(!feof(f))
{
fscanf(f,"%s", &str);
push(&pos,str);
}
int c=0,m=0;
char* x= pop(&Tail);
while (!IsEmpty(&Tail))
{
name = pop(&Tail);
if (strcmp(name,x)==0)
{
c++;
}
}
printf("%d",c);
fclose(f);
return 0;
}
<file_sep>/hash/main.cpp
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
using namespace std;
struct list{
list *next;
int value;
};
const int key = 15;
list *mass[15];
list* addtohashtable(list* head,int value,int t)
{ list *p0,*p=NULL;
if ((p =(list*) malloc(sizeof(list))) == 0) {
fprintf (stderr, "out of memory (insertNode)\n");
exit(1);
}
p0 = head;
p =new list;
head = p;
p->value = value;
p->next=p0;
printf("%d %d\n",t, p->value);
return p;
}
int hash_f(int num)
{
return(num % key);
}
int found(int fn)
{
int k=1;
list* p = mass[hash_f(fn)];
while (fn!=p->value)
{
k++;
p = p -> next;
}
printf("Количество проб: %d\n",k );
return hash_f(fn);
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
int num,value;
int k,fn;
FILE * f= fopen("lab5.txt", "r");
while(!feof(f))
{
fscanf(f,"%d", &num);
k = hash_f(num);
mass[k] = addtohashtable(mass[k],num,k);
}
printf("Введите искомое число:\n");
scanf("%d", &fn);
printf("Номер ячейки искомого числа: %d\n", found(fn));
return 0;
}
<file_sep>/Фрактал/Фрактал/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Фрактал
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
}
Button btn1 = new Button();
TextBox Textl = new TextBox();
TextBox Texts = new TextBox();
TextBox Textp = new TextBox();
Label lbll = new Label();
Label lbls = new Label();
Label lblp = new Label();
private void Form1_Load(object sender, EventArgs e)
{
lbll.Top = 25;
lbll.Left = 50;
lbll.Text = "Высота ствола";
lbll.Width = 100;
this.Controls.Add(lbll);
this.Controls.Add(Textl);
Textl.Top = 50;
Textl.Left = 50;
Textl.Text = "100";
this.Controls.Add(lbls);
lbls.Width = 150;
lbls.Top = 75;
lbls.Left = 50;
lbls.Text = "Соотношение веток";
this.Controls.Add(Texts);
Texts.Top = 100;
Texts.Left = 50;
Texts.Text = "70";
this.Controls.Add(lblp);
lblp.Top = 125;
lblp.Left = 50;
lblp.Text = "Угол наклона ветви";
this.Controls.Add(Textp);
Textp.Top = 150;
Textp.Left = 50;
Textp.Text = "70";
this.Controls.Add(btn1);
btn1.Text = "Построить дерево с заданными параметрами";
btn1.Top = 200;
btn1.Left = 25;
btn1.Height = 50;
btn1.Width = 150;
pic.Size = this.Size;
bmp = new Bitmap(pic.Width, pic.Height);
g = Graphics.FromImage(bmp);
pic.Image = bmp;
btn1.Click += btn1_Click;
}
int x, y, l, s;
double p;
PictureBox pic = new PictureBox();
Bitmap bmp;
Graphics g;
Pen MyPen = new Pen(Color.Black);
Point x1y1 = new Point();
Point x2y2 = new Point();
void btn1_Click(object sender, EventArgs e)
{
try
{
g.Clear(this.BackColor);
pic.Image = bmp;
x = this.Width / 2 + 50;
y = this.Height - 50;
l = Convert.ToInt32(Textl.Text);
s = Convert.ToInt32(Texts.Text);
p = Convert.ToDouble(Textp.Text) * Math.PI / 180;
FracTree(x, y, Math.PI / 2, p, l, s);
// Form1.BackColor = Color.Black;
this.Controls.Add(pic);
}
catch (System.StackOverflowException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
public void FracTree(int x, int y, double a, double p, int l, int s)
{
if (l < 10)
return;
else
{
if (l < 25)
MyPen.Color = Color.Pink;
else
MyPen.Color = Color.Maroon;
Point XY = new Point(x, y);
MyPen.Width = l / 8;
l = l * s / 100;
int x1 = (int)(x +l * Math.Cos(a));
int y1 = (int)(y -l * Math.Sin(a));
x1y1.X = x1;
x1y1.Y = y1;
int x2 = x + (int)(l / 2 * Math.Cos(a));
int y2 = y - (int)(l / 2 * Math.Sin(a));
x2y2.X = x2;
x2y2.Y = y2;
g.DrawLine(MyPen, XY, x1y1);
FracTree(x1, y1, a - p, p, l, s);
FracTree(x1, y1, a + p, p, l, s);
// FracTree(x2, y2, a - p, p, l, s);
// FracTree(x2, y2, a + p, p, l, s);
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
}
}
}
<file_sep>/tree.cpp
#include <iostream>
#include <stdio.h>
#include <locale.h>
#include <Windows.h>
#include <conio.h>
using namespace std;
struct btree
{
int key;
btree *left, *right;
};
int maxl=0;
btree * tree=NULL;
void push(int a,btree **t)
{
if ((*t)==NULL)
{
(*t)=new btree;
(*t)->key=a;
(*t)->left=(*t)->right=NULL;
return;
}
if (a>(*t)->key) push(a,&(*t)->right);
else push(a,&(*t)->left);
}
void print (btree *t, int h)
{
if(t)
{
if (maxl<h)
maxl=h;
print(t -> right, h + 1);
for(int j = 0; j < h; j++)
printf(" ");
printf("%d", t -> key);
printf("\n");
print(t -> left, h + 1);
}
}
void Free(btree *t)
{
if (t->left)
{
Free(t->left);
}
if (t->right)
{
Free(t->right);
}
delete t;
t=NULL;
}
int main ()
{
setlocale(0,"");
SetConsoleCP (1251);
SetConsoleOutputCP (1251);
int n;
int s;
cout<<"Enter count of Leaf ";
cin>>n;
for (int i=0;i<n;i++)
{
cout<<"Enter count ";
scanf ("%d", &s);
push(s,&tree);
}
cout<<"Your tree\n";
print(tree,0);
printf("glubina %d",maxl);
Free(tree);
getch();
return 0;
}
| 615b7d6aa9b7df2d1e9ab5eb54b6c49035fa0825 | [
"C#",
"C++"
] | 6 | C++ | Kannoken/Trash | 7135eae6b12c1f6c46ff341a5d4d80d5d18a52b4 | 8235f1691bf4f7040b784f5ad8251ad0757af1be |
refs/heads/master | <repo_name>lfardo/anuncio<file_sep>/db_anuncio.sql
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 1192.168.127.12
-- Generation Time: Jul 05, 2017 at 07:36 PM
-- Server version: 10.1.24-MariaDB
-- PHP Version: 7.0.20
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
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 utf8mb4 */;
--
-- Database: `db_anuncio`
--
-- --------------------------------------------------------
--
-- Table structure for table `bairro`
--
CREATE TABLE `bairro` (
`id` int(11) NOT NULL,
`des_bairro` varchar(20) NOT NULL,
`friendly_url` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `cidade`
--
CREATE TABLE `cidade` (
`id` int(11) NOT NULL,
`des_cidade` varchar(20) NOT NULL,
`friendly_url` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `bairro`
--
ALTER TABLE `bairro`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `cidade`
--
ALTER TABLE `cidade`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `bairro`
--
ALTER TABLE `bairro`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `cidade`
--
ALTER TABLE `cidade`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;COMMIT;
/*!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 */;
| b6bf616bfe71f1932974d12909400aeaf0e8731c | [
"SQL"
] | 1 | SQL | lfardo/anuncio | 93ba80b15c0b44d6cdf6f22c51dd44c828b063ef | f76c838c5aab3b75ba94c572b45924f96cf922a9 |
refs/heads/master | <repo_name>Waffy21/intento2<file_sep>/freertos_W4.c
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
#include "fsm.h"
#include "stm32f0xx_hal.h"
/* USER CODE BEGIN Includes */
//sharedmoney = xSemaphoreCreateMutex(); /* Recurso compartido */
#define TEMP110_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7C2)) /* TS ADC raw data acquired at temperature of 110 °C */
#define TEMP30_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7B8)) /* TS ADC raw data acquired at temperature of 30 °C */
#define VDD_CALIB ((uint16_t) (330)) /* Necesario para calibrar la temperatura */
#define VDD_APPLI ((uint16_t) (300)) /* Necesario para calibrar la temperatura */
/* USER CODE END Includes */
/* Private variables ---------------------------------------------------------*/
#define CUP_TIME 250
#define COFFEE_TIME 3000
#define MILK_TIME 3000
#define RETURN_MONEY_TIME 5000
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
#define THRESHOLD_HIGH 40
#define THRESHOLD_LOW 30
TickType_t tim1, tim2;
static int dinero = 60;
static int coffee_signal = 0;
static int milk_signal = 0;
static int final_signal = 0;
volatile int tiempo = 0;
volatile int tiempoguardado;
unsigned ADC_temp; /* Valor captado por el ADC para calcular la temperatura */
int32_t temperature; /* Temperatura en ºC */
//static void timer_isr (union sigval arg) {timer = 1; }
static int button = 0;
static int button_pressed (fsm_t* this) {
if(dinero >= 50){
button = 1;
return button; /*se sirve el café*/
}
else {
button = 0; /*no hay suficiente dinero*/
}
return 0;
}
enum cofm_state {
COFM_WAITING,
COFM_CUP,
COFM_COFFEE,
COFM_MILK,
};
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
static int cup_finished (fsm_t* this) {return coffee_signal;}
static int coffee_finished (fsm_t* this) { return milk_signal;}
static int milk_finished (fsm_t* this) {return final_signal;}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)) /* End Of Conversion */
{
ADC_temp = HAL_ADC_GetValue(hadc); /* Valor a la entrada */
/* Calibramos la temperatura */
temperature = (((int32_t) ADC_temp * VDD_APPLI / VDD_CALIB) - (int32_t) *TEMP30_CAL_ADDR );
temperature = temperature * (int32_t)(110 - 30);
temperature = temperature / (int32_t)(*TEMP110_CAL_ADDR - *TEMP30_CAL_ADDR);
temperature = temperature + 30;
if (temperature > 35){ /* El umbral superior es de 35ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_SET); /* Umbral superado ---> Activamos LED */
}
if (temperature < 25){ /* El umbral inferior es de 25ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_RESET); /* Umbral superado ---> Activamos LED */
}
}
}
static void cup (fsm_t* this)
{
//timer_start (CUP_TIME);
coffee_signal = 1;
}
static void coffee (fsm_t* this)
{
// timer_start (COFFEE_TIME);
milk_signal = 1;
}
static void milk (fsm_t* this)
{
//digitalWrite (GPIO_COFFEE, LOW);
//digitalWrite (GPIO_MILK, HIGH);
//timer_start (MILK_TIME);
final_signal = 1;
}
static void finish (fsm_t* this)
{
}
static fsm_trans_t cofm[] = {
{ COFM_WAITING, button_pressed, COFM_CUP, cup },
{ COFM_CUP, cup_finished, COFM_COFFEE, coffee },
{ COFM_COFFEE, coffee_finished, COFM_MILK, milk },
{ COFM_MILK, milk_finished, COFM_WAITING, finish },
{-1, NULL, -1, NULL },
};
void StartDefaultTask(void const * argument)
{
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_SET);
for(;;)
{
}
}
void StartTask02(void const * argument)
{
for(;;)
{
// if(xSemaphoreTake(block,1000)){
// xSemaphoreGive(block);
//}
}
}
void StartTask03(void const * argument)
{
fsm_t* cofm_fsm = fsm_new (cofm); /*creamos maquina de estados de maquina de cafe*/
for(;;)
{
tim1 = xTaskGetTickCount();
fsm_fire (cofm_fsm); /*lanzamos maquina de cafe*/
tim2 = xTaskGetTickCount();
}
}
int tiempos(TickType_t a, TickType_t b){
// return ((b-a)*1000)/configTICK_RATE_HZ;
int t = ((b-a)*1000)/configTICK_RATE_HZ;
if (t >= tiempo){
tiempo = t;
}
return tiempo;
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/freertos_j.c
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
*
* Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
/* USER CODE BEGIN Includes */
#include "stm32f0xx_hal.h"
#include "cmsis_os.h"
/* USER CODE END Includes */
/* Variables -----------------------------------------------------------------*/
/* USER CODE BEGIN Variables */
#define TEMP110_CAL_ADDR ((uint16_t*)((uint32_t) 0x1FFFF7C2))
#define TEMP30_CAL_ADDR ((uint16_t*)((uint32_t) 0x1FFFF7B8))
#define VDD_CALIB ((uint16_t) (330))
#define VDD_APPLI ((uint16_t) (300))
ADC_HandleTypeDef hadc;
int32_t temperature;
//int32_t tempGv;
unsigned int tempGv;
volatile int flag_adc;
osThreadId myThreadID;
TickType_t tim1, tim2;
volatile int tiempo;
volatile int flag_time;
osThreadId myThreadID2;
/* USER CODE END Variables */
/* Function prototypes -------------------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
/* USER CODE END FunctionPrototypes */
/* Hook prototypes */
/* USER CODE BEGIN Application */
/* StartTask02 function */
void StartTask02(void const * argument)
{
/* USER CODE BEGIN StartTask02 */
myThreadID2 = osThreadGetId();
/* Infinite loop */
for(;;)
{
osDelay(5000);
// tim2 = xTaskGetTickCount();
// HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_9);
}
/* USER CODE END StartTask02 */
}
/* StartTask03 function */
void StartTask03(void const * argument)
{
/* USER CODE BEGIN StartTask03 */
myThreadID = osThreadGetId();
/* Infinite loop */
for(;;)
{
osDelay(1000);
tim1 = xTaskGetTickCount();
flag_adc = 1;
HAL_ADC_Start_IT(&hadc);
if(flag_adc){
osThreadSuspend(myThreadID);
}
tim2 = xTaskGetTickCount();
temperature = (((int32_t) tempGv * VDD_APPLI / VDD_CALIB) - (int32_t) *TEMP30_CAL_ADDR );
temperature = temperature * (int32_t)(110 - 30);
temperature = temperature / (int32_t)(*TEMP110_CAL_ADDR - *TEMP30_CAL_ADDR);
temperature = temperature + 30;
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_8);
// tiempo = xTaskGetTickCount()- tim1;
tiempo = tiempos(tim1, tim2);
}
/* USER CODE END StartTask03 */
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc){
tempGv = HAL_ADC_GetValue(hadc);
flag_adc = 0;
osThreadResume(myThreadID);
}
int tiempos(TickType_t a, TickType_t b){
return ((b-a)*1000)/configTICK_RATE_HZ;
}
/* USER CODE END Application */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/freertos_W3.c
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
*
* Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
#include "fsm.h"
#include "stm32f0xx_hal.h"
/* USER CODE BEGIN Includes */
//sharedmoney = xSemaphoreCreateMutex(); /* Recurso compartido */
extern xSemaphoreHandle block;
/* USER CODE END Includes */
/* Variables -----------------------------------------------------------------*/
osThreadId defaultTaskHandle;
osThreadId MonederoHandle;
osThreadId MCafeHandle;
/* USER CODE BEGIN Variables */
ADC_HandleTypeDef hadc;
/* USER CODE END Variables */
/* Function prototypes -------------------------------------------------------*/
void StartDefaultTask(void const * argument);
void StartTask02(void const * argument);
void StartTask03(void const * argument);
void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */
/* USER CODE BEGIN FunctionPrototypes */
/* USER CODE BEGIN Includes */
#define TEMP110_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7C2)) /* TS ADC raw data acquired at temperature of 110 °C */
#define TEMP30_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7B8)) /* TS ADC raw data acquired at temperature of 30 °C */
#define VDD_CALIB ((uint16_t) (330)) /* Necesario para calibrar la temperatura */
#define VDD_APPLI ((uint16_t) (300)) /* Necesario para calibrar la temperatura */
unsigned ADC_temp; /* Valor captado por el ADC para calcular la temperatura */
int32_t temperature; /* Temperatura en ºC */
/* USER CODE END Includes */
/* Private variables ---------------------------------------------------------*/
#define CUP_TIME 250
#define COFFEE_TIME 3000
#define MILK_TIME 3000
#define RETURN_MONEY_TIME 5000
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
#define THRESHOLD_HIGH 40
#define THRESHOLD_LOW 30
static int dinero = 0;
static int button = 0;
static int button_pressed (fsm_t* this) {
if(dinero >= 50){
return button; /*se sirve el café*/
}
if (dinero < 50) {
button = 0; /*no hay suficiente dinero*/
}
return 0;
}
static int timer = 0;
//static void timer_isr (union sigval arg) {timer = 1; }
/* USER CODE END PV */
enum cofm_state {
COFM_WAITING,
COFM_CUP,
COFM_COFFEE,
COFM_MILK,
};
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
static int timer_finished (fsm_t* this) { return timer; }
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)) /* End Of Conversion */
{
ADC_temp = HAL_ADC_GetValue(hadc); /* Valor a la entrada */
/* Calibramos la temperatura */
temperature = (((int32_t) ADC_temp * VDD_APPLI / VDD_CALIB) - (int32_t) *TEMP30_CAL_ADDR );
temperature = temperature * (int32_t)(110 - 30);
temperature = temperature / (int32_t)(*TEMP110_CAL_ADDR - *TEMP30_CAL_ADDR);
temperature = temperature + 30;
if (temperature > 35){ /* El umbral superior es de 35ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_SET); /* Umbral superado ---> Activamos LED */
}
if (temperature < 25){ /* El umbral inferior es de 25ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_RESET); /* Umbral superado ---> Activamos LED */
}
}
}
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
/* res = a - b */
void
timeval_sub (struct timeval *res, struct timeval *a, struct timeval *b)
{
res->tv_sec = a->tv_sec - b->tv_sec;
res->tv_usec = a->tv_usec - b->tv_usec;
if (res->tv_usec < 0) {
--res->tv_sec;
res->tv_usec += 1000000;
}
}
/* res = a + b */
void
timeval_add (struct timeval *res, struct timeval *a, struct timeval *b)
{
res->tv_sec = a->tv_sec + b->tv_sec
+ a->tv_usec / 1000000 + b->tv_usec / 1000000;
res->tv_usec = a->tv_usec % 1000000 + b->tv_usec % 1000000;
}
/* a < b */
int
timeval_less (struct timeval *a, struct timeval *b)
{
return (a->tv_sec < b->tv_sec) ||
((a->tv_sec == b->tv_sec) && (a->tv_usec < b->tv_usec));
}
/* wait until next_activation (absolute time) */
void delay_until (struct timeval* next_activation)
{
struct timeval now, timeout;
gettimeofday (&now, NULL);
timeval_sub (&timeout, next_activation, &now);
select (0, NULL, NULL, NULL, &timeout);
}
static struct timeval timer_endtime;
static void timer_start (int ms) {
struct timeval inc = { ms/1000, (ms % 1000) * 1000 };
gettimeofday (&timer_endtime, NULL);
timeval_add (&timer_endtime, &timer_endtime, &inc);
}
static void cup (fsm_t* this)
{
//dinero = dinero - 50; /*el cafe cuesta 50 centimos*/
timer_start (CUP_TIME);
//printf("Sirve vaso");
//printf(" ");
}
static void coffee (fsm_t* this)
{
timer_start (COFFEE_TIME);
//printf("Sirve cafe");
//printf(" ");
}
static void milk (fsm_t* this)
{
timer_start (MILK_TIME);
//printf("Sirve leche");
//printf(" ");
}
static void finish (fsm_t* this)
{
//printf("Termina");
//printf(" ");
//HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_SET); /* Umbral superado ---> Activamos LED */
}
static struct timeval tcofm_max;
int cmd_tiempos (char *arg)
{
long long tcofm_us = tcofm_max.tv_sec * 10000000LL + tcofm_max.tv_usec; /*ponemos LL para que no desborde*/
printf("cofm: %lld\n", tcofm_us);
return 0;
}
static fsm_trans_t cofm[] = {
{ COFM_WAITING, button_pressed, COFM_CUP, cup },
{ COFM_CUP, timer_finished, COFM_COFFEE, coffee },
{ COFM_COFFEE, timer_finished, COFM_MILK, milk },
{ COFM_MILK, timer_finished, COFM_WAITING, finish },
{-1, NULL, -1, NULL },
};
/* USER CODE END FunctionPrototypes */
/* Hook prototypes */
/* Init FreeRTOS */
void MX_FREERTOS_Init(void) {
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* USER CODE BEGIN RTOS_MUTEX */
/* add mutexes, ... */
/* USER CODE END RTOS_MUTEX */
/* USER CODE BEGIN RTOS_SEMAPHORES */
/* add semaphores, ... */
/* USER CODE END RTOS_SEMAPHORES */
/* USER CODE BEGIN RTOS_TIMERS */
/* start timers, add new ones, ... */
/* USER CODE END RTOS_TIMERS */
/* Create the thread(s) */
/* definition and creation of defaultTask */
osThreadDef(defaultTask, StartDefaultTask, osPriorityIdle, 0, 128);
defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);
/* definition and creation of Devolver */
osThreadDef(Monedero, StartTask02, osPriorityAboveNormal, 0, 128);
MonederoHandle = osThreadCreate(osThread(Monedero), NULL);
/* definition and creation of MeteMoneda */
osThreadDef(MaquinaCafe, StartTask03, osPriorityNormal, 0, 128);
MCafeHandle = osThreadCreate(osThread(MaquinaCafe), NULL);
/* USER CODE BEGIN RTOS_THREADS */
/* add threads, ... */
/* USER CODE END RTOS_THREADS */
/* USER CODE BEGIN RTOS_QUEUES */
/* add queues, ... */
/* USER CODE END RTOS_QUEUES */
}
/* StartDefaultTask function */
void StartDefaultTask(void const * argument)
{
/* USER CODE BEGIN StartDefaultTask */
/* Infinite loop */
for(;;)
{
HAL_ADC_Start_IT(&hadc);
osDelay(5000);
}
/* USER CODE END StartDefaultTask */
}
/* StartTask02 function */
/*Tarea con mayor prioridad*/
/*
* En este thread implementamos el monedero, que puede meter monedas o devolverlas
*
* */
void StartTask02(void const * argument)
{
/* USER CODE BEGIN StartTask02 */
/* Infinite loop */
for(;;)
{
if(xSemaphoreTake(block,1000)){
/*aqui pongo el metodo que modifica el recurso compartido */
xSemaphoreGive(block);
}
osDelay(1);
}
/* USER CODE END StartTask02 */
}
/* StartTask03 function */
/*Tarea con prioridad intermedia */
/*
* En este thread implementamos la maquina de cafe, que resta el coste del cafe al dinero del monedero
*/
void StartTask03(void const * argument)
{
/* USER CODE BEGIN StartTask03 */
/* Infinite loop */
fsm_t* cofm_fsm = fsm_new (cofm);
for(;;)
{
fsm_fire(cofm_fsm);
osDelay(5000);
}
/* USER CODE END StartTask03 */
}
/* USER CODE BEGIN Application */
/* USER CODE END Application */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/main.c
/**
******************************************************************************
* File Name : main.c
* Description : Main program body
******************************************************************************
*
* Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f0xx_hal.h"
#include "cmsis_os.h"
#include "adc.h"
#include "gpio.h"
#include "fsm.h"
#include <time.h>
/* USER CODE BEGIN Includes */
#define TEMP110_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7C2)) /* TS ADC raw data acquired at temperature of 110 °C */
#define TEMP30_CAL_ADDR ((uint16_t*) ((uint32_t) 0x1FFFF7B8)) /* TS ADC raw data acquired at temperature of 30 °C */
#define VDD_CALIB ((uint16_t) (330)) /* Necesario para calibrar la temperatura */
#define VDD_APPLI ((uint16_t) (300)) /* Necesario para calibrar la temperatura */
unsigned ADC_temp; /* Valor captado por el ADC para calcular la temperatura */
int32_t temperature; /* Temperatura en ºC */
/* USER CODE END Includes */
/* Private variables ---------------------------------------------------------*/
#define CUP_TIME 250
#define COFFEE_TIME 3000
#define MILK_TIME 3000
#define RETURN_MONEY_TIME 5000
/*
#define GPIO_COIN_5 7
#define GPIO_COIN_10 8
#define GPIO_COIN_20 9
#define GPIO_COIN_50 10
#define GPIO_COIN_100 11
#define GPIO_COIN_200 12
*/
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
#define THRESHOLD_HIGH 40
#define THRESHOLD_LOW 30
static int dinero = 0;
static int return_waiting = 0;
static int button = 0;
static void button_isr (void) { button = 1; }
static int cmd_button (char * arg) { button_isr(); return 0; } /*funcion para interprete*/
static int button_pressed (fsm_t* this) {
if(dinero >= 50){
return button; /*se sirve el café*/
}
if (dinero < 50) {
button = 0; /*no hay suficiente dinero*/
}
return 0;
}
static int timer = 0;
//static void timer_isr (union sigval arg) {timer = 1; }
static int button_return = 0;
static void button_return_isr (void) { button_return = 1; }
static int cmd_button_return (char * arg) { button_return_isr(); return 0; } /*funcion para interprete*/
static int button_pressed_return (fsm_t* this) { return button_return; }
static int return_to_wait (fsm_t* this) { return return_waiting; };
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(void);
void MX_FREERTOS_Init(void);
enum cofm_state {
COFM_WAITING,
COFM_CUP,
COFM_COFFEE,
COFM_MILK,
};
enum mofm_state {
MOFM_WAITING,
MOFM_RETURN,
};
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
static void return_money (fsm_t* this) /*evento llamado si se pulsa el botón de devolver dinero*/
{
//digitalWrite (GPIO_BUTTON_RETURN, HIGH);
timer_start (RETURN_MONEY_TIME);
return_waiting = 1; /*variable para ir al estado MOFM_RETURN*/
dinero = 0;
}
static void back_to_waiting (fsm_t* this)
{
return_waiting = 0; /*de aqui siempre se vuelve a MOFM_WAITING*/
button_return = 0;
}
static int timer_finished (fsm_t* this) { return timer; }
static fsm_trans_t mofm[] = {
{ MOFM_WAITING, button_pressed_return, MOFM_RETURN, return_money },
{ MOFM_RETURN, return_to_wait, MOFM_WAITING, back_to_waiting },
{-1, NULL, -1, NULL },
};
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)) /* End Of Conversion */
{
ADC_temp = HAL_ADC_GetValue(hadc); /* Valor a la entrada */
/* Calibramos la temperatura */
temperature = (((int32_t) ADC_temp * VDD_APPLI / VDD_CALIB) - (int32_t) *TEMP30_CAL_ADDR );
temperature = temperature * (int32_t)(110 - 30);
temperature = temperature / (int32_t)(*TEMP110_CAL_ADDR - *TEMP30_CAL_ADDR);
temperature = temperature + 30;
if (temperature > 35){ /* El umbral superior es de 35ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_SET); /* Umbral superado ---> Activamos LED */
}
if (temperature < 25){ /* El umbral inferior es de 25ºC */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_8, GPIO_PIN_RESET); /* Umbral superado ---> Activamos LED */
}
}
}
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
xSemaphoreHandle block = 0;
static void cup (fsm_t* this)
{
/*sacamos fuera la comprobacion de dinero
a la rutina de respuesta a la interrupc del boton de compra */
dinero = dinero - 50; /*el cafe cuesta 50 centimos*/
//digitalWrite (GPIO_LED, LOW);
//digitalWrite (GPIO_CUP, HIGH);
timer_start (CUP_TIME);
printf("Sirve vaso");
printf(" ");
}
static void coffee (fsm_t* this)
{
//digitalWrite (GPIO_CUP, LOW);
//digitalWrite (GPIO_COFFEE, HIGH);
timer_start (COFFEE_TIME);
printf("Sirve cafe");
printf(" ");
}
static void milk (fsm_t* this)
{
//digitalWrite (GPIO_COFFEE, LOW);
//digitalWrite (GPIO_MILK, HIGH);
timer_start (MILK_TIME);
printf("Sirve leche");
printf(" ");
}
static void finish (fsm_t* this)
{
//digitalWrite (GPIO_MILK, LOW);
//digitalWrite (GPIO_LED, HIGH);
//button = 0;
//button_return = 0;
printf("Termina");
printf(" ");
/*dinero = dinero - 50;*/
/*return dinero; */
}
static struct timeval tcofm_max, tmofm_max;
int cmd_tiempos (char *arg)
{
long long tcofm_us = tcofm_max.tv_sec * 10000000LL + tcofm_max.tv_usec; /*ponemos LL para que no desborde*/
long long tmofm_us = tmofm_max.tv_sec * 10000000LL + tmofm_max.tv_usec;
printf("cofm: %lld\n", tcofm_us);
printf("mofm: %lld\n", tmofm_us);
return 0;
}
static fsm_trans_t cofm[] = {
{ COFM_WAITING, button_pressed, COFM_CUP, cup },
{ COFM_CUP, timer_finished, COFM_COFFEE, coffee },
{ COFM_COFFEE, timer_finished, COFM_MILK, milk },
{ COFM_MILK, timer_finished, COFM_WAITING, finish },
{-1, NULL, -1, NULL },
};
/* USER CODE END 0 */
void* main_e2 (void *arg)
{
struct timeval clk_period = { 0, 250 * 1000 };
struct timeval next_activation;
struct timeval tcofm, tmofm;
fsm_t* cofm_fsm = fsm_new (cofm); /*creamos maquina de estados de maquina de cafe*/
fsm_t* mofm_fsm = fsm_new (mofm); /*creamos maquina de estados de monedero*/
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
gettimeofday (&next_activation, NULL);
fsm_fire (cofm_fsm); /*lanzamos maquina de cafe*/
gettimeofday (&tcofm, NULL);
fsm_fire (mofm_fsm); /*lanzamos monedero*/
gettimeofday (&tmofm, NULL);
timeval_sub (&tmofm, &tmofm, &tcofm);
timeval_sub (&tcofm, &tcofm, &next_activation);
timeval_max (&tmofm_max, &tmofm_max, &tmofm);
timeval_max (&tcofm_max, &tcofm_max, &tcofm);
}
/* USER CODE END 3 */
}
int main(void)
{
block = xSemaphoreCreateMutex(); /*Creamos el semaforo*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC_Init();
/* USER CODE BEGIN 2 */
//HAL_ADC_Start_IT(&hadc);
/* USER CODE END 2 */
/* Call init function for freertos objects (in freertos.c) */
MX_FREERTOS_Init();
/* Start scheduler */
osKernelStart();
/* We should never get here as control is now taken by the scheduler */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSI14;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.HSI14CalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL12;
RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
/**Configure the Systick interrupt time
*/
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
/**Configure the Systick
*/
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 3, 0);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief Period elapsed callback in non blocking mode
* @note This function is called when TIM1 interrupt took place, inside
* HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
* a global variable "uwTick" used as application time base.
* @param htim : TIM handle
* @retval None
*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
/* USER CODE BEGIN Callback 0 */
/* USER CODE END Callback 0 */
if (htim->Instance == TIM1) {
HAL_IncTick();
}
/* USER CODE BEGIN Callback 1 */
/* USER CODE END Callback 1 */
}
/**
* @brief This function is executed in case of error occurrence.
* @param None
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler */
/* User can add his own implementation to report the HAL error return state */
while(1)
{
}
/* USER CODE END Error_Handler */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/freertos_j3.c
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
*
* Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
/* USER CODE BEGIN Includes */
#include "stm32f0xx_hal.h"
#include "cmsis_os.h"
#include "fsm.h"
#include "wiringPi.h"
#include "time.h"
/* USER CODE END Includes */
/* Variables -----------------------------------------------------------------*/
/* USER CODE BEGIN Variables */
#define TEMP110_CAL_ADDR ((uint16_t*)((uint32_t) 0x1FFFF7C2))
#define TEMP30_CAL_ADDR ((uint16_t*)((uint32_t) 0x1FFFF7B8))
#define VDD_CALIB ((uint16_t) (330))
#define VDD_APPLI ((uint16_t) (300))
#define GPIO_BUTTON 2
#define GPIO_LED 3
#define GPIO_CUP 4
#define GPIO_COFFEE 5
#define GPIO_MILK 6
#define GPIO_BUTTON_RETURN 13
#define CUP_TIME 250
#define COFFEE_TIME 3000
#define MILK_TIME 3000
#define RETURN_MONEY_TIME 5000
ADC_HandleTypeDef hadc;
int32_t temperature;
//int32_t tempGv;
unsigned int tempGv;
volatile int flag_adc;
osThreadId myThreadID;
TickType_t tim1, tim2;
volatile int tiempo = 0;
volatile int tiempoguardado;
//static int dinero = 0;
//static int button_return = 0;
//static int return_waiting = 0;
static int dinero = 0;
static int button_return = 1;
static int return_waiting = 0;
static void return_money (fsm_t* this) /*evento llamado si se pulsa el botón de devolver dinero*/
{
digitalWrite (GPIO_BUTTON_RETURN, HIGH);
//timer_start (RETURN_MONEY_TIME);
// osDelay(5000);
return_waiting = 1; /*variable para ir al estado MOFM_RETURN*/
dinero = 0;
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_8);
// osDelay(5000);
}
static void back_to_waiting (fsm_t* this)
{
// return_waiting = 0; /*de aqui siempre se vuelve a MOFM_WAITING*/
// button_return = 0;
return_waiting = 0; /*de aqui siempre se vuelve a MOFM_WAITING*/
button_return = 1;
HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_9);
}
static int button_pressed_return (fsm_t* this) { return button_return; }
static int return_to_wait (fsm_t* this) { return return_waiting; };
enum mofm_state {
MOFM_WAITING,
MOFM_RETURN,
};
static fsm_trans_t mofm[] = {
{ MOFM_WAITING, button_pressed_return, MOFM_RETURN, return_money },
{ MOFM_RETURN, return_to_wait, MOFM_WAITING, back_to_waiting },
{-1, NULL, -1, NULL },
};
struct timeval next_activation;
struct timeval tcofm, tmofm;
/* USER CODE END Variables */
/* Function prototypes -------------------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
/* USER CODE END FunctionPrototypes */
/* Hook prototypes */
/* USER CODE BEGIN Application */
/* StartTask02 function */
void StartTask02(void const * argument)
{
/* USER CODE BEGIN StartTask02 */
//fsm_t* cofm_fsm = fsm_new (cofm); /*creamos maquina de estados de maquina de cafe*/
fsm_t* mofm_fsm = fsm_new (mofm); /*creamos maquina de estados de monedero*/
/* Infinite loop */
for(;;)
{
// osDelay(1000);
tim1 = xTaskGetTickCount();
// osDelay(1000);
fsm_fire (mofm_fsm);
tim2 = xTaskGetTickCount();
tiempoguardado = tiempos(tim1, tim2);
}
/* USER CODE END StartTask02 */
}
/* StartTask03 function */
void StartTask03(void const * argument)
{
/* USER CODE BEGIN StartTask03 */
myThreadID = osThreadGetId();
/* Infinite loop */
for(;;)
{
osDelay(1000);
flag_adc = 1;
HAL_ADC_Start_IT(&hadc);
if(flag_adc){
osThreadSuspend(myThreadID);
}
tim2 = xTaskGetTickCount();
temperature = (((int32_t) tempGv * VDD_APPLI / VDD_CALIB) - (int32_t) *TEMP30_CAL_ADDR );
temperature = temperature * (int32_t)(110 - 30);
temperature = temperature / (int32_t)(*TEMP110_CAL_ADDR - *TEMP30_CAL_ADDR);
temperature = temperature + 30;
// HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_9);
// tiempo = xTaskGetTickCount()- tim1;
// tiempo = tiempos(tim1, tim2);
}
/* USER CODE END StartTask03 */
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc){
tempGv = HAL_ADC_GetValue(hadc);
flag_adc = 0;
osThreadResume(myThreadID);
}
int tiempos(TickType_t a, TickType_t b){
// return ((b-a)*1000)/configTICK_RATE_HZ;
int t = ((b-a)*1000)/configTICK_RATE_HZ;
if (t >= tiempo){
tiempo = t;
}
return tiempo;
}
/* USER CODE END Application */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 572b1a9d0c034265fda9d5ce68efd03b9e4d1e3f | [
"C"
] | 5 | C | Waffy21/intento2 | f65e89366ce258c22dc3e038832c94ebaebc1782 | 695afd99bfaf9323a0c009ae3a4bab75d9ff9dfa |
refs/heads/master | <repo_name>SegnorAlberto/DataModelling-JSON-XML<file_sep>/JSON/JSON on Python/citibike.py
import json
import csv
sourceFile=open('citibike_data.json','r')
json_data=json.load(sourceFile)
# Execution time= when the data was requested
outputFile=open("ConvertedJson.csv","w")
outputWriter=csv.writer(outputFile)
print(json_data['executionTime'])
# print(json_data['stationBeanList'])
for station in json_data['stationBeanList']:
row_array=[]
row_array.append(json_data['executionTime'])
for attribute in station:
row_array.append(station[attribute])
outputWriter.writerow(row_array)
sourceFile.close()
outputFile.close()<file_sep>/XML/XML on PHP/Tutorial three/data.php
<?php
function C_element($e_name,$parent){
global $xml;
$node=$xml->createElement($e_name);
$parent->appendChild($node);
return $node;
}
function C_value($value,$parent){
global $xml;
$value=$xml->createTextNode($value);
$parent->appendChild($value);
return $value;
}
$s_id=$_POST['id'];
$s_name=$_POST['name'];
$xml=new DOMDOcument("1.0");
$xml->load("mydata.xml");
$root=$xml->getElementsByTagName("students")->item(0);
$student=C_element("student",$root);
$id=C_element("id",$student);
C_value("$s_id",$id);
$name=C_element("name",$student);
C_value("$s_name",$name);
$xml->formatOutput=true;
$xml->save("mydata.xml");
<file_sep>/JSON/JSON on PHP/Application using json/CRUD application using json/index.php
<?php
require 'users.php';
$users=getUsers();
include 'Partial/header.php';
?>
<div class="container">
<h1>CRUD with JSON: Small town citizens</h1>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Username</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Website</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user):?>
<tr>
<td><?php echo $user['name'] ?></td>
<td><?php echo $user['username'] ?></td>
<td><?php echo $user['email'] ?></td>
<td><?php echo $user['phone'] ?></td>
<td>
<a target="_blank" href="http://<?php echo $user['website'] ?>">
<?php echo $user['website'] ?></a>
</td>
<td>
<button class="btn btn-info" title="view"><a href="view.php?id=<?php echo $user['id'] ?>"> <i class="fas fa-edit"></i></a> </button>
<button class="btn btn-secondary" title="update"><a href="update.php?id=<?php echo $user['id'] ?>"><i class="fas fa-pen-alt"></i></a></button>
<button class="btn btn-danger" title="delete"><a href="delete.php?id=<?php echo $user['id'] ?>"><i class="fas fa-trash-alt"></i></a></button>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
<?php include 'Partial/footer.php';?>
<file_sep>/XML/XML on PHP/Tutorial one/config.php
<?php
// $conn=mysqli_connect("127.0.0.1","root","");
// mysqli_select_db('xmltuts',$conn);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xmltuts";
$db = "library";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully. <br>";
$con = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully. <br>";
?><file_sep>/JSON/JSON on PHP/Application using json/dogs application/St1/default.php
<?php
$dogs=json_decode(file_get_contents('dogs.json'));
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<title>Dogs</title>
</head>
<body>
<div class="container py-5">
<h1 class="display-2 text-center">Our Dogs</h1>
<div class="row">
<?php foreach ($dogs as $dog):?>
<?php $age=round($dog->age/12);
$weight=round($dog->weight/16);
if($dog->fur->sheds==true){
$sheds="Yes";
}else{
$sheds="No";
}
?>
<div class="col-12 col-md-4">
<div class="card mb-5">
<img class="card-img-top" src="<?php echo $dog->image;?>" alt="<?php echo $dog->name;?>">
<div class="card-body">
<h2 class="h3 mb-0"><?php echo ucfirst($dog->name);?> </h2>
<p> <?php echo ucfirst($dog->breed);?></p>
<hr class="my-4">
<ul class="list-unstyled">
<li>Age: <?php echo $age;?></li>
<li>Sex: <?php echo $dog->sex;?></li>
<li>Weight: <?php echo $weight;?> lbs.</li>
</ul>
<h3 class="h3">Fur</h3>
<ul class="list-unstyled">
<li>length: <?php echo $dog->fur->length;?></li>
<li>Color: <?php echo $dog->fur->color;?></li>
<li>Shed: <?php echo $sheds;?> lbs.</li>
</ul>
<h3 class="h4">Tricks</h3>
<ul class="list-unstyled">
<?php
$has_tricks=false;
foreach ($dog->tricks as $key => $value) {
if ($value==true) {
$has_tricks=true;
echo '<li>'.ucfirst($key).'</li>';
}
}
if ($has_tricks==false) {
echo '<li>None. Teach me!</li>';
}
?>
</ul>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
</body>
</html><file_sep>/XML/XML on PHP/Tutorial one/load_xml_file.php
<?php
$file='xml-file.xml';
// if(!$xmlfile=simplexml_load_file($file))
// exit('Failed to open'.$xmlfile);
// echo "First Name: " .$xmlfile->address->fname.'; '."Last Name ".$xmlfile->address->lname ."<br>";
// echo "Miss ".$xmlfile->address->fname." ".$xmlfile->address->lname." is our ".$xmlfile->address->jobtitle;
if(!$xmlfile=simplexml_load_file($file))
exit('Failed to open'.$xmlfile);
foreach ($xmlfile->children() as $xml) {
echo $xml->fname. " ".$xml->lname. " is our ".$xml->jobtitle."<br>";
}
?>
<file_sep>/XML/XML on PHP/Tutorial two/index.php
<?php
// require 'simplexml.class.php';
if(isset($_GET['action'])){
$products=simplexml_load_file('products.xml');
$id=$_GET['id'];
$index=0;
$i=0;
foreach ($products->product as $product) {
if($product['id']==$id){
$index=$i;
break;
}
$i++;
}
unset($products->product[$index]);
file_put_contents('products.xml', $products->asXML());
}
$products=simplexml_load_file('products.xml');
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link href="all.css" rel="stylesheet">
<script src="https://kit.fontawesome.com/f8b64b4b0f.js"></script>
<title>CRUD with XML</title>
</head>
<body>
<div class="container">
<h1>XML CRUD: List product information</h1>
<br><br>
<button class="btn btn-success text-right text-white"><a href="add.php">Add New product</a></button>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Options</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product):?>
<tr>
<th scope="row"><?php echo $product['id'];?></th>
<td><?php echo $product->name;?></td>
<td><?php echo $product->price;?></td>
<td>
<button type="button" class="btn btn-primary" title="Edit">
<a href="edit.php?id=<?php echo $product['id'];?>">
<i class="fas fa-edit"></i> </a></button>
<button href="index.php?action=delete&id=<?php echo $product['id'];?>" type="button" class="btn btn-danger" title="Delete"
onclick="return confirm('Are you sure ?')">
<i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</body>
</html>
<file_sep>/XML/XML on PHP/Tutorial two/edit.php
<?php
$products=simplexml_load_file('products.xml');
if(isset($_POST['submitSave'])){
foreach ($products->product as $product) {
if($product['id']==$_POST['id']){
$product->name=$_POST['name'];
$product->price=$_POST['price'];
break;
}
}
file_put_contents('products.xml',$products->asXML());
header('location: index.php');
}
foreach ($products->product as $product) {
if($product['id']==$_GET['id']){
$id=$product['id'];
$name=$product->name;
$price=$product->price;
break;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link href="all.css" rel="stylesheet">
<script src="https://kit.fontawesome.com/f8b64b4b0f.js"></script>
<title>CRUD with XML</title>
</head>
<body>
<div class="container">
<div class="card">
<form method="post">
<table class="table">
<div class="card-head">
<h3>Add New User</h3>
</div>
<div class="card-body">
<tbody>
<tr>
<td>Id</td>
<td><input type="text" name="id" value="<?php echo $id; ?>" readonly="yes"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="price" value="<?php echo $price; ?>"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submitSave" value="Save"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep>/XML/XML on Python/Part2.py
from xml.dom import minidom
xmldoc=minidom.parse("C:/Python/API/venv/XML/data/kml.kml")
kml=xmldoc.getElementsByTagName("kml")[0]
document=kml.getElementsByTagName("Document")[0]
placemarks=document.getElementsByTagName("Placemark")
for placemark in placemarks:
desc=placemark.getElementsByTagName("description")[0].firstChild.data
lst=desc.split(":")
population=int(lst[1].split("<")[0])
coords=placemark.getElementsByTagName("coordinates")[0].firstChild.data
lst2=coords.split(",")
longitude=float(lst2[0])
latitude=float(lst2[1])
cityName=placemark.getElementsByTagName("name")[0].firstChild.data
print(cityName+":", -longitude,latitude,population)
<file_sep>/XML/XML on Python/part4.py
from xml.etree import ElementTree
with open('data/names.xml') as f:
document=ElementTree.parse(f)
persons=document.findall("person/person")
for p in persons:
print('%s %s' % (p.findtext("first_name"),p.findtext("last_name")))
special=document.find("persons-special/person")
# print('%s %s' % (special.findtex("first_name"),special.findtex("last_name")))
all_persons=document.iterfind("persons/person")
for person in all_persons:
print('%s %s' % (person.findtext('first_name'),person.findtext("last_name")))
print('\n\n<?xml version="1.0"?>')
tag_iterator=document.iter()
for t in tag_iterator:
tag_name=t.tag
tag_text=t.text.strip()
tag_attrs=t.attrib
if len(tag_attrs)!=0:
print(tag_attrs['id'])
if tag_text=='':
if t.get('id') is not None:
print('<%s id="%s">' %(tag_name,t.get('id')))
else:
print('<%s>' %tag_name)
else:
print('<%s>%s</%s>'%(tag_name,tag_text,tag_name))
<file_sep>/XML/XML on Python/Part1.py
import os
import xml.etree.cElementTree as et
base_path=os.path.dirname(os.path.realpath(__file__))
xml_file=os.path.join(base_path,"data\\product_listing.xml")
tree=et.parse(xml_file)
root=tree.getroot()
for child in root:
print(child.tag, child.attrib)
for child in root:
for element in child:
print(element.tag,":", element.text)
new_product=et.SubElement(root,"product",attrib={"id":"4"})
new_prod_name=et.SubElement(new_product,"name")
new_prod_desc=et.SubElement(new_product,"description")
new_prod_cost=et.SubElement(new_product,"cost")
new_prod_ship=et.SubElement(new_product,"shipping")
new_prod_name.text="Python Pants"
new_prod_desc.text="These pants will surely help you code like crazy!"
new_prod_cost.text="39.90"
new_prod_ship.text="5.00"
tree.write(xml_file)
for child in root:
print(child.tag,child.attrib)<file_sep>/JSON/JSON on PHP/Application using json/dogs application/St1/indexdogs.php
<?php
$drinks= file_get_contents('drinks.json');
$drinks=json_decode($drinks);
// print_r($drinks)
foreach ($drinks as $drink) {
echo "<li>".$drink->name.'</li>';
}
$dogs= file_get_contents('dogs.json');
$dogs=json_decode($dogs,true);
echo "<pre>";
print_r($dogs);
echo "</pre>";
foreach ($dogs as $dog) {
$age=round($dog->age/12);
if($dog->fur->sheds==true){
$sheds='that sheds.';
}else{
$sheds='thst does not shed.';
}
echo "<li>".ucfirst($dog->name).' is a '.$age.' year old '.$dog->breed.' with '.
$dog->fur->length.' '.$dog->fur->color.' fur '.$sheds.'</li>';
}
?><file_sep>/Readme.md
This repos contain files on JSON and XML development as well as some application
made using XML file such as complete CRUD application using JSON file as storage
unit. Also an application used to create, read, edit and update an XML file.
<file_sep>/JSON/JSON on Python/Json3.py
import requests
# r=requests.get('https://www.trivago.co.za/south-africa-147/hotel')
# a=requests.get('https://www.porn.com/pictures/a-few-pics-of-a-teenager-pussy-5575709')
# c=requests.get('https://imgs.xkcd.com/comics/python.png')
#
# with open('vg.png','wb') as f:
# f.write(a.content)
# print(a.status_code)
# print(a.ok)
# print(a.headers)
payload={'page':2,'count':25}
payload1={'username':'corey','password':'<PASSWORD>'}
r=requests.get('http://httpbin.org/get',params=payload)
p=requests.post('http://httpbin.org/post',data=payload1)
ro=requests.get('http://httpbin.org/basic-auth/corey/testing',auth=('corey','testing'), timeout=3)
t=requests.get('https://httpbin.org/delay/2',timeout=3)
print(r.url)
print(p.text)
r_dict=p.json()
print(r_dict['form'])
print(ro)
print(t)<file_sep>/XML/XML on Python/Part3.py
from xml.dom import minidom
import os
from datetime import *
import xml.etree.cElementTree as et
xmldoc=minidom.parse('C:/Python/API/venv/XML/data/biking3-15-2012.tcx.xml')
tcd=xmldoc.getElementsByTagName("TrainingCenterDatabase")[0]
actElts=tcd.getElementsByTagName("Activities")[0]
activities=actElts.getElementsByTagName("Activity")
# print(tcd)
for activity in activities:
sport=activity.attributes["Sport"]
sportName=sport.value
idElement=activity.getElementsByTagName("Id")[0]
timeOfDay=idElement.firstChild.data
year=int(timeOfDay[0:4])
month=int(timeOfDay[5:7])
day=int(timeOfDay[8:10])
date=datetime(year,month,day)
print(sportName,date)
# print(activity)
<file_sep>/JSON/JSON on PHP/Application using json/CRUD application using json/users.php
<?php
function getUsers(){
return json_decode(file_get_contents('users.json'),true);
}
function getUsersById($id){
$users=getUsers();
foreach ($users as $user) {
if($user['id']==$id){
return $user;
}
}
return null;
}
function createUser($data){
}
function updateUser($data,$id){
$users=getUsers();
foreach ($users as $i => $user) {
if($user['id']==$id){
$users[$i]=array_merge($user,$data);
}
}
file_put_contents('users.json', json_encode($users));
// echo "<pre>";
// var_dump($users);
// echo "</pre>";
}
function deleteUser($id){
}<file_sep>/XML/XML on PHP/Tutorial one/getData.php
<?php
include_once('config.php');
$sql = "SELECT * FROM xmlobject";
$result = mysqli_query($conn, $sql);
// $sql=mysql_query("SELECT * FROM xmlobject");
// while($row=mysql_fetch_object($sql)){
// $resultset=$row->data;
// $info=simplexml_load_string($resultset);
// echo $info->content;
// }
// if ($result)
// {
// while ($row=mysqli_fetch_object($result))
// {
// $resultset=$row->data;
// $info=simplexml_load_string($resultset);
// echo $info->from." wrote to ".$info->to." to say: ".$info->content;
// }
// // Free result set
// mysqli_free_result($result);
// }
// mysqli_close($conn);
$query="SELECT * FROM books";
$res = mysqli_query($con, $query);
$xml= new DOMDocument("1.0");
$xml->formatOutput = true;
$books=$xml->createElement("books");
$xml->appendChild($books);
while($row=mysqli_fetch_array($res, MYSQLI_ASSOC)){
$book=$xml->createElement("book");
$books->appendChild($book);
$title=$xml->createElement("title",$row["name"]);
$book->appendChild($title);
$type=$xml->createElement("type",$row["type"]);
$book->appendChild($type);
$author=$xml->createElement("Author",$row["author"]);
$book->appendChild($author);
$price=$xml->createElement("Price",$row["price"]);
$book->appendChild($price);
$pages=$xml->createElement('pages',$row["pages"]);
$book->appendChild($pages);
}
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("mybooks.xml");
<file_sep>/XML/XML on PHP/Tutorial three/XML.php
<?php
$xml=new DomDocument("1.0","UTF-8");
$xml->formatOutput=true;
$xml->preserveWhiteSpace=false;
// The root element is company: first element(tag) of the file
$company=$xml->createElement("company");
$xml->appendChild($company);
// employee is a tag in company: childnode
$emp=$xml->createElement("employee");
$company->appendChild($emp);
$compnyName=$xml->createElement("Name");
$company->appendChild($compnyName);
$cName=$xml->createElement("Name","Pharmamedica");
$compnyName->appendChild($cName);
$cAdress=$xml->createElement("Address");
$compnyName->appendChild($cAdress);
$street=$xml->createElement("street","Midland Road");
$cAdress->appendChild($street);
$number=$xml->createElement("number",7896);
$cAdress->appendChild($number);
$postCode=$xml->createElement("postCode","M1E2H6" );
$cAdress->appendChild($postCode);
$city=$xml->createElement("city","Toronto");
$cAdress->appendChild($city);
$state=$xml->createElement("state", "Ontario");
$cAdress->appendChild($state);
$country=$xml->createElement("country","Canada");
$cAdress->appendChild($country);
$name=$xml->createElement("name","<NAME>");
$emp->appendChild($name);
$age=$xml->createElement("age",26);
$emp->appendChild($age);
$jobtitle=$xml->createElement("Jobtitle","React developer");
$emp->appendChild($jobtitle);
$dept=$xml->createElement("department","Technologies");
$emp->appendChild($dept);
$empAdd=$xml->createElement("address");
$emp->appendChild($empAdd);
$streetName=$xml->createElement("street", "Dixie Road");
$empAdd->appendChild($streetName);
$houseNumber=$xml->createElement("number",345);
$empAdd->appendChild($houseNumber);
$postCode=$xml->createElement("postCode","H4M1T8" );
$empAdd->appendChild($postCode);
$city=$xml->createElement("city","Toronto");
$empAdd->appendChild($city);
$state=$xml->createElement("state", "Ontario");
$empAdd->appendChild($state);
$country=$xml->createElement("country","Canada");
$empAdd->appendChild($country);
$name=$xml->createElement("name","<NAME>");
$emp->appendChild($name);
$age=$xml->createElement("age",56);
$emp->appendChild($age);
$jobtitle=$xml->createElement("Jobtitle","Vice president");
$emp->appendChild($jobtitle);
$dept=$xml->createElement("department","Finance");
$emp->appendChild($dept);
$empAdd=$xml->createElement("address");
$emp->appendChild($empAdd);
$streetName=$xml->createElement("street", "Don Valley");
$empAdd->appendChild($streetName);
$houseNumber=$xml->createElement("number",3450);
$empAdd->appendChild($houseNumber);
$postCode=$xml->createElement("postCode","T6U9H2" );
$empAdd->appendChild($postCode);
$city=$xml->createElement("city","Toronto");
$empAdd->appendChild($city);
$state=$xml->createElement("state", "Ontario");
$empAdd->appendChild($state);
$country=$xml->createElement("country","Canada");
$empAdd->appendChild($country);
echo "<xmp>".$xml->saveXML()."</xmp>";
?><file_sep>/JSON/JSON on Python/Json2.py
import json
from urllib.request import urlopen
# urlopen("https://finance.yahoo/webservice/v1/symbols/allcurrencies/quote?format=json") as response:
with urlopen("http://ergast.com/api/f1/2004/1/results.json") as response:
source=response.read()
# print(source)
df=json.loads(source)
print(json.dumps(df,indent=2))
# print(len(df['MRData']['RaceTable']['Races']['Results']['position']))
#
for item in df['MRData']['RaceTable']['Races']:
# season=item["season"]
# name =item["raceName"]
# circuit=item["Circuit"]["circuitName"]
# city=item["Circuit"]["Location"]["locality"]
# country = item["Circuit"]["Location"]["country"]
# rank=item['Results']["Driver"]["number"]
Nationality=item['Results']["Driver"]["nationality"]
print(season,name,city,country)<file_sep>/JSON/JSON on Python/citibike2.py
import json
import csv
import glob
outputFile=open("ConvertedJson2.csv","w")
outputWriter=csv.writer(outputFile)
folder_name="json_downloads"
for filename in glob.iglob(folder_name+"/*.json"):
sourceFile=open(filename,'r')
json_data=json.load(sourceFile)
for station in json_data['stationBeanList']:
row_array = []
row_array.append(json_data['executionTime'])
for attribute in station:
row_array.append(station[attribute])
outputWriter.writerow(row_array)
sourceFile.close()
outputFile.close()<file_sep>/XML/XML on PHP/Tutorial two/add.php
<?php
if(isset($_POST['submitSave'])){
$products=simplexml_load_file('products.xml');
$product=$products->addChild('product');
$product->addAttribute('id',$_POST['id']);
$product->addChild('name',$_POST['name']);
$product->addChild('price',$_POST['price']);
file_put_contents('products.xml',$products->asXML());
header('location: index.php');
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link href="all.css" rel="stylesheet">
<script src="https://kit.fontawesome.com/f8b64b4b0f.js"></script>
<title>CRUD with XML</title>
</head>
<body>
<div class="container">
<div class="card">
<div class="card-head">
<h3>Add New User</h3>
</div>
<div class="card-body">
<form method="POST" action="">
<div class="form-row">
<div class="form-group col-md-2">
<label for="id">ID</label>
<input type="text" class="form-control" name="id">
</div>
<div class="form-group col-md-4">
</div>
<div class="form-group col-md-6">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" >
</div>
<div class="form-group col-md-6">
<label for="price">Price</label>
<input type="text" class="form-control" name="price" >
</div>
<input type="submit" class="btn btn-primary" name="submitSave" value="Save">
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep>/JSON/JSON on Python/Mn_Quandl.py
import json
import requests
# Serialisation: From string to Json file
# using json.load syntax to read json files; i.e data in json format
data=json.load(open('MGEX_IH1.json','r'))
data1=json.load(open('HRWI.json','r'))
requests=requests.get("https://www.quandl.com/api/v3/datasets/CHRIS/MGEX_IH1.json?api_key=<KEY>")
data2=requests.text
data2=json.loads(data2)
# deserialization: from json to json ot from json to string
data_des=json.dump(data,open('mineapo.json','w'))
data_des1=json.dump(data1,open('mineapo1.json','w'))
data_des2=json.dumps(data2,indent=2)
print(type(data))
print(type(data1))
print(type(data2))
print(type(data_des))
print(type(data_des1))
print((type(data_des2)))
print(data_des2)<file_sep>/JSON/JSON on PHP/Application using json/dogs application/St1/index.php
<?php
$chars=json_decode(file_get_contents('https://swapi.co/api/people/'));
// echo "<pre>";
// print_r($chars);
// echo "</pre>";
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
<title>Dogs</title>
</head>
<body>
<div class="container py-5">
<div class="row">
<?php foreach ($chars->results as $char):?>
<div class="col-12 col-md-3">
<div class="card mb-4">
<div class="card-body">
<h2><?php echo $char->name;?></h2>
<p><?php echo $char->birth_year;?></p>
<hr>
<ul class="list-unstyled">
<?php
foreach ($char->films as $film) {
$the_film=json_decode(file_get_contents($film));
// echo "<pre>";
// print_r($the_film);
// echo "</pre>";
echo '<li class="my-2">'.$the_film->title.'</li>';
}
?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</body>
</html><file_sep>/JSON/JSON on Python/Json_Json_Module.py
import json
people_string='{ "people":[ { "name":"<NAME>", "Phone":"615-55-7164","emails":["<EMAIL>","<EMAIL>"], "has_license": false},{"name":"<NAME>","Phone": "560-555-5153","emails": null,"has_license":true}]}'
data=json.loads(people_string)
# print(data)
for person in data['people']:
print(person['name'])
del person['Phone']
new_string=json.dumps(data,indent=2, sort_keys=True)
print(new_string)
<file_sep>/XML/XML on PHP/Tutorial three/readxml.php
<?php
$xml=new DomDocument("1.0","UTF-8");
$xml->formatOutput=true;
$xml->preserveWhiteSpace=false;
$xml->load("company.xml");
if(!$xml){
$company=$xml->createElement("company");
$xml->appendChild($company);
}else{
$company=$xml->firstChild;
}
if(isset($_POST['submit']))
{
$fname=$_POST['name'];
$fage=$_POST['age'];
$fdept=$_POST['dept'];
$jobtitle=$_POST['jobtitle'];
$emp=$xml->createElement("employee");
$company->appendChild($emp);
$name=$xml->createElement("name",$fname);
$emp->appendChild($name);
$age=$xml->createElement("age",$fage);
$emp->appendChild($age);
$jobtitle=$xml->createElement("Jobtitle",$jobtitle);
$emp->appendChild($jobtitle);
$dept=$xml->createElement("department",$fdept);
$emp->appendChild($dept);
$empAdd=$xml->createElement("address");
$emp->appendChild($empAdd);
$streetName=$xml->createElement("street", "Mussband drive");
$empAdd->appendChild($streetName);
$houseNumber=$xml->createElement("number",7017);
$empAdd->appendChild($houseNumber);
$postCode=$xml->createElement("postCode","H4B1R4" );
$empAdd->appendChild($postCode);
$city=$xml->createElement("city","Toronto");
$empAdd->appendChild($city);
$state=$xml->createElement("state", "Ontario");
$empAdd->appendChild($state);
$country=$xml->createElement("country","Canada");
$empAdd->appendChild($country);
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("company.xml");
}
?><file_sep>/JSON/JSON on Python/Json4.py
import requests
import json
import time
r=requests.get('https://formulae.brew.sh/api/formula.json')
packages_json=r.json()
packages_str=json.dumps(packages_json,indent=2)
results=[]
t1=time.perf_counter()
for package in packages_json:
package_name=package['name']
package_desc=package['desc']
package_url=f'https://formulae.brew.sh/api/formula/{package_name}.json'
r1=requests.get(package_url)
package_json=r1.json()
# package_str=json.dumps(package_json,indent=2)
install_30=package_json['analytics']['install_on_request']['30d'][package_name]
install_90=package_json['analytics']['install_on_request']['90d'][package_name]
install_365=package_json['analytics']['install_on_request']['365d'][package_name]
data={
'name':package_name,
'desc':package_desc,
'analytics':{
'30d':install_30,
'90d':install_90,
'365d':install_365
}
}
results.append(data)
# time.sleep(r1.elapsed.total_seconds())
# break
print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')
# print(package_name,package_desc,install_30,install_90,install_365)
t2=time.perf_counter()
print(f'Finished in {t2-t1} seconds')
with open('package_info.json','w') as f:
json.dump(results,f,indent=2)
print(results)
<file_sep>/JSON/JSON on PHP/Application using json/CRUD application using json/update.php
<?php
include 'Partial/header.php';
require 'users.php';
// if(!isset($_GET['id'])){
// echo include"Partial/not_found.php";
// exit;
// }
$userId=$_GET['id'];
$user=getUsersById($userId);
if(!$user){
echo include"Partial/not_found.php";
exit;
}
// echo "<pre>";
// var_dump($_SERVER);
// echo "</pre>";
if($_SERVER['REQUEST_METHOD']==='POST'){
echo "<pre>";
var_dump($_POST);
echo "</pre>";
// updateUSer($_POST, $userId);
}
?>
<div class="container">
<div class="card">
<div class="card-header text-white bg-success">
<h3>Update User: <?php echo $user['name'];?></h3>
</div>
<div class="card-body">
<form method="POST" enctype="multipart/form-data" action="">
<div class="form-group">
<label >Name</label>
<input type="name" name="name" class="form-control" value="<?php echo $user['name'] ?>">
</div>
<div class="form-group">
<label >Username</label>
<input type="text" name="unsername"class="form-control" value="<?php echo $user['username'] ?>">
</div>
<div class="form-group">
<label >Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $user['email'] ?>">
</div>
<div class="form-group">
<label >Phone</label>
<input type="text" name="phone"class="form-control" value="<?php echo $user['phone'] ?>">
</div>
<div class="form-group">
<label >Website</label>
<input type="text" name="website" class="form-control" value="<?php echo $user['website'] ?>">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="picture" class="form-control-file"></div>
<input type="submit" class="btn btn-success" value="Update" name="update">
</form>
</div>
</div>
<?php include 'Partial/footer.php'; ?><file_sep>/JSON/JSON on Python/Json1.py
import json
import pandas as pd
import ast
with open('states.json') as file:
data=json.load(file)
for state in data['states']:
print(state['name'],state['abbreviation'])
del state['area_codes']
with open('new_states.json','w') as f:
json.dump(data,f,indent=2 )
| dc9c061c0a0607b72c7d69c6d2c36545704fc4a6 | [
"Markdown",
"Python",
"PHP"
] | 28 | Python | SegnorAlberto/DataModelling-JSON-XML | b1b4ee8b5fdd7fec5c2ff2609938b050cb84f110 | 9fc1fb5d1339f8990279f900b494e80f36094121 |
refs/heads/master | <file_sep><?php
if (have_posts()) {
while(have_posts()) {
the_post();
the_title();
the_content();
the_date();
}
}else {
echo '404! Not found!';
}
| fdbd38654a45272772ffc5334845ffd1a57663bb | [
"PHP"
] | 1 | PHP | Zachmanjz/From-Scratch | c67d6ad96993a87d1be1bc2d67daff3fa647b2f9 | d29745940bde16cabb25c2cfd9fa1c770747d83c |
refs/heads/master | <repo_name>skuhlmann/event_schedule<file_sep>/db/migrate/20150414192756_add_slug_to_event.rb
class AddSlugToEvent < ActiveRecord::Migration
def change
add_column :events, :day_slug, :string
end
end
<file_sep>/spec/features/browse_events_spec.rb
require 'rails_helper'
require 'capybara/rails'
require 'capybara/rspec'
describe "The event user", type: :feature do
it "can view all events for a single day" do
track = Track.create(name: "test_track", order: 1)
event = Event.create(name: "test event", start_date: DateTime.current, end_date: DateTime.current)
track.events << event
visit root_path
expect(page).to have_content("test event")
end
it "can toggle between days" do
track = Track.create(name: "test track", order: 1)
date = DateTime.current
earlier_date = date.yesterday
event = Event.create(name: "test event",
start_date: date,
end_date: date)
same_event = Event.create(name: "another test event",
start_date: date,
end_date: date)
earlier_event = Event.create(name: "older event",
start_date: earlier_date,
end_date: date)
[event, earlier_event, same_event].each { |e| track.events << e }
visit root_path
expect(page).to have_content("older event")
expect(page).to have_content("#{event.day_slug} events")
expect(page).to have_content("#{earlier_event.day_slug} events")
click_link("#{event.day_slug} events")
expect(page).to have_content("test event")
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'events#index'
get '/events/:day_slug' => 'events#index'
get '/events' => 'events#index'
end
<file_sep>/app/controllers/events_controller.rb
class EventsController < ApplicationController
def index
@event_slugs = Event.day_slugs
if missing_slug?
@events = Event.where(day_slug: Event.earliest_day_slug)
@tracks = @events.available_tracks
else
@events = Event.where(day_slug: params[:day_slug])
@tracks = @events.available_tracks
end
end
private
def missing_slug?
params[:day_slug].nil? || Event.day_slugs.none? do |slug|
slug == params[:day_slug]
end
end
end
<file_sep>/db/seeds.rb
require 'csv'
class Seed
def initialize
generate_tracks
generate_events
end
def generate_tracks
Track.create(name: "Pattern Recognition", order: 1)
Track.create(name: "Image, Speech, and Signal Processing", order: 2)
Track.create(name: "Document Analysis", order: 3)
Track.create(name: "Biometrics", order: 4)
Track.create(name: "Bioinformatics", order: 5)
puts "#{Track.count} Tracks created"
end
def generate_events
CSV.foreach("db/csv/seed_events.csv", { encoding: "UTF-8", headers: true, header_converters: :symbol}) do |row|
Event.create(row.to_hash)
end
puts "#{Event.count} Events created"
end
end
Seed.new
<file_sep>/spec/models/event_spec.rb
require 'rails_helper'
RSpec.describe Event, type: :model do
it "can belong to a track" do
track = Track.create(name: "test track", order: 1)
event = Event.create(name: "test event")
event.track = track
expect(event.track.name).to eq("test track")
end
it "creates a day slug on save" do
date = DateTime.current
event = Event.create(name: "test event",
start_date: date)
slug = date.to_date.to_formatted_s(:db)
expect(event.day_slug).to eq(slug)
end
it "returns it's earliest day slug" do
date = DateTime.current
earlier_date = date.yesterday
event = Event.create(name: "test event",
start_date: date)
earlier_event = Event.create(name: "older event",
start_date: earlier_date)
expect(Event.earliest_day_slug).to eq(earlier_event.day_slug)
end
it "return a list of unique day slugs" do
date = DateTime.current
earlier_date = date.yesterday
event = Event.create(name: "test event",
start_date: date)
same_event = Event.create(name: "another test event",
start_date: date)
earlier_event = Event.create(name: "older event",
start_date: earlier_date)
expect(Event.count).to eq(3)
expect(Event.day_slugs.count).to eq(2)
end
end
<file_sep>/app/models/event.rb
class Event < ActiveRecord::Base
belongs_to :track
before_save :generate_day_slug
def generate_day_slug
self.day_slug = start_date.to_date.to_formatted_s(:db) if start_date.present?
end
def self.earliest_day_slug
minimum(:day_slug)
end
def self.day_slugs
all.map { |event| event.day_slug }.uniq
end
def self.track(order)
where(track_id: [order, nil])
end
def self.available_tracks
pluck(:track_id).grep(Integer).uniq.sort
end
end
<file_sep>/db/migrate/20150414172049_add_track_ref_to_events.rb
class AddTrackRefToEvents < ActiveRecord::Migration
def change
add_reference :events, :track, index: true
add_foreign_key :events, :tracks
end
end
<file_sep>/README.md
# README
The event schedule is an exercise in creating a simple event agenda with mulitple events and concurrent tracks.
## Install
Installation instructions:
` git clone https://github.com/skuhlmann/event_schedule.git `
` bundle install `
Database creation and initialization:
` rake db:create && rake db:migrate & rake db:seed `
How to run the test suite:
` rspec `
### Exercise Requirements
* Create a rails application (latest version). Do this on GitHub to make it easier to review and install locally.
* If you are familiar with postgresql as your database use that, otherwise sqllite is ok.
* Setup an appropriate data model for the attached events.
* Display the tracks in a tabular format so they are viewable in a browser. Times should be on the left side (y-axis), tracks on the top (x-axis). The cells should be events. Note it doesn't have to look pretty.
* Only one day at a time should be shown, so there should be a toggle between different days (the days should be generated from the database, not hard-coded)
* The start and end times of each session should line up with the appropriate times on the left
* Some sessions go across all tracks. Those sessions are the Monday Plenary Break, all coffee breaks, all lunches, the poster session and the night at the aquarium.
* The order of the tracks (thus columns) should be configurable (meaning setup the data model to support that, but don't worry about writing a gui for it or anything)
<file_sep>/spec/models/track_spec.rb
require 'rails_helper'
RSpec.describe Track, type: :model do
it "Returns it's events" do
track = Track.create(name: "test track", order: 1)
event = Event.create(name: "test event")
event2 = Event.create(name: "another test event")
track.events << event
track.events << event2
expect(track.events.count).to eq(2)
expect(track.events[0]).to eq(event)
end
end
| 3bc427f6f0d586d44463b1489c433bb0009153b4 | [
"Markdown",
"Ruby"
] | 10 | Ruby | skuhlmann/event_schedule | 5c2aa01c8cd5d898b336e0b3148ba8e57fb06101 | eaf285900e7c2a39405fa91cc0414529b9c6b6ca |
refs/heads/master | <repo_name>laurynasn/pies<file_sep>/scripts/main.js
//script for the menu toggle
$('.menuBtn').click(function() {
if ($('.toggleMenuBtn').text() === ' ▼') {
$('.toggleMenuBtn').text(' ▲');
$('#topNav').removeClass('hide').addClass('show');
} else {
$('.toggleMenuBtn').text(' ▼');
$('#topNav').removeClass('show').addClass('hide');
}
});
//script for custom checkbox
$('.checkbox').click(function() {
if ($('.checkbox input').attr('checked')) {
$('label.checkbox').removeClass('unchecked').addClass('checked');
} else {
$('label.checkbox').removeClass('checked').addClass('unchecked');
}
});
| f10c44707c9cae33ffba705a8ac4a05b0daef8df | [
"JavaScript"
] | 1 | JavaScript | laurynasn/pies | 6d46f9f6aae6e8b09ea5e1484572e24b4e388e86 | 44aefe238e67fef55bdc7409338f64420525416a |
refs/heads/master | <file_sep>package com.example.runningapp.db
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface RunDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRun(run: Run)
@Delete
suspend fun deleteRun(run: Run)
@Query(value = "SELECT * FROM running_table ORDER BY timestamp DESC")
fun getAllRunsSortedByDate():LiveData<List<Run>>
@Query(value = "SELECT * FROM running_table ORDER BY timeInMillis DESC")
fun getAllRunsSortedByTimeInMillis():LiveData<List<Run>>
@Query(value = "SELECT * FROM running_table ORDER BY caloriesBurned DESC")
fun getAllRunsSortedByCaloriesBurned():LiveData<List<Run>>
@Query(value = "SELECT * FROM running_table ORDER BY averageSpeedInKMPH DESC")
fun getAllRunsSortedByAverageSpeed():LiveData<List<Run>>
@Query(value = "SELECT * FROM running_table ORDER BY distanceInMeters DESC")
fun getAllRunsSortedByDistance():LiveData<List<Run>>
@Query(value = "SELECT SUM(timeInMillis) FROM running_table")
fun getTotalTimeInMillis():LiveData<Long>
@Query(value = "SELECT SUM(caloriesBurned) FROM running_table")
fun getTotalCaloriesBurned():LiveData<Int>
@Query(value = "SELECT SUM(distanceInMeters) FROM running_table")
fun getTotalDistance():LiveData<Int>
@Query(value = "SELECT AVG(averageSpeedInKMPH) FROM running_table")
fun getTotalAverageSpeed():LiveData<Float>
/**
* @Query("""
SELECT * FROM running_table
ORDER BY
CASE WHEN :column = 'timestamp' THEN timestamp END DESC,
CASE WHEN :column = 'timeInMillis' THEN timeInMillis END DESC,
CASE WHEN :column = 'calories' THEN caloriesBurned END DESC,
CASE WHEN :column = 'speed' THEN averageSpeedInKMPH END DESC,
CASE WHEN :column = 'distance' THEN distanceInMeters END DESC
""")
fun sortBy(column : String) : LiveData<List<Run>>
**/
}<file_sep>package com.example.runningapp.di
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import androidx.room.Room
import com.example.runningapp.db.RunningDatabase
import com.example.runningapp.other.Constants.KEY_FIRST_TIME_TOGGLE
import com.example.runningapp.other.Constants.KEY_NAME
import com.example.runningapp.other.Constants.KEY_WEIGHT
import com.example.runningapp.other.Constants.RUNNING_DATABASE_NAME
import com.example.runningapp.other.Constants.SHARED_PREFERENCES_NAME
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun providesRunningDatabase(@ApplicationContext applicationContext: Context)
= Room.databaseBuilder(
applicationContext,
RunningDatabase::class.java,
RUNNING_DATABASE_NAME
).build()
@Singleton
@Provides
fun providesRunningDao(database: RunningDatabase) = database.getDao()
@Singleton
@Provides
fun provideSharedPreferences(@ApplicationContext applicationContext: Context ) =
applicationContext.getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE)
@Singleton
@Provides
fun provideName(sharedPreferences: SharedPreferences) =
sharedPreferences.getString(KEY_NAME, " ") ?: " "
@Singleton
@Provides
fun provideWeight(sharedPreferences: SharedPreferences) =
sharedPreferences.getFloat(KEY_WEIGHT, 80f)
@Singleton
@Provides
fun provideFirstTimeToggle(sharedPreferences: SharedPreferences) =
sharedPreferences.getBoolean(KEY_FIRST_TIME_TOGGLE, true)
}<file_sep>package com.example.runningapp.db
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverter
import androidx.room.TypeConverters
@Database(
entities = [Run::class],
version = 1
)
@TypeConverters(Converter::class)
abstract class RunningDatabase:RoomDatabase() {
abstract fun getDao():RunDao
}<file_sep># Running-Tracker Application
A health application that tracks runners' locations to calculate speed, calories burned and more. You can see previous runs and track personal progress.
<file_sep>package com.example.runningapp.other
enum class SortType {
DATE, RUNNING_TIME, DISTANCE, AVERAGAE_SPEED, CALORIES_BURNED
} | 72b7c7574b344ac5a11bf8cacc8f28e673e1c6bc | [
"Markdown",
"Kotlin"
] | 5 | Kotlin | RutaleIvanPaul/Running-Tracker-Application | 9b714b866d2639e69efca597320a0a910be6e6f0 | f96787bb0ce2629724ef869270b3571e6d57b0a1 |
refs/heads/master | <file_sep>import re
import requests
import smtplib
import datetime
import poplib
p = poplib.POP3_SSL('pop.gmail.com')
p.user(username)
p.pass_(<PASSWORD>)
mails = [p.retr(emailNum)[1] for emailNum in [int(numstr.split(' ')[0]) for numstr in p.list()[1]]]
p.quit()
addresses_sub = [mail[3].split('<')[1].split('>')[0] for mail in mails if 'subscribe' in mail[34].lower() and 'unsubscribe' not in mail[34].lower()]
addresses_unsub = [mail[3].split('<')[1].split('>')[0] for mail in mails if 'unsubscribe' in mail[34].lower()]
current_file = open('C:/Users/2-321 Desktop/Desktop/Anaconda/subscriberList.txt')
addresses = current_file.read().split('\n')
current_file.close()
for address in addresses_sub:
if address not in addresses:
addresses.append(address)
for address in addresses_unsub:
if address in addresses:
addresses.remove(address)
current_file = open('C:/Users/2-321 Desktop/Desktop/Anaconda/subscriberList.txt','w')
current_file.write('\n'.join(addresses))
current_file.close()
current_file = open('C:/Users/2-321 Desktop/Desktop/Anaconda/PRL_PRA_Scraper.txt','r')
current = current_file.read()
current_file.close()
(prl_volume,prl_issue) = re.findall('PRL Volume ([0-9]+), Issue ([0-9]+)',current)[0]
(pra_volume,pra_issue) = re.findall('PRA Volume ([0-9]+), Issue ([0-9]+)',current)[0]
paper_regexp = '<a href="/(.*?[0-9])">(.*?)</a>(?:.*?"authors">)(.*?)</h6>'
sect_regexp_start = '<a name="sect-'
sect_regexp_end = '(?:(?!</section>).)*'
(prl_url,pra_url) = ('http://journals.aps.org/prl/issues/'+prl_volume+'/'+prl_issue,'http://journals.aps.org/pra/issues/'+pra_volume+'/'+pra_issue)
base_url = 'journals.aps.org/'
(prl_req,pra_req) = (requests.get(prl_url),requests.get(pra_url))
(prl_data,pra_data) = (prl_req.text,pra_req.text)
(prl_sect,pra_sect) = (['Letters: Atomic, Molecular, and Optical Physics'],['Rapid Communications: Atomic and Molecular Processes in External Fields, including Interactions with Strong Fields and Short Pulses','Articles: Atomic and Molecular Processes in External Fields, including Interactions with Strong Fields and Short Pulses','Rapid Communications: Quantum Optics, Physics of Lasers, Nonlinear Optics, Classical Optics','Articles: Quantum Optics, Physics of Lasers, Nonlinear Optics, Classical Optics'])
(prl_sect_regexp,pra_sect_regexp) = (['letters-atomic'],['rapid-communications-atomic-and-molecular-p','articles-atomic-and-molecular-p','rapid-communications-quantum-o','articles-quantum-o'])
now = datetime.datetime.now()
msg = 'From: 2-321 Drive\nTo: PRL Email List\nMIME-Version: 1.0\nContent-type: text/html\nSubject: Physical Review Article Update '+str(now.month)+'/'+str(now.day)+'/'+str(now.year)
(new_prl,new_pra) = (not(('<h1>Not Found</h1>' in prl_data)|('Volume '+prl_volume+', Issue '+prl_issue+' (partial)' in prl_data)),not(('<h1>Not Found</h1>' in pra_data)|('Volume '+pra_volume+', Issue '+pra_issue+' (partial)' in pra_data)))
if new_prl:
msg = msg+'\n\n<font size="3"><u><b>PRL Volume '+prl_volume+', Issue '+prl_issue+':</b></u></font><br><br>'
for sect,sect_regexp in zip(prl_sect,prl_sect_regexp):
sect_data = re.findall(sect_regexp_start+sect_regexp+sect_regexp_end,prl_data,re.DOTALL)
if sect_data:
prl_papers = re.findall(paper_regexp,sect_data[0])
msg = msg+'<ul><font size="2"><li><b>'+sect+'</b></li></font></ul>'+'<br>'+'<br><br>'.join(['<a href="'+base_url+paper[0]+'">'+paper[1]+'</a><br>'+paper[2] for paper in prl_papers])
if msg[-4:]=='<br>':
msg = msg+'None Found'
(prl_volume,prl_issue) = (int(prl_volume),int(prl_issue))
(prl_volume,prl_issue) = (str(prl_volume+(prl_issue==26)),str(prl_issue*(prl_issue<26)+1))
if new_pra:
if new_prl:
msg = msg+'<br><br>'
else:
msg = msg+'\n\n'
msg = msg+'<font size="3"><u><b>PRA Volume '+pra_volume+', Issue '+pra_issue+':</b></u></font><br><br>'
for sect,sect_regexp in zip(pra_sect,pra_sect_regexp):
sect_data = re.findall(sect_regexp_start+sect_regexp+sect_regexp_end,pra_data,re.DOTALL)
if sect_data:
pra_papers = re.findall(paper_regexp,sect_data[0])
msg = msg+'<ul><font size="2"><li><b>'+sect+'</b></li></font></ul>'+'<br>'+'<br><br>'.join(['<a href="'+base_url+paper[0]+'">'+paper[1]+'</a><br>'+paper[2] for paper in pra_papers])
if msg[-4:]=='<br>':
msg = msg+'None Found'
(pra_volume,pra_issue) = (int(pra_volume),int(pra_issue))
(pra_volume,pra_issue) = (str(pra_volume+(pra_issue==6)),str(pra_issue*(pra_issue<6)+1))
if any([new_prl,new_pra]):
msg = msg+'<br><br><br>Send an email to <EMAIL> with the word "unsubscribe" in the body of the email to unsubscribe from this list.'
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(username,password)
s.sendmail(username,addresses,msg.encode('utf8'))
s.quit()
current_file = open('C:/Users/2-321 Desktop/Desktop/Anaconda/PRL_PRA_Scraper.txt','w')
current_file.write('PRL Volume '+prl_volume+', Issue '+prl_issue+'\nPRA Volume '+pra_volume+', Issue '+pra_issue)
current_file.close()
<file_sep># PRL-PRA-Scraper
| b9f39989687db00500d39f8de2b92318bb4dc323 | [
"Markdown",
"Python"
] | 2 | Python | e-champenois/PRL-PRA-Scraper | c80ad9859fdd37bb70f03962cea6c90f965123b2 | 39bfa552e5516fa3a5ae870c24b490094a504c90 |
refs/heads/master | <repo_name>mbadros/Series-I-Bonds<file_sep>/README.md
# Calculating Series I Bond Values
* Calculate historical monthly values for the Series I (inflation-indexed) bonds issued by the U.S. Treasury.
* Calculate projected future values (through maturity) for Series I bonds based on an assumed rate of inflation.
### Details ###
Since [1998], the U.S. Treasury has issued Series I bonds to allow investors and savers to earn a guaranteed real rate of return, that is, a nominal rate in excess of the inflation rate.
Interest on an I Bond rates is a combination of two rates:
* A fixed rate of return which remains the same throughout the life of the I Bond and
* A variable inflation rate which we calculate twice a year, based on changes in the nonseasonally adjusted Consumer Price Index for all Urban Consumers (CPI-U) for all items, including food and energy (CPI-U for March compared with the CPI-U for September of the same year, and then CPI-U for September compared with the CPI-U for March of the following year).
Interest is earned on the bond every month.
The interest is compounded semiannually: Every six months, on the 6th and 12th month anniversaries of the issue date, all interest the bond has earned in previous months is in the bond's new principal value on which interest is earned for the next 6 months.
### Caveats ###
This R script is intended as an estimate for informational purposes only, and is not meant to be a representation as to the value of any specific bond at any point in time. This script is not an offer to buy or sell any securities.
The [U.S. Treasury securities website](https://www.treasurydirect.gov) contains much more detailed information about Series I Savings Bonds. However, it is not clear precisely how the Treasury applies certain rounding conventions to the calculation of interest accruals. In addition, there may be floating-point errors that affect the precise calculation of reported results.<file_sep>/bond_price_calculation.R
######
##
packages <- c('quantmod', 'lubridate', 'rvest', 'dplyr')
lapply(packages, require, character.only = TRUE)
# Load CPI data from FRED
CPIU <- getSymbols('CPIAUCNS', src = 'FRED', return.class = 'zoo', auto.assign = FALSE)
inflation_measuremt_dates <- seq(from = as.Date("1998-03-01"), to = Sys.Date(), by = "6 months")
CPI_levels_semiannually <- CPIU[inflation_measuremt_dates]
inflation_rate <- round(CPI_levels_semiannually / Lag(CPI_levels_semiannually) - 1, digits = 4)
index(inflation_rate) <- index(inflation_rate) + months(2)
url <- 'https://www.treasurydirect.gov/indiv/research/indepth/ibonds/res_ibonds_iratesandterms.htm'
info_table = read_html(url) %>% html_table()
raw_fixed_rate <- info_table[[3]]
raw_fixed_rate$rate <- as.numeric(gsub("%", "", raw_fixed_rate[ , 2]))/100
raw_fixed_rate$date <- mdy(raw_fixed_rate[ , 1])
fixed_rate <- raw_fixed_rate %>% select(c("date", "rate")) %>% arrange(date)
ISSUE_DATE <- '2001-10-13'
YEARS_TO_CALC <- 30
DENOMINATION <- 1000
INFLATION_ASSUMED <- 0.013
VALUE_DATE = as.Date('2017-10-01')
adj_issue_date <- as.Date(as.yearmon(ISSUE_DATE), frac = 0)
maturity_date <- adj_issue_date + years(30)
fixed_component <- fixed_rate$rate[findInterval(adj_issue_date, fixed_rate$date)]
inflation_period <- inflation_rate[index(inflation_rate) > adj_issue_date - months(6)]
composite_rate <- fixed_component + (2 * inflation_period) + (fixed_component * inflation_period)
coredata(composite_rate) <- pmax(0, round(coredata(composite_rate), digits = 4))
PROJ_COMPOSITE <- round(fixed_component + (2 * INFLATION_ASSUMED) + (fixed_component * INFLATION_ASSUMED), digits = 4)
redemption <- data.frame(Date = seq(from = adj_issue_date, to = min(VALUE_DATE, maturity_date), by = "1 month"),
Bond_value = DENOMINATION,
Interest_base = DENOMINATION,
Monthly_interest = 0,
Unpaid_interest = 0)
g <- seq(adj_issue_date, min(VALUE_DATE, maturity_date), 'month')
monthly_rates <- zoo(rep(composite_rate / 12, each = 6), order.by = g) ## Check Rounding
for(i in 1:(length(g)-1)) {
redemption$Monthly_interest[i] <- (monthly_rates[i] * redemption$Interest_base[i]) %>% round(digits = 2)
redemption$Unpaid_interest[i] <- redemption$Unpaid_interest[max(1, i-1)] + redemption$Monthly_interest[i]
redemption$Bond_value[i+1] <- redemption$Interest_base[i] + redemption$Unpaid_interest[i]
redemption$Interest_base[i + 1] <- redemption$Interest_base[i]
if(i %% 6 == 0) {
redemption$Interest_base[i+1] <- redemption$Interest_base[i] + redemption$Unpaid_interest[i]
redemption$Unpaid_interest[i] <- 0
}
}
final_value <- redemption$Bond_value[length(g)] + redemption$Unpaid_interest[length(g) - 1]
cat("The bond's value at", format(redemption$Date[length(g)], '%B %Y'), 'is')
paste0('$', prettyNum(final_value, format = 'f', big.mark = ',')
)
| 40957f4aea3d633f7f58bef9724e3e51877c6713 | [
"Markdown",
"R"
] | 2 | Markdown | mbadros/Series-I-Bonds | 3c79bbc37096959577b79cb7b9ebcbc8cfac7ee4 | 28156813f3de9cc3e9a0ff284762f9bf5804b1f8 |
refs/heads/master | <repo_name>osher30/MemorialPath1<file_sep>/app/src/main/java/com/shlomisasportas/ShowSearchDataActivity.java
package com.shlomisasportas;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ShowSearchDataActivity extends AppCompatActivity {
ListView listView ;
ArrayList listData;
public static String latitude,longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_show_search_data);
listView = (ListView) findViewById(R.id.list);
listData = new ArrayList();
for (int i =0; i< SearchActivity.keys.size(); i++){
listData.add(MainActivity.allUsers.get(SearchActivity.keys.get(i)).getFirstName() + " " + MainActivity.allUsers.get(SearchActivity.keys.get(i)).getLastName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listData);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
String firstName = "שם פרטי: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getFirstName()+"\n"
+ "שם משפחה: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getLastName()+"\n"
+"תאריך לידה: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getDateOfBirth()+"\n"
+ "שם האם: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getMomName()+"\n"
+ "שם האב: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getDadName()+"\n"
+ "מקום קבורה: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getDeathLocation()+"\n"
+ "תאריך פטירה: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getDateOfDeath()+"\n"
+ "גיל: "+MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getAge()+"\n"
+ "עיר קבורה:" +MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getCity()+"\n"
+ "שורה:" +MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getRow()+"\n"
+ "גוש:" +MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getParcel()+"\n"
+ "חלקה:" +MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getPart()+"\n"
+ "מספר קבר:" +MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getGravenumber()+"\n";
latitude = MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getLatitude();
longitude = MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getLongitude();
Intent i = new Intent(ShowSearchDataActivity.this, IndiviualsInfoActivity.class);
i.putExtra("data", firstName);
i.putExtra("url", MainActivity.allUsers.get(SearchActivity.keys.get(itemPosition)).getProfilePicture());
i.putExtra("position", position);
startActivity(i);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/DeleteEventsActivity.java
package com.shlomisasportas;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class DeleteEventsActivity extends AppCompatActivity {
public static ArrayList<EventPost> allEvents;
public static ArrayList<String> allkeys;
public ArrayList<String> eventplace;
ListView listView ;
ImageView profile, video, picture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_events);
allEvents = new ArrayList<>();
allkeys = new ArrayList<>();
eventplace = new ArrayList<>();
profile = (ImageView) findViewById(R.id.profile);
video = (ImageView) findViewById(R.id.video);
picture = (ImageView) findViewById(R.id.music);
picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DeleteEventsActivity.this, PhotoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position", 0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url", getIntent().getStringExtra("url"));
startActivity(i);
}
});
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DeleteEventsActivity.this, IndiviualsInfoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
}
});
video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DeleteEventsActivity.this, YoutubeVideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position", 0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url", getIntent().getStringExtra("url"));
startActivity(i);
}
});
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = mFirebaseDatabase.getReference("Events");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.v("Database",""+ childDataSnapshot.getKey()); //displays the key for the node
EventPost post = new EventPost();
String key = MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0)));
if (key.equals(""+childDataSnapshot.child("key").getValue())){
post.setPlace(""+childDataSnapshot.child("place").getValue());
post.setDatee(""+childDataSnapshot.child("datee").getValue());
post.setLocation(""+childDataSnapshot.child("location").getValue());
allkeys.add(childDataSnapshot.getKey());
allEvents.add(post);
eventplace.add("מיקום: "+childDataSnapshot.child("place").getValue()+"\n,תאריך: "
+""+childDataSnapshot.child("datee").getValue());
}else {
Log.i("datanot", ""+childDataSnapshot.child("place").getValue());
Log.i("datanot", ""+childDataSnapshot.child("datee").getValue());
Log.i("datanot", ""+childDataSnapshot.child("location").getValue());
Log.i("datanot", ""+key);
Log.i("datanot", ""+childDataSnapshot.child("key").getValue());
}
}
listView = (ListView) findViewById(R.id.list);
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(DeleteEventsActivity.this,
android.R.layout.simple_list_item_1, android.R.id.text1, eventplace);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(DeleteEventsActivity.this);
builder.setMessage("האם אתה בטוח שברצונך למחוק אירוע זה ?")
.setCancelable(false)
.setPositiveButton(" כן", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
databaseReference.child(allkeys.get(pos)).removeValue();
allkeys.remove(pos);
allEvents.remove(pos);
eventplace.remove(pos);
listView.invalidateViews();
}
})
.setNegativeButton("לא", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
Intent i = new Intent(DeleteEventsActivity.this, AddMemorialEventActivity.class);
i.putExtra("position", getIntent().getIntExtra("position", 0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url", getIntent().getStringExtra("url"));
startActivity(i);
return true;
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.addeve, menu);
return true;
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/VideoActivity.java
package com.shlomisasportas;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import nz.co.iswe.android.mediagallery.MediaGalleryView;
import nz.co.iswe.android.mediagallery.MediaInfo;
public class VideoActivity extends AppCompatActivity {
private MediaGalleryView mMediaGalleryView;
ArrayList<String> allURls=new ArrayList<>();
public static ArrayList<String> thumbnailURLs = new ArrayList<>();
ArrayList<String> deleteKeys = new ArrayList<>();
ProgressDialog pd ;
ImageView profile, memorialEvent, picture, video;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
pd = new ProgressDialog(this,R.style.ProgressDiaglog);
pd.setMessage("loading");
pd.show();
picture = (ImageView) findViewById(R.id.music);
memorialEvent = (ImageView) findViewById(R.id.memorialevent);
profile = (ImageView) findViewById(R.id.profile);
video = (ImageView) findViewById(R.id.video);
picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i= new Intent(VideoActivity.this, PhotoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
}
});
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(VideoActivity.this, IndiviualsInfoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
}
});
memorialEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
builder.setCancelable(false)
.setPositiveButton("מחק אירוע", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(VideoActivity.this, DeleteEventsActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
})
.setNegativeButton("הוסף אירוע", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(VideoActivity.this, AddMemorialEventActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
builder.setCancelable(false)
.setPositiveButton("סרטון יוטיוב?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i= new Intent(VideoActivity.this, YoutubeVideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
})
.setNegativeButton("סרטון?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i= new Intent(VideoActivity.this, VideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = mFirebaseDatabase.getReference("Videos");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.v("Database",""+ childDataSnapshot.getKey()); //displays the key for the node
String key = MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0)));
if (key.equals(""+childDataSnapshot.child("key").getValue())){
deleteKeys.add(""+childDataSnapshot.getKey());
String url = ""+childDataSnapshot.child("url").getValue();
String thumbnailurl = ""+childDataSnapshot.child("thumbnailurl").getValue();
allURls.add(url);
thumbnailURLs.add(thumbnailurl);
Log.i("urlssss", url);
Log.i("urlssss", thumbnailurl);
}
}
mMediaGalleryView = (MediaGalleryView) findViewById(R.id.scroll_gallery_view);
new Thread(new Runnable() {
public void run() {
final Bitmap bm[] = new Bitmap[allURls.size()] ;//= getBitmapFromURL("https://firebasestorage.googleapis.com/v0/b/shlomisasportas-344fc.appspot.com/o/-L1rNct1TFhYFxZaHYq-%2Foria.png?alt=media&token=<PASSWORD>");
for (int i=0; i<allURls.size(); i++){
bm[i] = getBitmapFromURL(thumbnailURLs.get(i));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i=0; i<allURls.size();i++){
mMediaGalleryView
.setThumbnailSize(100)
.setZoom(true)
.setFragmentManager(getSupportFragmentManager())
.addMedia(MediaInfo
.url(allURls.get(i), bm[i]));
}
pd.dismiss();
}
});
}
}).start();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private Bitmap convertDrawableToBitmap(int image) {
return ((BitmapDrawable) getResources().getDrawable(image)).getBitmap();
}
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
myBitmap = getResizedBitmap(myBitmap, 200,200);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.addpic, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.add:
LinearLayout layout = new LinearLayout(VideoActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText edittext = new EditText(VideoActivity.this);
edittext.setHint("הכנס קישור לסרטון");
final EditText edittext1 = new EditText(VideoActivity.this);
edittext1.setHint("הכנס תמונת קישור");
layout.addView(edittext);
layout.addView(edittext1);
alert.setView(layout);
alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//What ever you want to do with the value
String YouEditTextValue = edittext.getText().toString();
if (!YouEditTextValue.equals("") & !edittext1.getText().toString().equals("")){
addData(YouEditTextValue, edittext1.getText().toString());
Intent i = new Intent(VideoActivity.this, VideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
finish();
}
}
});
alert.setNegativeButton("לא", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
return true;
case R.id.delete:
DatabaseReference dbNode = FirebaseDatabase.getInstance().getReference().getRoot().child("Videos").child(deleteKeys.get(mMediaGalleryView.current_Selected()));
dbNode.removeValue();
Toast.makeText(VideoActivity.this, "Deleted", Toast.LENGTH_LONG).show();
Intent i = new Intent(VideoActivity.this, VideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addData(String url, String thumbnail){
FirebaseDatabase database = FirebaseDatabase.getInstance();
// Log.i("reference",""+SearchActivity.keys.get(MainActivity.allkeys.get( getIntent().getIntExtra("position",0))));
DatabaseReference posts = database.getReference("Videos");//.child(""+MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0))));
posts.keepSynced(true);
String key = MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0)));
VideoPost eventPost = new VideoPost();
eventPost.setKey(key);
eventPost.setUrl(url);
eventPost.setThumbnailurl(thumbnail);
posts.push().setValue(eventPost);
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/PhotoActivity.java
package com.shlomisasportas;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import nz.co.iswe.android.mediagallery.MediaGalleryView;
import nz.co.iswe.android.mediagallery.MediaInfo;
public class PhotoActivity extends AppCompatActivity {
private MediaGalleryView mMediaGalleryView;
ArrayList<String> allURls=new ArrayList<>();
ImageView memorialEvent, profile, video;
ArrayList<String> deleteKeys = new ArrayList<>();
ProgressDialog pd ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
pd = new ProgressDialog(this,R.style.ProgressDiaglog);
pd.setMessage("loading");
pd.show();
memorialEvent = (ImageView) findViewById(R.id.memorialevent);
profile = (ImageView) findViewById(R.id.profile);
video = (ImageView) findViewById(R.id.video);
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(PhotoActivity.this, IndiviualsInfoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
}
});
memorialEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(PhotoActivity.this, DeleteEventsActivity.class);
i.putExtra("position", getIntent().getIntExtra("position", 0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url", getIntent().getStringExtra("url"));
startActivity(i);
}
});
/*memorialEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
builder.setCancelable(false)
.setPositiveButton("מחק אירוע", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(PhotoActivity.this, DeleteEventsActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
})
.setNegativeButton("הוסף אירוע", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(PhotoActivity.this, AddMemorialEventActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});*/
video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(PhotoActivity.this, YoutubeVideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position", 0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url", getIntent().getStringExtra("url"));
startActivity(i);
}
});
/*video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
builder.setCancelable(false)
.setPositiveButton("סרטון יוטיוב?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i= new Intent(PhotoActivity.this, YoutubeVideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
})
.setNegativeButton("סרטון?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i= new Intent(PhotoActivity.this, VideoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
startActivity(i);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});*/
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = mFirebaseDatabase.getReference("Pictures");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.v("Database",""+ childDataSnapshot.getKey()); //displays the key for the node
String key = MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0)));
if (key.equals(""+childDataSnapshot.child("key").getValue())){
Log.v("DatabaseMatch",""+ childDataSnapshot.getKey());
deleteKeys.add(""+childDataSnapshot.getKey());
String url = ""+childDataSnapshot.child("url").getValue();
allURls.add(url);
Log.i("urlssss", url);
}
}
mMediaGalleryView = (MediaGalleryView) findViewById(R.id.scroll_gallery_view);
new Thread(new Runnable() {
public void run() {
final Bitmap bm[] = new Bitmap[allURls.size()] ;//= getBitmapFromURL("https://firebasestorage.googleapis.com/v0/b/shlomisasportas-344fc.appspot.com/o/-L1rNct1TFhYFxZaHYq-%2Foria.png?alt=media&token=<PASSWORD>");
for (int i=0; i<allURls.size(); i++){
bm[i] = getBitmapFromURL(allURls.get(i));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i=0; i<allURls.size();i++){
mMediaGalleryView
.setThumbnailSize(100)
.setZoom(true)
.setFragmentManager(getSupportFragmentManager())
.addMedia(MediaInfo.imageLoader(bm[i]));
}
;
pd.dismiss();
}
});
}
}).start();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
myBitmap = getResizedBitmap(myBitmap, 200,200);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.addpic, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.add:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText edittext = new EditText(PhotoActivity.this);
alert.setTitle("הכנסת תמונת קישור");
alert.setView(edittext);
alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//What ever you want to do with the value
String YouEditTextValue = edittext.getText().toString();
if (!YouEditTextValue.equals("")){
addData(YouEditTextValue);
Intent i = new Intent(PhotoActivity.this, PhotoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
finish();
}
}
});
alert.setNegativeButton("לא", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
return true;
case R.id.delete:
DatabaseReference dbNode = FirebaseDatabase.getInstance().getReference().getRoot().child("Pictures").child(deleteKeys.get(mMediaGalleryView.current_Selected()));
dbNode.removeValue();
Toast.makeText(PhotoActivity.this, "Deleted", Toast.LENGTH_LONG).show();
Intent i = new Intent(PhotoActivity.this, PhotoActivity.class);
i.putExtra("position", getIntent().getIntExtra("position",0));
i.putExtra("data", getIntent().getStringExtra("data"));
i.putExtra("url",getIntent().getStringExtra("url"));
startActivity(i);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addData(String url){
FirebaseDatabase database = FirebaseDatabase.getInstance();
// Log.i("reference",""+SearchActivity.keys.get(MainActivity.allkeys.get( getIntent().getIntExtra("position",0))));
DatabaseReference posts = database.getReference("Pictures");//.child(""+MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0))));
posts.keepSynced(true);
String key = MainActivity.allkeys.get(SearchActivity.keys.get(getIntent().getIntExtra("position",0)));
PicturePost eventPost = new PicturePost();
eventPost.setKey(key);
eventPost.setUrl(url);
posts.push().setValue(eventPost);
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/MainActivity.java
package com.shlomisasportas;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public static ArrayList<Post> allUsers;
private ProgressDialog dialog;
ImageView search,addNewProfile;
public static ArrayList<String> allkeys;
ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this,R.style.ProgressDiaglog);
logo = (ImageView) findViewById(R.id.upcomingevents);
logo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, UpComingEventsActivity.class);
startActivity(i);
}
});
allkeys = new ArrayList<>();
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
search = (ImageView) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i =new Intent(MainActivity.this, SearchActivity.class);
startActivity(i);
}
});
allUsers = new ArrayList<>();
addNewProfile = (ImageView) findViewById(R.id.addProfile);
addNewProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, AddNewUserActivity.class);
startActivity(i);
}
});
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = mFirebaseDatabase.getReference("allUsers");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.v("Database",""+ childDataSnapshot.getKey()); //displays the key for the node
allkeys.add(childDataSnapshot.getKey());
Post post = new Post();
post.setFirstName(""+childDataSnapshot.child("firstName").getValue());
post.setLastName(""+childDataSnapshot.child("lastName").getValue());
post.setAge(""+childDataSnapshot.child("age").getValue());
post.setDateOfBirth(""+childDataSnapshot.child("dateOfBirth").getValue());
post.setDeathLocation(""+childDataSnapshot.child("deathLocation").getValue());
post.setDateOfDeath(""+childDataSnapshot.child("dateOfDeath").getValue());
post.setMomName(""+childDataSnapshot.child("momName").getValue());
post.setDadName(""+childDataSnapshot.child("dadName").getValue());
post.setProfilePicture(""+childDataSnapshot.child("profilePicture").getValue());
post.setPart(""+childDataSnapshot.child("part").getValue());
post.setCity(""+childDataSnapshot.child("city").getValue());
post.setParcel(""+childDataSnapshot.child("parcel").getValue());
post.setRow(""+childDataSnapshot.child("row").getValue());
post.setGravenumber(""+childDataSnapshot.child("gravenumber").getValue());
post.setLongitude(""+childDataSnapshot.child("longitude").getValue());
post.setLatitude(""+childDataSnapshot.child("latitude").getValue());
allUsers.add(post);
}
dialog.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//addData("Jasson", "Roy", "01/01/1991", "25", "01/01/2017", "India", "Jannifer", "Roy" );
}
public void addData(String firstName,String lastName,String dayOfBirth,String Age,String DateOfDeath,
String deathLocation,String momsName,String dadName){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference posts = database.getReference("allUsers");
//this code for keep posts even app offline until the app online again
posts.keepSynced(true);
Post post = new Post();
post.setFirstName(firstName);
post.setLastName(lastName);
post.setAge(Age);
post.setDateOfBirth(dayOfBirth);
post.setDadName(dadName);
post.setMomName(momsName);
post.setDateOfDeath(DateOfDeath);
post.setDeathLocation(deathLocation);
posts.push().setValue(post);
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/EventInfoActivity.java
package com.shlomisasportas;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class EventInfoActivity extends AppCompatActivity {
String data;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_info);
data = getIntent().getStringExtra("event");
tv = (TextView) findViewById(R.id.info);
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = mFirebaseDatabase.getReference("allUsers").child(getIntent().getStringExtra("key"));
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String firstname = (String)dataSnapshot.child("firstName").getValue();
String lastname = (String)dataSnapshot.child("lastName").getValue();
data =data + "\nשם פרטי:"+firstname+
"\nשם משפחה: "+lastname;
tv.setText(data);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
<file_sep>/app/src/main/java/com/shlomisasportas/AddNewUserActivity.java
package com.shlomisasportas;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.icu.text.SimpleDateFormat;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
import java.util.Locale;
public class AddNewUserActivity extends AppCompatActivity {
DatePickerDialog.OnDateSetListener date,date2;
Calendar myCalendar = Calendar.getInstance();
EditText dob, age, lastName, firstName, dadName, momName, deathLocation, deathDate, profilepicURL,
part, row, city, gravenumber, parcel, latitude, longitude;
Button add;
CheckBox auto;
GPSTracker gpsTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_user);
gpsTracker = new GPSTracker(this);
date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
date2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel2();
}
};
if (Build.VERSION.SDK_INT >= 23){
if (checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,getApplicationContext(),this)) {
//You fetch the Location here
//code to use the
}
else
{
requestPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,getApplicationContext(),this);
}
}
auto = (CheckBox) findViewById(R.id.auto);
auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked){
longitude.setText(gpsTracker.getLongitude()+"");
latitude.setText(gpsTracker.getLatitude()+"");
}else {
latitude.setText("");
longitude.setText("");
}
}
}
);
parcel = (EditText) findViewById(R.id.parcel);
part = (EditText) findViewById(R.id.part);
gravenumber = (EditText) findViewById(R.id.gravenum);
city = (EditText) findViewById(R.id.city);
row = (EditText) findViewById(R.id.row);
dob = (EditText) findViewById(R.id.dob);
age = (EditText) findViewById(R.id.age);
lastName = (EditText) findViewById(R.id.lastName);
firstName = (EditText) findViewById(R.id.firstName);
dadName = (EditText) findViewById(R.id.dadName);
momName = (EditText) findViewById(R.id.momName);
deathDate = (EditText) findViewById(R.id.deathDate);
deathLocation = (EditText) findViewById(R.id.deathLocation);
profilepicURL = (EditText) findViewById(R.id.profilepicurl);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
add = (Button) findViewById(R.id.add);
dob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DatePickerDialog(AddNewUserActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
deathDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DatePickerDialog(AddNewUserActivity.this, date2, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (dob.getText().toString().equals("") || age.getText().toString().equals("") ||
lastName.getText().toString().equals("") || firstName.getText().toString().equals("") ||
dadName.getText().toString().equals("") || momName.getText().toString().equals("") ||
deathDate.getText().toString().equals("") || deathLocation.getText().toString().equals("") ||
profilepicURL.getText().toString().equals("") || city.getText().toString().equals("")
|| row.getText().toString().equals("") || gravenumber.getText().toString().equals("")
|| parcel.getText().toString().equals("") ||part.getText().toString().equals("")
|| latitude.getText().toString().equals("") || longitude.getText().toString().equals("")){
Toast.makeText(AddNewUserActivity.this, "נדרש למלא את כל השדות", Toast.LENGTH_LONG).show();
}else{
addData(firstName.getText().toString(), lastName.getText().toString(), dob.getText().toString(),
age.getText().toString(), deathDate.getText().toString(), deathLocation.getText().toString(),
momName.getText().toString(), dadName.getText().toString(), profilepicURL.getText().toString());
finish();
Toast.makeText(AddNewUserActivity.this,"הפרופיל נוצר", Toast.LENGTH_LONG).show();
}
}
});
}
private void updateLabel() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
dob.setText(sdf.format(myCalendar.getTime()));
}
private void updateLabel2() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
deathDate.setText(sdf.format(myCalendar.getTime()));
}
public void addData(String firstName,String lastName,String dayOfBirth,String Age,String DateOfDeath,
String deathLocation,String momsName,String dadName,String profilepicture){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference posts = database.getReference("allUsers");
//this code for keep posts even app offline until the app online again
posts.keepSynced(true);
Post post = new Post();
post.setFirstName(firstName);
post.setLastName(lastName);
post.setAge(Age);
post.setDateOfBirth(dayOfBirth);
post.setDadName(dadName);
post.setMomName(momsName);
post.setDateOfDeath(DateOfDeath);
post.setDeathLocation(deathLocation);
post.setProfilePicture(profilepicture);
post.setCity(city.getText().toString());
post.setGravenumber(gravenumber.getText().toString());
post.setRow(row.getText().toString());
post.setParcel(parcel.getText().toString());
post.setPart(part.getText().toString());
post.setLatitude(latitude.getText().toString());
post.setLongitude(longitude.getText().toString());
posts.push().setValue(post);
}
public void requestPermission(String strPermission,Context _c,Activity _a){
if (ActivityCompat.shouldShowRequestPermissionRationale(_a,strPermission)){
Toast.makeText(AddNewUserActivity.this,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(_a,new String[]{strPermission},1);
}
}
public static boolean checkPermission(String strPermission,Context _c,Activity _a){
int result = ContextCompat.checkSelfPermission(_c, strPermission);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// fetchLocationData();
} else {
Toast.makeText(getApplicationContext(),"Permission Denied, You cannot access location data.",Toast.LENGTH_LONG).show();
finish();
}
break;
}
}
}
| 1fa97fecd0ef5b81f7fe97fea7747c2aa13fa796 | [
"Java"
] | 7 | Java | osher30/MemorialPath1 | 944c6bfb4161fc7b7852157faecfcf18c0e32216 | 695f8669b8d72a1e7476b8bf7973573ab8de45fa |
refs/heads/master | <repo_name>Taufansa/yumfood<file_sep>/app/Http/Controllers/TagController.php
<?php
namespace App\Http\Controllers;
use App\Http\Resources\TagResource;
use App\Tag;
use Illuminate\Http\Request;
class TagController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//method show all Tags
return TagResource::collection(Tag::paginate());
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//method insert tags
//15 minutes
try {
if (is_null($request->name)) {
$msg = [
'message' => 'null',
'status' => 205
];
return $msg;
}
$request->validate([
'name' => 'required',
]);
$data = Tag::create($request->all());
if ($data) {
$msg = [
'message' => 'insert succes',
'status' => 200
];
} else {
$msg = [
'message' => 'insert fail',
'status' => 205
];
}
return $msg;
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//method show Tag
//5 minutes
try {
$data = Tag::find($id);
if ($data) {
return $data;
} else{
$msg = [
'message' => 'data not found',
'status' => 205
];
return $msg;
}
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//method update tag
//10 minutes
try {
if (is_null($request->name)) {
$msg = [
'message' => 'null',
'status' => 205
];
return $msg;
}
$request->validate([
'name' => 'required'
]);
$find = Tag::find($id);
if ($find) {
$data = Tag::where('id',$id)->update(['name'=>$request->name]);
if ($data) {
$msg = [
'message' => 'update succes',
'status' => 200
];
} else {
$msg = [
'message' => 'update fail',
'status' => 205
];
}
return $msg;
} else{
$msg = [
'message' => 'data not found',
'status' => 205
];
return $msg;
}
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//method delete tag
//5 minutes
try {
$data = Tag::destroy($id);
if ($data > 0) {
$msg = [
'message' => 'delete succes',
'status' => 204
];
}else {
$msg = [
'message' => 'delete fail',
'status' => 205
];
}
return $msg;
} catch (Throwable $e) {
report($e);
return false;
}
}
}
<file_sep>/app/Http/Controllers/VendorController.php
<?php
namespace App\Http\Controllers;
use App\Http\Resources\VendorResource;
use App\Vendor;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class VendorController extends Controller
{
/**
* Display a listing of the resource.
*
* @return AnonymousResourceCollection
*/
public function index()
{
//method show all vendors
return VendorResource::collection(Vendor::paginate());
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//method insert vendor
//15 minutes
try {
if (is_null($request->name)) {
$msg = [
'message' => 'null',
'status' => 205
];
return $msg;
}
$request->validate([
'name' => 'required|max:128',
]);
$data = Vendor::create($request->all());
if ($data) {
$msg = [
'message' => 'insert succes',
'status' => 200
];
} else {
$msg = [
'message' => 'insert fail',
'status' => 205
];
}
return $msg;
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//method show vendor
//5 minutes
try {
$data = Vendor::find($id);
if ($data) {
return $data;
} else{
$msg = [
'message' => 'data not found',
'status' => 205
];
return $msg;
}
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//method update vendor
//10 minutes
try {
if (is_null($request->name)) {
$msg = [
'message' => 'null',
'status' => 205
];
return $msg;
}
$request->validate([
'name' => 'required|max:128'
]);
$find = Vendor::find($id);
if ($find) {
$data = Vendor::where('id',$id)->update(['name'=>$request->name]);
if ($data) {
$msg = [
'message' => 'update succes',
'status' => 200
];
} else {
$msg = [
'message' => 'update fail',
'status' => 205
];
}
return $msg;
} else{
$msg = [
'message' => 'data not found',
'status' => 205
];
return $msg;
}
} catch (Throwable $e) {
report($e);
return false;
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//method delete vendor
//5 minutes
try {
$data = Vendor::destroy($id);
if ($data > 0) {
$msg = [
'message' => 'delete succes',
'status' => 204
];
}else {
$msg = [
'message' => 'delete fail',
'status' => 205
];
}
return $msg;
} catch (Throwable $e) {
report($e);
return false;
}
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::prefix('v1')->group(function () {
Route::apiResource('vendors', 'VendorController');
Route::post('/vendors/insert','VendorController@store');
Route::get('/vendors/show/{id}','VendorController@show');
Route::patch('/vendors/update/{id}','VendorController@update');
Route::delete('/vendors/delete/{id}','VendorController@destroy');
Route::apiResource('tags', 'TagController');
Route::post('/tags/insert','TagController@store');
Route::get('/tags/show/{id}','TagController@show');
Route::patch('/tags/update/{id}','TagController@update');
Route::delete('/tags/delete/{id}','TagController@destroy');
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
| d4b9faf0019e0b5572552f545c6324e31d7d9db7 | [
"PHP"
] | 3 | PHP | Taufansa/yumfood | 41ddfae6dc7fd0965b1039dd3fff46af37419371 | 3a91f35b6aa9f044c887b285c8728e7eff2b7129 |
refs/heads/master | <repo_name>haoxunba/knowledge<file_sep>/LocalDevelopServer/Nginx.md
# Nginx for Window
## Nginx简介
nginx是一款开源的高性能的http服务器和反向代理服务器,也就是说Nginx本身就可以托管网站(类似于Tomcat一样),进行Http服务处理,也可以作为反向代理服务器使用,从而达到网站的负载均衡。
阿里技术团队http://tengine.taobao.org/book
`nginx -s stop` fast shutdown
`nginx -s quit` graceful shutdown
`nginx -s reload` changing configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processes
`nginx -s reopen` re-opening log files
## 我目前的配置
1. 打开`conf/nginx.conf`
2. 自定义server下面的listen端口号
3. 更改root D:source为自己的项目路径,路径要配到html文件的上一级
4. 打开命令行,同时将路径切换到当前nginx所在文件
4. 命令行检测nginx.conf配置文件是否合法`nginx -t -c conf/nginx.conf`
5. 命令行`start nginx`
## Nginx配置反向代理服务器
使用Nginx和Tomcat来搭建高性能负载均衡集群,即使用Nginx的反向代理功能来实现请求的分发
下面的案例是使用tomcat来模拟目标主机,通过nginx搭建反向代理服务器,从而转发请求到真实的tomcat服务器
```
upstream tomcatserver1 {
server 192.168.72.49:8081;
}
upstream tomcatserver2 {
server 192.168.72.49:8082;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://tomcatserver1;
index index.html index.htm;
}
}
server {
listen 81;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://tomcatserver2;
index index.html index.htm;
}
}
```
`upstream tomcatserver1` 配置服务器集群, 可以配置多个服务器,通过weight设置不同服务器的权重
`proxy_pass http://tomcatserver1` 代理服务器转发请求,后面的就是集群的名字
https://www.cnblogs.com/xingzc/p/5753030.html(里面还详细介绍反向代理服务器的优点)
## FQA
1. 什么情况下access.log才会有内容
在浏览器中输入连接向服务器发送请求的时候才会有内容
2. 假如我将listen的端口从9001改为9002时,为什么9001还是可以正常起作用
因为是在任务管理器中开了多个nginx.exe进程,需要将原来的进程关闭才能避免上面的情况出现
> 通过命令行关闭所有相同进程的命令
1. win+r 输入powershell(注意不是cmd命令)
2. 输入ps命令,查看当前所有进程
3. 结束单个进程命令: kill + 进程名称前面的id
4. 结束多个相同进程命令: `taskkill /F /IM nginx.exe`(注意空格位置)
3. nginx默认端口80会隐藏
默认端口打开文件时`localhost:80/index.html`,实际的浏览器会将80隐藏`localhost/index.html`
4. 端口被占用
情形1: 设置8080端口(或其他端口时)会跳转到别的页面,而不跳转到nginx配置的页面,并且nginx没有任何反应,log文件没有任何信息响应,也不会报错;
情形2: 设置设置8080端口(或其他端口时)访问不到页面,打开error.log可以看到报错错误信息是`bind() to 0.0.0.0:80 failed (10013: An attempt was made to access a socket in a way forbidden by its access permissions)`
上面两种情形可以理解端口被占用,解决办法
运行–cmd
```
C:\>netstat -aon|findstr "8080"
TCP 127.0.0.1:80 0.0.0.0:0 LISTENING 2448
```
端口被进程号为2448的进程占用,继续执行下面命令:
```
C:\>tasklist|findstr "2448"
```
```
thread.exe 2016 Console 0 16,064 K
```
很清楚,thread占用了你的端口,Kill it
如果第二步查不到,那就开任务管理器,进程—查看—选择列—pid(进程位标识符)打个勾就可以了
看哪个进程是2448,然后杀之即可。
另外,强制终止进程: CMD命令: `taskkill /F /pid 1408`; powershell命令 `kill 1480`
其实上面我都还没解决问题 最后发现有个http.d 这个是apache的进程 结束了这个进程nginx才启动了
如果朋友们使用的phpstudy这个集成软件,那么你在使用它的nginx的时候就要注意了,如果你的listen端口不是80,但是还是出现了上述的错误,那么你要去看看 include vhost.conf里的配置
https://www.cnblogs.com/YangJieCheng/p/5843660.html
<file_sep>/CSS/CSSModules.md
# CSS Modules
本文主要介绍原生的css modules和React Css Modules
## css modules
### 局部作用域
```javascript
import React from 'react';
import style from './App.css';
export default () => {
return (
<h1 className={style.title}>
Hello World
</h1>
);
};
```
> 将类名添加到`style`(这里的`style`必须是引入`App.css`对应的变量)对象上,通过构建工具编译成哈希值,这样类名独一无二,实现局部作用域
```
<h1 class="_3zyde4l1yATCOkgn-DBWEL">
Hello World
</h1>
```
### 配合webpack应用
CSS Modules 提供各种[插件](https://github.com/css-modules/css-modules/blob/master/docs/get-started.md),支持不同的构建工具。其中构建工具Webpack 的[`css-loader`](https://github.com/webpack/css-loader#css-modules)插件对 CSS Modules 的支持最好
**webpack配置文件**
```
module.exports = {
module: {
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1 // 0 => 无 loader(默认); 1 => postcss-loader; 2 => postcss-loader, sass-loader,
localIdentName: '[local]---[hash:base64:5]'
}
},
'postcss-loader',
'sass-loader'
]
}
};
```
> 关键就是在插件`css-loader`后添加查询参数`modules`从而调用`css-modules`
### 添加多个类名
```
<div className={value.class + " " + value.class2}>{value.value}</div>
```
拼接字符串啊……
要不喜欢的话用字符串模板也行啊
```
<div className={`${value.class} ${value.class2}`}>{value.value}</div>
```
花括号里面就是可以运算的部分,注意两个类名之间要有空格
如果是数组的话直接join也行啊
```
<div className={classnames.join(" ")}>{value.value}</div>
```
本文最后提到的classnames插件也是可以做到的,这种插件办法对于动态判断添加类名是非常适合的
### 全局作用域
CSS Modules 允许使用:global(.className)的语法,声明一个全局规则。凡是这样声明的class,都不会被编译成哈希字符串。
App.css加入一个全局class。
```
.title {
color: red;
}
:global(.title) {
color: green;
}
```
App.js使用普通的class的写法,就会引用全局class。
```
import React from 'react';
import styles from './App.css';
export default () => {
return (
<h1 className="title">
Hello World
</h1>
);
};
```
CSS Modules 还提供一种显式的局部作用域语法:local(.className),等同于.className,所以上面的App.css也可以写成下面这样。
```
:local(.title) {
color: red;
}
:global(.title) {
color: green;
}
```
CSS Modules 是一个可以被多种方法实现的规范。react-css-modules 利用 webpack css-loader 所提供的功能启用了现有的 CSS Modules 的集成。
其实多数情况下,我们很少定义全局作用域的样式,我们通常会把用到的全局作用域的样式全部放到一个单独的文件中,然后在入口文件进行一个全局的引入。
### 定制哈希类名
上面的案例在引入css-loader时,在它的options中除了用到modules,还有一个属性localIdentName就是用来定时哈希类名的
```
module: {
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1 // 0 => 无 loader(默认); 1 => postcss-loader; 2 => postcss-loader, sass-loader,
localIdentName: '[local]---[hash:base64:5]'
}
},
'postcss-loader',
'sass-loader'
]
}
```
也可以这样定义
```
localIdentName=[path][name]---[local]---[hash:base64:5]
```
编译的结果就类似于
```
demo03-components-App---title---GpMto
```
### 利用composes进行class的组合
在 CSS Modules 中,一个选择器可以继承另一个选择器的规则,这称为"组合"("composition")。
在App.css中,让.title继承.className 。
```
.className {
background-color: blue;
}
.title {
composes: className;
color: red;
}
```
App.js不用修改。
```
import React from 'react';
import style from './App.css';
export default () => {
return (
<h1 className={style.title}>
Hello World
</h1>
);
};
```
App.css编译成下面的代码。
```
._2DHwuiHWMnKTOYG45T0x34 {
color: red;
}
._10B-buq6_BEOTOl9urIjf8 {
background-color: blue;
}
```
相应地, h1的class也会编译成`<h1 class="_2DHwuiHWMnKTOYG45T0x34 _10B-buq6_BEOTOl9urIjf8">`。
选择器也可以继承其他CSS文件里面的规则。
another.css
```
.className {
background-color: blue;
}
```
App.css可以继承another.css里面的规则。
```
.title {
composes: className from './another.css';
color: red;
}
```
### 输入变量
CSS Modules 支持使用变量,不过需要安装 `PostCSS` 和 `postcss-modules-values`。
```
$ npm install --save postcss-loader postcss-modules-values
```
把postcss-loader加入webpack.config.js。
```
var values = require('postcss-modules-values');
module.exports = {
entry: __dirname + '/index.js',
output: {
publicPath: '/',
filename: './bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader?modules!postcss-loader"
},
]
},
postcss: [
values
]
};
```
接着,在colors.css里面定义变量。
```
@value blue: #0c77f8;
@value red: #ff0000;
@value green: #aaf200;
```
App.css可以引用这些变量。
```
@value colors: "./colors.css";
@value blue, red, green from colors;
.title {
color: red;
background-color: blue;
}
```
## react-css-modules
webpack [css-loader](https://github.com/webpack/css-loader#css-modules) itself has several disadvantages:
* You have to use `camelCase` CSS class names.
* You have to use `styles` object whenever constructing a `className`.
* Mixing CSS Modules and global CSS classes is cumbersome.
* Reference to an undefined CSS Module resolves to `undefined` without a warning.
### styleName
<b>React CSS Modules component automates loading of CSS Modules using `styleName` property</b>
Using `react-css-modules`:
* You are warned when `styleName` refers to an undefined CSS Module ([`errorWhenNotFound`](https://www.npmjs.com/package/react-css-modules#errorwhennotfound)option).
* You can enforce use of a single CSS module per `ReactElement` ([`allowMultiple`](https://www.npmjs.com/package/react-css-modules#allowmultiple) option).
<b>allowMultiple</b>
Default: false.
Allows multiple CSS Module names.
When false, the following will cause an error:
```
<div styleName='foo bar' />
```
<b>errorWhenNotFound</b>
Default: true.
Throws an error when styleName cannot be mapped to an existing CSS Module.
```javascript
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';
class Table extends React.Component {
render () {
return <div styleName='table'>
<div styleName='row'>
<div styleName='cell'>A0</div>
<div styleName='cell'>B0</div>
</div>
</div>;
}
}
export default CSSModules(Table, styles);
```
强制是否使用单一的css模块
```javascript
export default createCSSModules(Login, styles, {
allowMultiple: true
});
```
<font color="blue"> `className`不能直接用less里面的类名,是因为在执行该处代码的时候,类名已经被编译过了,所以直接拿是拿不到的。 但是`styleName`里面是可以直接写类名的,因为他拿到类名自己会进行编译,得到的结果和之前`createCSSModules`编译的结果相同。</font>
### 同样需要webpack配合
```javascript
//webpack配置文件 webpack.config.js
loaders: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, '../src'),
],
loader: 'babel-loader',
}, {
test: /\.less$/,
loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!less'
}
]
```
根据上面的配置,生成的类名类似于
```html
<div class="table__table___32osj">
<div class="table__row___2w27N">
<div class="table__cell___1oVw5">A0</div>
<div class="table__cell___1oVw5">B0</div>
</div>
</div>
```
### classnames
https://www.npmjs.com/package/classnames
主要应用场景就是需要提前**对多个类名进行批量处理**,然后通过变量返回类名集合
#### 配合styleName应用
```javascript
import classNames from 'classnames';
...
getWrapperClass = () => {
let { block, fixed, full } = this.props;
let config = {
full,
'btn-wrapper': true,
[`btn-wrapper${block ? '-block' : ''}`]: true,
};
if (fixed) {
config = Object.assign(config, {
[`fixed-${fixed}`]: true,
});
}
return classname(config)
}
render() {
const clsName = classname(class1, class2, { 'hideKeyboard': !this.state.showKeyboard });
return(
<div styleName={ this.getWrapperClass()} onClick={ this.closeModel}>
<div styleName={clsName}></div>
</div>
)
}
```
`styleName`也可以实现和`classnames`等同的效果,批量处理类名作用,不过可读性维护性不好
```
// 多个类名之间用空格分开
<section styleName={this.props.modalPosition ? 'msgBox' : 'msgBox-Postion msgBox'}>
```
## 参考
http://www.ruanyifeng.com/blog/2016/06/css_modules.html
[react-css-module-npm](https://www.npmjs.com/package/react-css-modules#the-implementation)
[react-css-module-中文翻译](https://segmentfault.com/a/1190000004530909)<file_sep>/jQuery/jQuery基础知识.md
# jQuery
> - jquery中一般获取的都是匹配到的元素集合中第一个元素,而设置添加的话则是对匹配到的元素集合中每个元素都设置
## jQuery基础介绍
### jQuery解决问题
1. window.onload 事件只能出现一次
2. 浏览器兼容性问题
3. 简单功能实现很繁琐
4. 属性或方法的名字很长容易出错、
### 版本介绍
v1.xx 版本: 兼容 IE6-8,以及其他浏览器
> 如果你需要兼容IE6-8,你可以继续使用1.12版本。
v2.xx 和 v3.xx 版本: 兼容 IE9+, 以及其他浏览器
### jquery和js入口函数区别
- 加载个数
js只能加载一个,jquery可以加载多个
- 执行时机
这些文件资源包括:页面文档、外部的js文件、外部的css文件、图片等。
jQuery的入口函数,是在文档加载完成后,就执行。文档加载完成指的是:DOM树加载完成后,就可以操作DOM
```
window.onload = function() {}
```
```
$(document.ready(function() {}))
$(function() {})
```
### jquery对象和DOM对象相互转换
```
var demo = document.getElementById('demo');
var $('demo') = $(demo);
var demo = $('demo')[0];
var demo = $('demo').get(0);
```
## 选择器
### 原生js
```
var demo = document.getElementById('demo');
var demo = document.getElementByTagName('demo')
```
### jquery
```
$('#id')
$('.class')
$('div')
$('div p') // 后代选择器
$('ul>li') // 父子选择器
$('div1,div2.div3')
$('li:eq(3)') // 伪类选择器
$('li:even')
$('li:odd')
$('li:first')
$('li:last')
$(':checkbox') // 表单选择器
$(':checked')
$(':text')
$('li[id]') // 属性选择器
$("li[id='']") //
```
### jquery 通过方法获取DOM元素
```
$('div').parent() // 获取直接父级
$('div').parent('p') // 获取父级中所有的p标签,直到tml
$('div').children() // 获取直接子级
$('div').find('span') // 获取所有后代span元素,用的较多
$('div').siblings() // 获取所有兄弟节点
$('div').next() // 获取下一个兄弟节点
$('div').nextAll() // 获取后面所有的兄弟节点
$('div').prev()
$('div').prevAll()
$('div').eq(n) // 获取第n个div
$('div').first()
$('div').last()
$('div').filter('.class') // 获取所有包含class类名的div
$('div').not('.class') // 同上相反
$('div:eq(n)').index() // 获取当前元素的索引号
```
## jquery操作DOM方法
jquery方法和原生js方法不能通用
### 操作样式
#### 基本样式操作
```
$('div').css('color','red');
$('div').css({'color': 'red', 'font-size': '16px'});
$('div').css('color');
```
> ** 设置的样式为行内式, 获取的样式包括行内和外部css **
#### 类样式操作
```
$('div').addClass('demo');
$('div').removeClass('demo');
$('div').hasClass('demo'); // true false
$('div').toggleClass('demo'); //有就除,没有就加
```
> - 添加、移除、切换样式都可以传多个参数,如`demo1 demo2 demo3`
> - `addClass`还可以传函数参数,应用场景就是针对jquery的DOM集合条件性的添加或移除类
> ```
div.addClass(function(index, currentClass) {
// index jquery伪数组中当前元素所在的下标
// currentClass 当前元素的类名
if(currentClass !== 'dubble') {
return 'select'
}
})
```
#### 尺寸样式
- `height()` `width()`
设置时传递的常用参数格式是`300 '300px'`,还有一种也可以但不常用`'300'`
```
$('div').height(); //获取值为数值类型
$('div').width();
```
```
// 下述不适用于window document
$('div').innerWidth() // 获取的宽度值包括padding
$('div').innnerHeight()
$('div').outWidth() // 获取宽度值包括padding和border
$('div').outHeight()
$('div').outWidth(true) // 获取的宽度值包括padding和border和margin
$('div').outHeight(true)
```
> 上述六中方法方法存在许多争议,建议不要使用
#### 坐标值
```
$('div').offset(); // 获取相对于文档左上角(document)位置 分为left值和top值
```
- position
> 获取相对于offset parent的(该元素最近的定位祖先元素)位置
> 返回值是一个包括left和top属性的对象
> 如果没有定位的祖先元素那么作用和`.offset()`相同
```
$('div').position(); // 获取相对于offset parent的(该元素最近的定位祖先元素)位置
```
```
$('div').scrollLeft();
$('div').scrollTop(); // 获取或设置相当于滚动条顶部的位置
```
### jquery动画
#### 显示、隐藏、滑入、滑出、淡入、淡出
```
$('div').show() // 默认显示,没有动画效果
$('div').show(slow) // slow对应600ms normal对应400ms fast对应200ms
$('div').show(2000) // 也可以自定义输入动画执行时间
$('div').show(2000, callback) // 可以添加回调函数
```
`后面的`hide slideDown slideUp slideToggle fadeIn fadeOut fadeToggle animate`所传的参数和上面的`show`相同
#### animate自定义动画
```
$('div').animate({params}, speed, callback)
// {params} 代表css属性,必传参数,并且对应属性值去掉单位必须是数值型
// speed 动画执行时间,可选参数,不写就代表动画立即执行
// callback 动画回调函数,可选参数,动画执行完之后做的事情
```
#### stop停止动画
```
$('div').stop(arg1, arg2)
// arg1 布尔值 是否清空后续的动画 可选参数 默认false
// arg2 布尔值 是否立即执行完当前动画 可选参数 默认false
```
### 节点操作
#### 获取节点
```
$('div').html();
$('div').text();
$('div').offsetParent(); // 获取最近的定位的祖先元素
```
#### 创建节点
```
var $span = $('<span></span>')
$('div').html('<span></span>')
$('div').text('文本')
$('div').clone() // 深拷贝
```
#### 添加节点
```
$('div').html($span);
$('div').text('文本');
$('div').append('<span></span>');
$('div').append($('span')); // 将span追加到div中
$('span').appendTo($div); // 同上相反
$('span').prepend($div); // 将span添加到div的第一个节点前面
$('span').first($div); // 将span作为兄弟元素添加到div前面
$('span').after($div); // 同上相反
```
- 如果`span`元素已经存在,则从原来位置删除,添加到`div`中去
#### 删除节点
```
$('div').html('');
$('div').empty(); // 这两个表示清空div的子节点
$('div').remove(); // 表示清空所有包括自己
```
### 属性操作
```
$('div').attr('data-key'); // 获取
$('div').attr('data-key', 'hello'); // 设置
$('div').removeAttr('data-key'); // 移除
```
> _对于表单的`disabled checked selected`等动态状态要使用`prop()`代替`attr()`_
### form表单
```
$('input').val(); // 获取
$('input').val('hello'); // 设置
```
## jquery事件
### 鼠标事件
#### click
```
<script>
$('div').click(function() {
console.log('执行了吗');
$(this).addClass('select');
})
</script>
```
> <font color="red">函数中的this是原生DOM中的,一定要转换成jquery,才能调用jquery的方法</font>
#### scroll
```
$('div').scroll(function);
```
## jquery补充
## jquery插件
<file_sep>/jQuery/jquery插件.md
## [jQuery.color](https://github.com/jquery/jquery-color)
该插件利用cssHack解决`jquery.animate()`不能改变背景色的问题
```
<body>
<div>
jquery插件主要弥补jquery动画不能改变背景色,提供一种cssHack
</div>
<script src="../jquery-3.2.1.js"></script>
<script src="./jquery.color.js"></script>
<script>
$('div').click(function() {
$(this).animate({"backgroundColor": "red"}, 2000);
})
</script>
</body>
```
## [jquery.lazyload](https://github.com/tuupola/jquery_lazyload)
懒加载插件,会等到图片进入浏览器的可视区域后,才会加载图片
否则,是不会加载图片的!
### data-original属性
原理:把真实的图片路径放到了 data-original 属性中
lazyload插件会在内部解析 data-original 属性,判断如果图片进入了
可视区域,它会将 data-original 的值,设置为 图片的src属性
```
<body>
<img class="lazy" data-original="img/example.jpg" width="640" height="480">
<script src="jquery.js"></script>
<script src="jquery.lazyload.js"></script>
<script>
$(function() {
$("img.lazy").lazyload();
});
</script>
</body>
```
> 注意:图片`img`必须设置尺寸
### 其他属性
语法就是
```
$("img.lazy").lazyload({
effect: "fadeIn"
})
```
- `placeholder : "img/grey.gif"`, 用图片提前占位
placeholder,值为某一图片路径.此图片用来占据将要加载的图片的位置,待图片加载时,占位图则会隐藏,里面是一个字符串,不用发送请求。
- `effect: "fadeIn"`, 载入使用何种效果
effect(特效),值有show(直接显示),fadeIn(淡入),slideDown(下拉)等,常用fadeIn
- `threshold: 200`, 提前开始加载
threshold,值为数字,代表页面高度.如设置为200,表示滚动条在离目标位置还有200的高度时就开始加载图片,可以做到不让用户察觉
- `event: 'click'`, 事件触发时才加载
event,值有click(点击),mouseover(鼠标划过),sporty(运动的),foobar(…).可以实现鼠标莫过或点击图片才开始加载,后两个值未测试…
- `container: $("#container")`, 对某容器中的图片实现效果
container,值为某容器.lazyload默认在拉动浏览器滚动条时生效,这个参数可以让你在拉动某DIV的滚动条时依次加载其中的图片
- `failurelimit : 10` 图片排序混乱时
failurelimit,值为数字.lazyload默认在找到第一张不在可见区域里的图片时则不再继续加载,但当HTML容器混乱的时候可能出现可见区域内图片并没加载出来的情况,failurelimit意在加载N张可见区域外的图片,以避免出现这个问题.
<file_sep>/Javascript高级程序设计/第二章/2.1.2defer.js
setTimeout(function() {
var div = document.getElementsByTagName('div')[0];
div.style.color='red';
console.log('我是defer1的内容');
}, 2000);<file_sep>/jQuery/jquery源码/测试代码/整体架构/整体架构.md
## jQuery整体轮廓
jQuery中以40行为分界线,整体就是匿名函数自执行
```
(function(global, factory) {
})(global, function() { // 第40行的位置
// jquery代码一万多行主体
})
```
> 下面jQuery1.X的版本的架构和现在的略有不同
```
(function() {
var a = 10;
function $() {
alert(a);
}
window.$ = $; // 将内部的变量挂载到window,使外面也可以访问
})()
$();
```
> 演绎 模仿jquery3
```
// 如果添加一个判断条件来判断匿名函数是否执行
(function(fn) {
if(true) {
fn()
}
})(function() {
console.log('原来的匿名函数执行主体部分');
})
```
## 分行标注源码功能块
### 14-40
针对`CommmonJS`环境
### 48 - 113
定义变量 重点是定义jQuery
```
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
},
```
一般我们在使用jquery时是`$().css() $().html()`等等,又因为在1029代码行`$ === jquery`,所以每次执行`$()`就相当于`new jQuery.fn.init( selector, context );`,所以`$()`其实就是一个对象,才会调用后面定义的方法。
> 面向对象`new`,如
```
var array = new Array();
array.push();
array.sort();
```
此时array就是对象
### 115-196
```
jQuery.fn = jQuery.prototype = { ... }
```
结合 3036代码行 `init.prototype = jQuery.fn`确定jquery的原型就是`jquery.fn`就是`jquery.prototype`
里面定义了一些jquery的实例方法
下面是一个他们之间关系图
、、、、、
### 198 - 265
`jQuery.extend = jQuery.fn.extend = function() {}`
jquer的继承方法,通过`extend`挂在到jquery上
### 267 - 513
`jQuery.fn({ })`
扩展工具方法,也叫静态方法
### 541 - 2794
`Sizzle` 复杂选择器
### 10249
`window.jQuery = window.$ = jQuery;`
<file_sep>/CSS/移动端自适应.md
# 移动端自适应
## DPR
什么是 DPR?
我们知道在 Chrome 浏览器控制台 console 中输入`window.devicePixelRatio`
可以获取当前屏幕的 DPR。
那么什么是 DPR (Device Pixel Ratio)?这里不妨先给它个定义:window.devicePixelRatio 是设备上物理像素 (physical pixels) 和设备无关像素 (device-independent pixels (dips)) 的比例。公式表示就是:window.devicePixelRatio = physical pixels / dips
这个定义里的 dips 并不太好理解,现在我们尝试通过下面几点来搞明白:
- 首先,dips 是一种度量单位
- 然后,要知道浏览器并不是根据物理硬件的像素来工作的,而是根据 dips 宽度来工作。
- 最后,还要知道 dips 是将像素值与实际距离联系起来的,不管屏幕的像素密度是多少,dips 为 1px,那么实际宽度就是 1px,也就是对应 CSS 中的 1px,而不是对应物理像素 1px。
这里我们就可以看到,1px 并不总是等于 1px。
下面这个例子非常重要
搞明白 dips,我们举个简单例子,MacBook Pro 13.3 英寸的显示器分辨率是 2560 x 1600,这个 2560px 就是我们前面说的设备上的物理像素值,而浏览器全屏显示的宽度只有 1280px,这个就是 dips 值,最终可以知道这台 MacBook Pro 电脑屏幕的 DPR 为 2,DPR 在这里所表达的意思就是:1280 dips 在实际显示的时候,被硬件扩展到了 2560 的硬件像素宽度,2 个物理像素对应 1 个 CSS 像素(这个指的水平方向或垂直方向,如果在一个平面内的话 4 个物理像素点对应 1 个 CSS 像素点)。
如果现在上面这台电脑里有一张实际宽度为 200px 的高清图片,在浏览器里被 css 设置宽度为 200px,那么这张图片看起来就会有点模糊,因为它实际被硬件扩展到了 400px 的硬件像素宽度,是它实际宽度的两倍。但是,如果它被 css 设置宽度为 100px,这时候它实际被硬件扩展到了 200px 的硬件像素宽度,和它实际像素一致,就不会模糊了。
根据上面案例可以理解到,一般设计图是640px或者750px,但是设备的dips是320px或375px,所以我们在设置样式的时候会将设计图除以2,得到需要操作的css像素<file_sep>/CSS/normalize.md
# normalize.css
是一个包文件,一个体积非常小的css文件,主要解决不同浏览器默认样式的差异,同时对HTML5元素、排版、列表、嵌入的内容、表单和表格都进行了一般化
相比css Reset,它的特点是
保护有用的浏览器默认样式而不是完全去掉它们
一般化的样式:为大部分HTML元素提供
修复浏览器自身的bug并保证各浏览器的一致性
优化CSS可用性:用一些小技巧
解释代码:用注释和详细的文档来
## Usage
可以通过npm安装
```
npm install --save normalize.css
```
因为文件体积很小,也可以不要安装直接将css复制出来,放在自定义的css里面,并在入口处导入
https://github.com/necolas/normalize.css<file_sep>/React/LifeCycle.md
# Lifecycle
## 三种Lifecycle
### Mounting
These methods are called when an instance of a component is being created and inserted into the DOM:
```
constructor()
componentWillMount()
render()
componentDidMount()
```
### Updating
An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:
```
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
```
### Unmounting
This method is called when a component is being removed from the DOM:
```
componentWillUnmount()
```
> 在life cycle中定义的方法叫做各自生命周期的 “lifecycle hooks”.
mountComponent 本质上是通过 **递归渲染** 内容的,由于递归的特性,父组件的 componentWillMount 一定在其子组件的 componentWillMount 之前调用,而父组件的 componentDidMount 肯定在其子组件的 componentDidMount 之后调用。
# 说明
生命周期共提供了10个不同的API。
## getDefaultProps
作用于组件类,只调用一次,返回对象用于设置默认的`props`,对于引用值,会在实例中共享。
With functions and ES6 classes `defaultProps` is defined as a property on the component itself:
```
class Greeting extends React.Component {
// ...
}
Greeting.defaultProps = {
name: 'Mary'
};
```
With `createReactClass()`, you need to define `getDefaultProps()` as a function on the passed object:
```
var Greeting = createReactClass({
getDefaultProps: function() {
return {
name: 'Mary'
};
},
// ...
});
```
## getInitialState
作用于组件的实例,在实例创建时调用一次,用于初始化每个实例的`state`,此时可以访问`this.props`。
注意: 如果组件是通过es6格式创建的,那么初始化的状态存放在constructor中,即
```
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}
```
With `createReactClass()`, you have to provide a separate `getInitialState` method that returns the initial state:
```
var Counter = createReactClass({
getInitialState: function() {
return {count: this.props.initialCount};
},
// ...
});
```
## constructor
`constructor(props)`
1.1 The constructor for a React component is called before it is mounted.
1.2 ** you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.**
1.3 The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.
1.4 It's okay to initialize state based on props if you know what you're doing. Here's an example of a valid React.Component subclass constructor:
```
constructor(props) {
super(props);
this.state = {
color: props.initialColor
};
}
```
## componentWillMount
在完成首次渲染之前调用,此时仍可以修改组件的state。
This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.
如果此时在 componentWillMount 中调用 setState,是不会触发 reRender(重新渲染),而是进行 state 合并。
## render
The render() method is required.
When called, it should examine this.props and this.state and return a single React element. This element can be either a representation of a native DOM component, such as `<div />`, or another composite component that you've defined yourself.
You can also return null or false to indicate that you don't want anything rendered. When returning null or false, ReactDOM.findDOMNode(this) will return null.
The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.
Note
render() will not be invoked if shouldComponentUpdate() returns false.
必选的方法,创建虚拟DOM,该方法具有特殊的规则:
* 只能通过`this.props`和`this.state`访问数据
* 可以返回`null`、`false`或任何React组件
* 只能出现一个顶级组件(不能返回数组)
* 不能改变组件的状态
* 不能修改DOM的输出
## componentDidMount
真实的DOM被渲染出来后调用,在该方法中可通过`this.getDOMNode()`访问到真实的DOM元素。此时已可以使用其他类库来操作这个DOM。
_在服务端中,该方法不会被调用。_
**Setting state in this method will trigger a re-rendering.**
## componentWillReceiveProps
```
componentWillReceiveProps(nextProps) {
if(this.props.parentValue != nextProps.parentValue) {
this.setState({
childValue: nextProps.parentValue
})
}
}
```
<b>不会执行的情况:</b>
mounting期间
setState更改state值
<b>执行情况:</b>
接收到新的props
<b>主要作用:</b>
对比props,设置setState
<b>其他注意事项:</b>
由于componentWillReceiveProps和componentWillMount的执行顺序都是在render之前,所以在这两个里面设置setState是不会导致re-render,只是和initialState进行合并
> If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
-
> Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.
## shouldComponentUpdate
`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when `forceUpdate()` is used.
if `shouldComponentUpdate()` returns `false`, then [`componentWillUpdate()`](), [`render()`](), and [`componentDidUpdate()`]() will not be invoked.
If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped.
<b>注意事项</b>
1. 与componentWillReceiveProps相比,不仅新的props能够触发shouldComponentUpdate,而且新的state也能够触发该周期
2. 主要应用就是对比新旧state或props,通过返回ture或false决定后续声明周期是否执行,主要是决定是否执行render
3. 不要在这里设置setState,重新设置state还会触发该周期,会陷入死循环
2. Returning `false` does not prevent child components from re-rendering when state changes.
## componentWillUpdate
接收到新的`props`或者`state`后,进行渲染之前调用,此时不允许更新`props`或`state`。
和shouldComponentUpdate一样,不要在这里设置setState,重新设置state还会触发该周期,会陷入死循环
用途
> * you might want to set a variable which might be needed for the render for this particular state
* you might want to animate your divs or
* dispatch events to clear/set your stores.
https://stackoverflow.com/questions/33075063/what-is-the-exact-usage-of-componentwillupdate-in-reactjs
## componentDidUpdate
完成渲染新的`props`或者`state`后调用,此时可以访问到新的DOM元素。
## componentWillUnmount
组件被移除之前被调用,可以用于做一些清理工作,在`componentDidMount`方法中添加的所有任务都需要在该方法中撤销,比如创建的定时器或添加的事件监听器。
# 摘录
http://react-china.org/t/react/1740
https://facebook.github.io/react/docs/react-component.html
https://zhuanlan.zhihu.com/p/20312691 <file_sep>/React/Controlled-Component.md
# Controlled Components
https://facebook.github.io/react/docs/forms.html
https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/ (官网推荐)
## 官网案例
```javascript
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
```
上述案例中注意
1. `onSubmit`的经典用法,即可以按键盘enter键触发,也可以点击submit按钮触发。
2. `event.target.value`获取当前input的值
3. `label`标签的应用
4. `event.preventDefault()`阻止submit表单默认提交事件
<b>handling Multiple Inputs</b>利用input共有的属性type和name实现
```javascript
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
```
注意一下事项
1. `event.target`的应用
2. `name`在`setState`中应用
3. 三元运算符
##
受控组件原理
input输入框输入一个值,触发onChange事件,从而调用setState函数,state的值改变触发render重新渲染,此时input的value值始终和最新的this.state的值相等
### 常见的应用场景
1. in-place feedback, like validations
2. disabling the button unless all fields have valid data
3. enforcing a specific input format, like credit card numbers
<b>不同form表单类型的获取value不同</b>
| Element | Value property | Change callbacew | value in the callback |
| ------------ | ------------ | ------------ | ------------ |
|`<input type="text" />` | value="string" | onChange | event.target.value|
|`<input type="checkbox" />` | checked={boolean} | onChange | event.target.checked|
|`<input type="radio" />` | checked={boolean} | onChange | event.target.checked|
|`<textarea />` | value="string" | onChange | event.target.value|
|`<select />` | value="option value" | onChange | event.target.value|
# Uncontroller Components
https://facebook.github.io/react/docs/uncontrolled-components.html
> In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
```javascript
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(input) => this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
```
注意点:
1. use a ref to get form values from the DOM.
2. use uncontrolled components sometimes easier to integrate React and non-React.
<b>Default Values</b>
use defaultValue instead of value attribute
```javascript
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
defaultValue="Bob"
type="text"
ref={(input) => this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
```
> Likewise, `<input type="checkbox">` and `<input type="radio"> `support `defaultChecked`, and `<select>` and `<textarea>` supports `defaultValue`.
# 补充区分event.target和event,currentTarget
## event.currentTarget
> https://developer.mozilla.org/zh-CN/docs/Web/API/Event/currentTarget
当事件遍历DOM时,标识事件的当前目标。它总是引用事件处理程序附加到的元素,而不是event.target,它标识事件发生的元素。
例子
event.currentTarget很有用, 当将相同的事件处理程序附加到多个元素时。
```
function hide(e){
e.currentTarget.style.visibility = "hidden";
console.log(e.currentTarget);
// 该函数用作事件处理器时: this === e.currentTarget
}
var ps = document.getElementsByTagName('p');
for(var i = 0; i < ps.length; i++){
// console: 打印被点击的p元素
ps[i].addEventListener('click', hide, false);
}
// console: 打印body元素
document.body.addEventListener('click', hide, false);
```
## event.target
一个触发事件的对象的引用。它与event.currentTarget不同, 当事件处理程序在事件的冒泡或捕获阶段被调用时。
event.target 属性可以用来实现事件委托 (event delegation)。
```
// Make a list
var ul = document.createElement('ul');
document.body.appendChild(ul);
var li1 = document.createElement('li');
var li2 = document.createElement('li');
ul.appendChild(li1);
ul.appendChild(li2);
function hide(e){
// e.target refers to the clicked <li> element
// This is different than e.currentTarget which would refer to the parent <ul> in this context
e.target.style.visibility = 'hidden';
}
// Attach the listener to the list
// It will fire when each <li> is clicked
ul.addEventListener('click', hide, false);
```
event.target 属性在实现事件代理时会被用到。
```
// 假定一个 list 变量为 ul 元素
function hide(e) {
// 点击列表项目(li)区域,e.target 与 e.currentTarget 不同
e.target.style.visibility = 'hidden';
}
list.addEventListener('click', hide, false);
// If some element (<li> element or a link within an <li> element for instance) is clicked, it will disappear.
// It only requires a single listener to do that
```<file_sep>/README.md
# knowledge
不积跬步无以至千里。
## HTML5
[html5基本知识(未完待续)](https://github.com/haoxunba/knowledge/issues/1)
## jQuery
[jquery基础知识 未完待续](https://github.com/haoxunba/knowledge/blob/master/jQuery%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md)
## JS一带一路系列
[运算符](https://github.com/haoxunba/knowledge/issues/3)
## React
### [高阶组件](https://github.com/haoxunba/knowledge/blob/master/React/Higher-Order-Component.md)
<file_sep>/CSS/CSS2和CSS3选择器汇总.md
## 基本选择器
序号 | 选择器 | 含义
---|---|----
1. | * | 通用元素选择器,匹配任何元素
2. | E | 标签选择器,匹配所有使用E标签的元素
3. | .info | class选择器,匹配所有class属性中包含info的元素
4. | #footer | id选择器,匹配所有id属性等于footer的元素
## 多元素的组合选择器
序号 | 选择器 | 含义
---|---|---
5. | E,F | 多元素选择器,同时匹配所有E元素或F元素,E和F之间用逗号分隔
6. | E F | 后代元素选择器,匹配所有属于E元素后代的F元素,E和F之间用空格分隔
7. | E > F | 子元素选择器,匹配所有E元素的子元素F
8. | E + F | 毗邻元素选择器,匹配所有紧随E元素之后的同级元素F
```
<style>
div[attr]+div {
color:aqua;
}
</style>
<div attr="demo">第一行</div>
<div>第二行</div> // 只有第二行的颜色变化
<div>第三行</div>
```
## CSS 2.1 属性选择器
序号 | 选择器 | 含义
---|---|---
9. | E[att] | 匹配所有具有att属性的E元素,不考虑它的值。(注意:E在此处可以省略,比如"[cheacked]"。以下同。)
10. | E[att="val"] | 匹配所有att属性等于"val"的E元素
11. | E[att~="val"] | 匹配所有att属性值当中有一个值等于"val"的E元素
12. | E[att|="val"] | 匹配所有att属性具有多个连字号分隔(-如zh-CN)的值、其中一个值以"val"开头的E元素,主要用于lang属性,比如"en"、"en-us"、"en-gb"等等
## CSS 2.1中的伪类
序号 | 选择器 | 含义
---|---|---
13. | E:first-child | 匹配E的父元素的第一个子元素
14. | E:link | 匹配所有未被点击的链接
15. | E:visited | 匹配所有已被点击的链接
16. | E:active | 匹配鼠标正在点击的E元素
17. | E:hover | 匹配鼠标悬停其上的E元素
18. | E:focus | 匹配获得当前焦点的E元素
19. | E:lang(c) | 匹配lang属性等于c的E元素
`:first-child`有坑,慎用,参考网站http://www.cnblogs.com/wangmeijian/p/4562304.html
主要应用在一组相同元素的兄弟元素,如下面的案例,或者ul下的li标签
> **只要E元素是它的父级的第一个子元素,就选中。**它需要同时满足两个条件,一个是“第一个子元素”,另一个是“这个子元素刚好是E”。
同样的还适用于`last-chilad nth-child nth-of-type` 等。
```
span:first-child {
background-color: lime;
}
上面的CSS作用于下面的HTML:
<div>
<span>This span is limed!</span>
<span>This span is not. :(</span>
</div>
```
`:link` 选择器不会设置已经访问过的链接的样式(即只要点击过新的链接,再怎么刷新页面也不会显示link里面设置的样式)。
`:active` 激活链接即代表的是用户按下按键和松开按键之间的时间。通常用于但并不限于 `<a>` 和 `<button>` HTML元素,因此我们常采用下面的先后顺序`link — :visited — :hover — :active。`
`:visited` 出于安全考虑只能在这里设置color相关的样式。
```
body { background-color: #ffffc9 }
a:link { color: blue } /* 未访问链接 */
a:visited { color: purple } /* 已访问链接 */
a:hover { font-weight: bold } /* 用户鼠标悬停 */
a:active { color: lime } /* 激活链接 */
```
## CSS 2.1中的伪元素
序号 | 选择器 | 含义
---|---|---
20. | E:first-line | 匹配E元素的第一行
21. | E:first-letter | 匹配E元素的第一个字母
22. | E:before | 在E元素之前插入生成的内容
23. | E:after | 在E元素之后插入生成的内容
## CSS 3的同级元素通用选择器
序号 | 选择器 | 含义
---|---|---
24. | E ~ F | 匹配任何在E元素之后的同级F元素
## CSS 3 属性选择器
序号 | 选择器 | 含义
---|---|---
25. | E[att^="val"] | 属性att的值以"val"开头的元素
26. | E[att$="val"] | 属性att的值以"val"结尾的元素
27. | E[att*="val"] | 属性att的值包含"val"字符串的元素
```
<style>
a[href*="abc"] {
color:red;
}
</style>
<a href="abc">第一个子元素</a>
<a href="aabcdef">第二2个子元素</a> // 两个元素都会变色
```
## CSS 3表单元素
序号 | 选择器 | 含义
---|---|---
28. | E:enabled | 匹配表单中激活的元素
29. | E:disabled | 匹配表单中禁用的元素
30. | E:checked | 匹配表单中被选中的radio(单选框)或checkbox(复选框)元素
31. | E::selection | 匹配用户当前选中的元素
不能用`input:text`
## CSS 3中的结构性伪类
序号 | 选择器 | 含义
---|---|---
32. | E:root | 匹配文档的根元素,对于HTML文档,就是HTML元素
33. | E:nth-child(n) | 匹配其父元素的第n个子元素,第一个编号为1
34. | E:nth-last-child(n) | 匹配其父元素的倒数第n个子元素,第一个编号为1
35. | E:nth-of-type(n) | 与:nth-child()作用类似,但是仅匹配使用同种标签的元素
36. | E:nth-last-of-type(n) | 与:nth-last-child() 作用类似,但是仅匹配使用同种标签的元素
37. | E:last-child | 匹配父元素的最后一个子元素,等同于:nth-last-child(1)
38. | E:first-of-type | 匹配父元素下使用同种标签的第一个子元素,等同于:nth-of-type(1)
39. | E:last-of-type | 匹配父元素下使用同种标签的最后一个子元素,等同于:nth-last-of-type(1)
40. | E:only-child | 匹配父元素下仅有的一个子元素,等同于:first-child:last-child或 :nth-child(1):nth-last-child(1)
41. | E:only-of-type | 匹配父元素下使用同种标签的唯一一个子元素,等同于:first-of-type:last-of-type或 :nth-of-type(1):nth-last-of-type(1)
42. | E:empty | 匹配一个不包含任何子元素的元素,注意,文本节点也被看作子元素
## CSS 3的反选伪类
序号 | 选择器 | 含义
---|---|---
43. | E:not(s) | 匹配不符合当前选择器的任何元素
## CSS 3中的 :target 伪类
序号 | 选择器 | 含义
---|---|---
44. | E:target | 匹配文档中特定"id"点击后的效果
<file_sep>/jQuery/jquery方法大全.md
## Miscellaneous
### DOM Element Methods
`.toArray()` 将jquery获取的DOM伪类集合转为原生DOM数组
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toArray demo</title>
<style>
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
Reversed - <span></span>
<div>One</div>
<div>Two</div>
<div>Three</div>
<script>
function disp( divs ) {
var a = [];
for ( var i = 0; i < divs.length; i++ ) {
a.push( divs[ i ].innerHTML );
}
$( "span" ).text( a.join( " " ) );
}
disp( $( "div" ).toArray().reverse() );
</script>
</body>
</html>
```
## .each()
当给jQuery里面的DOM对象绑定不同事件的时候,就用到each(),例如
```
$("#ulList").children("li").each(function (index,ele) {
$(ele).fadeTo(1,(index+1)/10);
})
```
## [Utilities](https://api.jquery.com/category/utilities/)
### extend
#### 语法
`jQuery.extend([deep], target, object1, object2)`
> `[deep]`代表是否深拷贝,true代表深拷贝,不填该参数则默认浅拷贝
> 第一个参数不能传false,因为一旦传false就会终止合并,直接返回`target`
> 如果`target` `object1` `object2`存在属性相同的情况,一般后面的覆盖前面的,`object2`覆盖`object1`,`object1`覆盖`target`
#### extend深拷贝与浅拷贝区别
```
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
```
下面的是一般合并,默认浅拷贝
```
// Merge object2 into object1
$.extend( object1, object2 );
console.log(object1);
// {"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
```
下面是深拷贝的结果
```
$.extend( true, object1, object2 );
console.log(object1);
//{"apple":0,"banana":{"weight":52,"price":100},"cherry":97}
```
下面是传入false的结果
```
$.extend( false, object1, object2 );
console.log(object1);
//{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
```
#### 应用场景
`jQuery.extend(object);`为扩展jQuery类本身.为类添加新的方法。
```
$.extend({
hello:function(){alert('hello');}
});
//调用就是$.hello();
```
## Ajax
### Global Ajax Event Handlers
> As of jQuery 1.9, all the handlers for the jQuery global Ajax events, must be attached to `document`.
例如`$(docuemnt).ajaxStart(function() {})`
> If `$.ajax()` or `$.ajaxSetup()` is called with the global option set to false, the other method will not fire.
#### ajaxSetup
`jQuery.ajaxSetup({})`
ajax初始化默认值,后面单独设置的ajax会覆盖
> strongly recommend against using this API
#### ajaxStart
`$(document).ajaxStart(fucntion)`
只要有一个ajax发送请求就执行
#### ajaxStop
`$(document).ajaxStop(fucntion)`
页面中所有ajax请求完成,执行stop
#### ajaxSend
`$(document).ajaxSend(function)`
每次ajax请求都会触发`ajaxSend`
可以通过传参来让`ajaxSend`每次执行的内容不同
> event: event object
jqxhr: XMLHttpRequest
settings: Ajax request object
```
$(document).ajaxSend(function(event, jqxhr, settings) {
if(settings.url === 'example.php') {
alert('ajaxSend handler');
}
})
```
#### ajaxSuccess
`$(document).ajaxSuccess(function)`
整体描述和上面的`ajaxSend`相同
也可以设置`$(document).ajaxSuccess(function(event, xhr, settings, data))`,只不过比`ajaxSend`多了一个参数。
> You can get the returned Ajax contents by looking at `xhr.responseXML` or `xhr.responseText` for `xml` and `html` respectively.
#### ajaxError
> This handler is not called for cross-domain script and cross-domain JSONP requests.
应用同上面一样,唯一的区别就是最后参数
`$(document).ajaxError(function(event, xhr, settings, throwError))`
#### ajaxComplete
应用同上面一样,唯一的区别就是最后参数
`$(document).ajaxError(function(event, xhr, settings))`
> You can get the returned Ajax contents by looking at `xhr.responseText.`
单个ajax事件就是
```
$('div').ajax{
beforeSend:{},
success:{},
error:{}
}
```<file_sep>/Javascript高级程序设计/第二章/2.1.3async.js
setTimeout(function() {
console.log('async');
},2000)<file_sep>/Javascript高级程序设计/javascript高级程序设计.md
该文件夹主要练习《Javascript 高级程序设计》相关的代码<file_sep>/React/Higher-Order-Component.md
# 高阶组件(higher-order component)
## 简介
简单说高阶组件就是一个函数,接收组件作为参数并返回一个组件
简单注意点
1. 本文中单词hoc指高阶组件,wrappedComponent指被包装组件
1. hoc和wrappedComponent有各自声明周期并遵循递归渲染
> 递归渲染:
其实,mountComponent(挂载组件) 本质上是通过 递归渲染 内容的,
由于递归的特性,父组件的 componentWillMount 一定在其子组件的 componentWillMount 之前调用,
而父组件的 componentDidMount 肯定在其子组件的 componentDidMount 之后调用。
这里通过在Hoc和usual中都定义这两个周期可以验证
```
//hoc
const simpleHoc = WrappedComponent => {
console.log('simpleHoc'); // 最先执行
return class extends Component {
componentWillMount() {
console.log('hoc componentWillMount'); // 渲染顺序first
}
componentDidMount() {
console.log('hoc componentDidMount'); // fourth
}
render() {
// return <WrappedComponent {...this.props}/>
return <WrappedComponent hocProps="test"/>
}
}
}
export default simpleHoc;
```
```
// usual
class Usual extends React.Component{
constructor(props) {
super(props);
this.state = {
a: 1
}
}
componentWillMount() {
console.log('usual componentWillMount'); // second
}
componentDidMount() {
console.log('usual componentDidMount'); // third
}
render() {
console.log(this.props, 'props');
return (
<div>
Usual
</div>
)
}
}
export default simpleHoc(Usual);
```
## 详解
高阶函数存在两种模式,一种是属性代理,一种是反向继承
### 属性代理(props proxy)
hoc接收外部的数据,然通过props将数据传递给wrappedComponent,这就是props proxy的意思。
和下面提到的反向继承相比,props proxy可以理解为正向继承,即被包装组件(wrapedComponent)可以继承包装组件(HOC)的props
属性代理可以分为三种
#### 第一种操作props
操作props
最直观的就是接受到props,我们可以做任何读取,编辑,删除的很多自定义操作。包括hoc中定义的自定义事件,都可以通过props再传下去。
```
const propsProxyHoc = WrappedComponent => class extends Component {
handleClick() {
console.log('click');
}
render() {
return (<WrappedComponent
{...this.props}
handleClick={this.handleClick}
/>);
}
};
export default propsProxyHoc;
```
```
class Usual extends React.Component{
render() {
console.log(this.props, 'props');
return (
<div>
Usual
</div>
)
}
}
export default simpleHoc(Usual);
```
#### 第二种利用ref
包装组件通过ref获取被包装组件实例,从而可以获取 被包装组件的props和state
注意在hoc里面获取到的props不包括hoc传给wrappedComponent
```
const refHoc = WrappedComponent => class extends Component {
componentDidMount() {
console.log(this.instanceComponent, 'instanceComponent');
}
render() {
return (<WrappedComponent
{...this.props}
ref={instanceComponent => this.instanceComponent = instanceComponent}
/>);
}
};
export default refHoc;
```
this.instanceComponent此时就可以获取wrappedComponent的实例,包括props,state,refs等
#### 第三种受控表单
不通过上面的ref方法获取被包装组件实例的state
考虑到hoc的主要作用就是处理数据,所以有一种情况会用到下面这种方法,就是受控组件
```
const formCreate = WrappedComponent => class extends Component {
constructor() {
super();
this.state = {
fields: {},
}
}
onChange = key => e => {
// 下面这种写法的好处就是,当只输入账户input时,fields对象只存储一个键值对,当再输入密码input时,fields又变为两个属性
this.setState({
fields: {
...this.state.fields,
[key]: e.target.value,
}
},()=>{
console.log(this.state.fields);
})
}
handleSubmit = () => {
console.log(this.state.fields);
}
getField = fieldName => {
return {
onChange: this.onChange(fieldName),
}
}
render() {
const props = {
...this.props,
handleSubmit: this.handleSubmit,
getField: this.getField,
}
return (<WrappedComponent
{...props}
/>);
}
};
export default formCreate;
```
```
class Login extends Component {
render() {
// 下面这种写法有点看不懂
// console.log({...this.props.getField('username')});
return (
<div>
<div>
<label id="username">
账户
</label>
<input name="username" {...this.props.getField('username')}/>
</div>
<div>
<label id="<PASSWORD>">
密码
</label>
<input name="<PASSWORD>" {...this.props.getField('password')}/>
</div>
<div onClick={this.props.handleSubmit}>提交</div>
<div>other content</div>
</div>
)
}
}
export default simpleHoc(Login);
```
### 反向继承(Inheritance Inversion)
上面提到了高阶组件有两种模式。一种是属性代理,一种是反向继承
反向继承(Inheritance Inversion),简称II,又分为两种方式
#### 第一种方式是普通方式
通过继承WrappedComponent,除了一些静态方法,包括生命周期,state,各种function,我们都可以得到
注意: 如果在constructor里面重新定义了this.state会覆盖反向继承来的state,其他反向继承来的东西还没有验证
```
const iiHoc = WrappedComponent => class extends WrappedComponent {
constructor() {
super();
this.state = {
b: this.state
}
}
render() {
console.log(this.state, 'state');
//return super.render();
return <WrappedComponent />
}
}
export default iiHoc;
```
#### 第二种方式渲染劫持
这里HOC里定义的组件继承了WrappedComponent的render(渲染),我们可以以此进行hijack(劫持),也就是控制它的render函数
```
const hijackRenderHoc = config => WrappedComponent => class extends WrappedComponent {
render() {
const { style = {} } = config;
const elementsTree = super.render();
console.log(elementsTree, 'elementsTree');
if (config.type === 'add-style') {
return <div style={{...style}}>
{elementsTree}
</div>;
}
return elementsTree;
}
};
export default hijackRenderHoc;
```
```
class II extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
II
</div>
)
}
}
export default simpleHoc({type: 'add-style', style: { color: 'red'}})(II)
```
## 注意点(约束)
其实官网有很多,简单介绍一下。
第一点
最重要的原则就是,注意高阶组件不会修改子组件,也不拷贝子组件的行为。高阶组件只是通过组合的方式将子组件包装在容器组件中,是一个无副作用的纯函数
第二点
要给hoc添加class名,便于debugger。为了方便上面的好多栗子组件都没写class 名。当我们在chrome里应用React-Developer-Tools的时候,组件结构可以一目了然,所以DisplayName最好还是加上。
constructor
> The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named withSubscription, and the wrapped component’s display name is CommentList, use the display name WithSubscription(CommentList):
```
function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component { ... }
WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
```
第三点
静态方法要复制
无论PP还是II的方式,WrappedComponent的静态方法都不会复制,如果要用需要我们单独复制,其他详解见官网。
```
// Define a static method
WrappedComponent.staticMethod = function() {...}
// Now apply a HOC
const EnhancedComponent = enhance(WrappedComponent);
// The enhanced component has no static method
typeof EnhancedComponent.staticMethod === 'undefined' // true
```
第四点
refs不会传递。 意思就是HOC里指定的ref,并不会传递到子组件,如果你要使用最好写回调函数通过props传下去。
第五点
不要在render方法内部使用高阶组件。简单来说react的差分算法会去比较 NowElement === OldElement, 来决定要不要替换这个elementTree。也就是如果你每次返回的结果都不是一个引用,react以为发生了变化,去更替这个组件会导致之前组件的状态丢失。
```
// HOC不要放到render函数里面
class WrappedUsual extends Component {
render() {
const WrappenComponent = addStyle(addFunc(Usual));
console.log(this.props, 'props');
return (<div>
<WrappedComponent />
</div>);
}
}
```
例如上面的案例有可能导致WrappenComponent组件的状态丢失
第六点
使用compose组合HOC。函数式编程的套路... 例如应用redux中的middleware以增强功能。redux-middleware解析
```
const addFunc = WrappedComponent => class extends Component {
handleClick() {
console.log('click');
}
render() {
const props = {
...this.props,
handleClick: this.handleClick,
};
return <WrappedComponent {...props} />;
}
};
const addStyle = WrappedComponent => class extends Component {
render() {
return (<div style={{ color: 'yellow' }}>
<WrappedComponent {...this.props} />
</div>);
}
};
// const WrappenComponent = addStyle(addFunc(Usual));
class WrappedUsual extends Component {
render() {
console.log(this.props, 'props');
return (<div>
hoc
</div>);
}
}
// The compose utility function is provided by many third-party libraries including lodash (as lodash.flowRight), Redux, and Ramda.
export default compose(addFunc, addStyle)(WrappedUsual);
```
第七点
React Redux's `connect`
```
const ConnectedComment = connect(commentSelector, commentActions)(CommentList);
```
connect是一个返回高阶组件的高阶函数!通过这个高阶组件返回的被包装组件能够连接到Redux store
*/<file_sep>/React/refs&DOM.md
# Refs and the DOM
通常我们通过props进行父子组件交互,但是当我们需要操作子组件实例或者真实的DOM元素时,就要用到props
1. Managing focus, text selection, or media playback.
2. Triggering imperative animations.
3. Integrating with third-party DOM libraries.
> 不要过度使用refs,尽量用state代替
**挂到组件(这里组件指的是有状态组件)上的ref表示对组件实例的引用,而挂载到dom元素上时表示具体的dom元素节点。**
ReactDOM.render()返回值其实就是ref代表的组件实例或dom元素,当ReactDOM.render()渲染组件时那么它返回的是组件实例;而渲染dom元素时,返回是具体的dom节点。
例如,下面代码:
```
const domCom = <button type="button">button</button>;
const refDom = ReactDOM.render(domCom,container);
//ConfirmPass的组件内容省略
const refCom = ReactDOM.render(<ConfirmPass/>,container);
console.log(refDom);
console.log(refCom);
```
## Adding a Ref to a DOM Element
```
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
```
> React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. ref callbacks are invoked before componentDidMount or componentDidUpdate lifecycle hooks.
## Adding a Ref to a Class Component
```
class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focusTextInput();
}
render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}
```
上面案例的功能就是当组件实例挂载完成时,立即执行实例中的focusTextInput方法,从而实现页面加载完成让对应的输入框获得焦点的体验
包装组件通过ref获取被包装组件实例,从而可以获取 被包装组件的props和state和方法
## Refs and Functional Components
You may not use the ref attribute on functional components because they don’t have instances:
```
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// This will *not* work!
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
```
You can, however, use the ref attribute inside a functional component as long as you refer to a DOM element or a class component:
```
function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
```
## Exposing DOM Refs to Parent Components
While you could add a ref to the child component, this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn’t work with functional components.
```
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
```
父组件Parent可以通过this.inputElement获得functional component的真实input元素,可以看出这种方式是适合functional component的
下面的案例是对于更深层次的调用后代组件的真实dom方法
```
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
function Parent(props) {
return (
<div>
My input: <CustomTextInput inputRef={props.inputRef} />
</div>
);
}
class Grandparent extends React.Component {
render() {
return (
<Parent
inputRef={el => this.inputElement = el}
/>
);
}
}
```
> Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use findDOMNode(), but it is discouraged.
```
export default class Parent extends React.Component {
componentDidMount() {
console.log(ReactDOM.findDOMNode(this.child))
}
render() {
return <Child ref={(child)=>{this.child=child}}/>
// return <div ref={(div)=>{this.test=div}}>124</div>
}
}
```
上面ReactDOM.findDOMNode拿到的是子组件Child render出来的所有DOM元素
## Legacy API: String Refs
```
<input type="text" ref={'input'}/>
```
使用this.refs.input会存在未知的bug,react官网不推荐使用
## 思考
子组件能不能拿到父组件的真实DOM元素
```
export default class Parent extends React.Component {
componentDidMount() {
console.log(ReactDOM.findDOMNode(this.child))
console.log(this.parentRef)
}
render() {
return (
<div>
<div ref={div=>this.parentRef=div}></div>
<Child ref={(child)=>{this.child=child}} parentRef = {this.parentRef}/>
</div>
)
}
}
```
```
export default class Child extends React.Component {
render() {
console.log(this.props);
return <div>这里是测试refs的子组件</div>
}
}
```
子组件打印出来的this.props的值是`{parentRef: undefined}`
考虑到通过ref获取真实dom只能在组件渲染完成后获取,即拿到真实dom的lifesycle只能是在render之后,那么在Parent组件中直接在render周期中向子组件传过去ref,此时ref还没有拿到真实DOM所以是undefined
那有没有其他办法呢<file_sep>/React/其他小知识点.md
# 其他React小知识点
## state
### setState
> React may batch multiple setState() calls into a single update for performance.
> 考虑到性能问题react会将所有的setState合并到一起,只更新一次,所以setState是异步的
```
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
```
To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
```
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
```
应用:
1. update state with values that depend on the current state
2. setState({}, callback)
## Handling Events
给react的方法传参注意事项
```
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
```
上面的`id`表示实参,不是形参, 参照下面的案例,注释部分不能传形参arg,所以注释部分运行起来会报错(`arg is not defined`)因此应该传实参比如空字符串
还要注意一点就是如果使用bind方法来传参,event这个形参是不写的
下面介绍具体案例
```
handleParentChange(arg, event) {
this.setState({
parentValue: arg || event.target.value
})
}
render() {
return (
<div>
// <input type="text" value={this.state.parentValue} onChange={this.handleParentChange.bind(this, arg)}/>
<input type="text" value={this.state.parentValue} onChange={this.handleParentChange.bind(this, '')}/>
</div>
)
}
```
这种传参一般是应用在给当前的事件加一个特殊的标记,可以让不同的元素运行同一个方法,从而做不同的处理
```
handleParentChange(arg, event) {
this.setState({
parentValue: event.target.value + arg
})
}
render() {
return (
<div>
// <input type="text" value={this.state.parentValue} onChange={this.handleParentChange.bind(this, arg)}/>
<input type="text" value={this.state.parentValue} onChange={this.handleParentChange.bind(this, 'first')}/>
<input type="text" value={this.state.parentValue} onChange={this.handleParentChange.bind(this, 'second')}/>
</div>
)
}
```
上面的两个输入框都输入1,第一个输入框显示的value就是`1first`,第二个输入框显示的value就是`1second`<file_sep>/Javascript高阶/性能优化.md
# 性能优化
## 减少http请求
减少http的主要手段是合并CSS、合并javascript、合并图片
## 合理利用缓存
## 代码压缩
## Lazyload image
## css放在页面头部,js放在底部
## 减少cookie传输
尽量减少cookie中传输的数据量。比如对于某些静态资源的访问,如CSS、script等,发送cookie没有意义,可以考虑静态资源使用独立域名访问,避免请求静态资源时发送cookie,减少cookie传输次数。
## 代码优化
分为js和css的代码优化
## CDN
CDN(contentdistribute network,内容分发网络)

## 反向代理
传统代理服务器位于浏览器一侧,代理浏览器将http请求发送到互联网上,而反向代理服务器位于网站机房一侧,代理网站web服务器接收http请求。如下图所示:

论坛网站,把热门词条、帖子、博客缓存在反向代理服务器上加速用户访问速度,当这些动态内容有变化时,通过内部通知机制通知反向代理缓存失效,反向代理会重新加载最新的动态内容再次缓存起来。
此外,反向代理也可以实现负载均衡的功能,而通过负载均衡构建的应用集群可以提高系统总体处理能力,进而改善网站高并发情况下的性能。<file_sep>/AntdMobile/AntdMobile.md
# antd-mobile
## 引入css的样式的两种方式
### 在入口处引入样式
```
// 一般入口文件是index.js
import 'antd-mobile/dist/antd-mobile.css'; // or 'antd-mobile/dist/antd-mobile.less'
```
或者下面这种方式引入样式
和上面的方法不同的地方就是,上面是直接从包文件的路径中引入样式,这个方法是将安装包里面lib目录下的antd-mobile.css复制到项目中指定的文件夹下(如style文件夹)
这样做的有点是可以在打包的时候编译指定文件夹下面的css
```
{
test: /\.css$/,
include: path.resolve(__dirname, 'src/styles'),
use: [
'style-loader',
'css-loader',
],
}
```
但是上面两种引入样式的做法都不能做到按需加载,antd内部会在浏览器的控制台提示警告,并推荐安装`babel-plugin-import`
### 利用babel-plugin-import
- 使用 babel-plugin-import(推荐)。
```
// .babelrc or babel-loader option
{
"plugins": [
["import", { "libraryName": "antd-mobile", "style": "css" }] // `style: true` 会加载 less 文件
]
}
```
然后只需从 antd-mobile 引入模块即可,无需单独引入样式。
```
// babel-plugin-import 会帮助你加载 JS 和 CSS
import { DatePicker } from 'antd-mobile';
```
- 手动引入
```
import DatePicker from 'antd-mobile/lib/date-picker'; // 加载 JS
import 'antd-mobile/lib/date-picker/style/css'; // 加载 CSS
// import 'antd-mobile/lib/date-picker/style'; // 加载 LESS
```
注意使用按需加载时,样式是直接引用node-modules中的样式,所以css-loader的配置里面不能在用类似上面的配置, 去掉include的配置,否则不能编译node-modules下面的css样式,会报错
```
{
test: /\.css$/,
// include: path.resolve(__dirname, 'src/styles'),
use: [
'style-loader',
'css-loader',
],
}
```
## 自定义样式
```
import React,{Component} from 'react';
import {Button, NavBar, Icon} from 'antd-mobile';
import CreateCSSModules from 'react-css-modules';
import style from './antdStyleReset.scss';
class AntdStyleReset extends React.Component {
render() {
return (
<div>
<div className="antdStyleReset">
<NavBar
mode="light"
className={style.nav1}
styleName = 'nav2'
style={{color: 'red'}}
prefixCls="antdStyleReset-navbar"
icon={<Icon type="left" />}
onLeftClick={() => console.log('onLeftClick')}
rightContent={[
<Icon key="0" type="search" style={{ marginRight: '16px' }} />,
<Icon key="1" type="ellipsis" />,
]}
>NavBar</NavBar>
</div>
<Button className={style.button} style={{color: 'red'}}>test1</Button>
</div>
)
}
}
export default CreateCSSModules(AntdStyleReset, style, {
allowMultiple: true
})
```
我尝试在引用的组件中利用`className`、`styleName`、`style`来自定义组件的样式,但是存在很多问题,比如
1. 设置的样式有可能被组件中权重更高的样式覆盖不起作用
2. 设置的样式不能精确指定到组件中某一个元素
还有的童鞋说定义`styleName`等于`NavBar`组件默认的类名比如`styleName = "am-navbar-left"`,这种方法也存在很多问题,比如
1. 比如定义`am-navbar-left`是想重置`NavBar`组件内部的某个元素的样式,这种做法只会将给类名设置到外层元素,不能设置到内层的元素
所以我推荐使用`prefixCls`来自定义组件,虽然这种方式比较笨拙,但是可以很好的解决上面的问题
根据上面的案例,总结相关步骤是
1. 自定义类名`prefixCls="antdStyleReset-navbar"`,我推荐定义方式是`组件名+antd的组件名`
2. 将相关的样式`node_modules/antd-mobile/lib/nav-bar/style/index.css`复制到`antdStyleReset`组件对应的样式`antdStyleReset.scss`中
3. 全局替换`am-navbar`为`antdStyleReset-navbar`
4. 更改相关元素类名的样式就可以了
<file_sep>/React/props.md
# Props
简单的应用就不介绍了,下面主要讲讲平时中注意的小知识点
## props和this.props应用场景
在functional component中用props,在class中用this.props
```
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
```
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
class App extends React.Component {
render() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
## this.props.children
注意this.props.children是this.props中唯一的特例
props.children is available on every component. It contains the content between the opening and closing tags of a component. For example:
```
// Welcome在被当做子组件调用时
<Welcome>Hello world!</Welcome>
```
The string Hello world! is available in props.children in the Welcome component:
```
// 此时在Welcome组件内部可以拿到Hello world!
function Welcome(props) {
return <p>{props.children}</p>;
}
```
For components defined as classes, use this.props.children:
```
// 上面是functional component的写法,下面是class写法,再次区分props和this.props
class Welcome extends React.Component {
render() {
return <p>{this.props.children}</p>;
}
}
```<file_sep>/React/React16.md
# React16
该处主要介绍react16新增的功能
## React16.2.0
### Improved Support for Fragments
之前在react16.0版本,在render return中可以用数组代替外层标签的包裹,类似于
```
render() {
return [
"Some text.",
<h2 key="heading-1">A heading</h2>,
"More text.",
<h2 key="heading-2">Another heading</h2>,
"Even more text."
];
}
```
这种写法存在很多麻烦的地方,所以Fragments就应运而生了
React 16.2 is now available! The biggest addition is improved support for returning multiple children from a component’s render method. We call this feature fragments
fragments的原理就是在return的children外边会隐式的帮你添加一个空标签,从而让你不需要添加一个多余的div等标签来包裹了,类似于
```
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
```
Fragments在react中的应用
第一种就是
```
const Fragment = React.Fragment;
<Fragment>
<ChildA />
<ChildB />
<ChildC />
</Fragment>
// This also works
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
```
第二种就是上面提到的空标签。二者的区别就是空标签不能使用任何attribute,Fragment目前只支持key属性<file_sep>/LocalDevelopServer/Tomcat.md
# Tomcat
## 简单介绍部署流程
1. 安装JDK并部署环境变量
2. 安装Tomcat并部署环境
注意tomcat官网会有版本选择说明,针对不同版本的JDK安装不同版本的tomcat
3. 设置端口,并部署web项目
可以在`Connector`中配置端口,默认8080
```
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
```
在Host里面添加下面的`Context`用来映射项目的路径
```
<Context path="/" reloadable="true" docBase="E:\knowledge"/>
```
配置完成,本地可以通过`localhost:8080`访问项目 | ebc8dedba6582d961e5fba9b0b006645fa2a2aed | [
"Markdown",
"JavaScript"
] | 23 | Markdown | haoxunba/knowledge | e1ad87fb3786c3bc7b5d9adeb003fcc4567b29dc | 929d84d42f32ff3ec3a432cd75a7aa887704bf13 |
refs/heads/main | <file_sep>from os import replace
#Webにリクエストする為
import requests
#Webサイトを読み取る為
from bs4 import BeautifulSoup
#クリップボード操作
import pyperclip
#文字列から辞書を作成する為
import ast
def time(s):
import datetime as dt
#s = "2021-04-14T10:42:00+09:00"
dtl = s.split('T')
dl = [int(num) for num in dtl[0].split('-')]
tl =[int(num) for num in dtl[1][:5].split(':')]
#曜日検索
date = dt.date(dl[0],dl[1],dl[2])
weekday ={'Sun':'日曜日','Mon':'月曜日','Tue':'火曜日','Wed':'水曜日','Thu':'木曜日','Fri':'金曜日','Sat':'土曜日'}
output = date.strftime('%Y年%m月%d日')+weekday[date.strftime('%a')]
output += str(tl[0]) +"時"+str(tl[1])+"分"
return output
def today(code):
#天気概況
url = 'https://www.jma.go.jp/bosai/forecast/data/overview_forecast/'
url += str(code)
url += '.json'
req = requests.get(url)
bsObj = BeautifulSoup(req.text,'html.parser')
dic = ast.literal_eval(bsObj.text)
#print("type:"+str(type(dic)))
dickey = [key for key in dic.keys()]
#print(dickey)
"""
publishingOffice #データ元
reportDatetime #報告日時
targetArea #対象地域
headlineText #ヘッドライン
text #詳細情報
"""
"""
output=''
for key in dic.keys():
output += dic[key]
output += '\n'
"""
output = dic[dickey[0]]+'より\n'
output += time(dic[dickey[1]])
output += dic[dickey[2]]+'の天気をお伝えします.\n'
output += dic[dickey[3]]
text = dic[dickey[4]].replace('【関東甲信地方】','')
text = text.replace('\n\n','\n')
output+=text+"以上です."
return output
def threedays(code):
url = 'https://www.jma.go.jp/bosai/forecast/data/forecast/'
url += str(code)
url += '.json'
req = requests.get(url)
bsObj = BeautifulSoup(req.text,'html.parser')
dic = ast.literal_eval(bsObj.text)
#output=''
#output = bsObj.text
o = dic[0]['timeSeries'][0]['areas'][0].keys()
print(o)
"""
for i in range(2):
for key in dic[i].keys():
if key != 'timeSeries':
print(dic[i][key])
else:
for j in range(len(dic[i][key])):
for tskey in dic[i][key][j].keys():
print(dic[i][key][j][tskey])
return output"""
#threedays(130000)
#w:上書き,a:追記,x:新規作成
f=open('weather output.txt','w')
text = today(130000)
pyperclip.copy(text)
f.write(text)
#f.write(threedays(130000))
f.close<file_sep>#pip install requests
#pip install beautifulsoup4
from os import write
import requests as req
from bs4 import BeautifulSoup
#import BeautifulSoup
f = open('output.txt','a')
url = req.get('http://www.jma.go.jp/bosai/common/const/area.json')
s = BeautifulSoup(url.text,'html.parser')
print(s)
bsObj = BeautifulSoup(url.text,'html.parser').text
for c in bsObj:
f.write(c)
if c=='}' or c=='{':
f.write('\n')
print('complete')
#f.write(bsObj) | 5a328cc0f09d22a8be37f8a24d915325abda7d62 | [
"Python"
] | 2 | Python | D-COMPAS/weather | 6b1181661b933f2ca5588d0af7b88b63e22ede94 | d6a0f5c1611d10e2067b4f0afecae344957720ed |
refs/heads/main | <file_sep>package ua.nure.danylenko.practice7;
import ua.nure.danylenko.practice7.controller.DOMController;
import ua.nure.danylenko.practice7.entity.Devices;
public class Main {
public static void usage() {
System.out.println("java ua.nure.danylenko.practice7.Main xmlFileName");
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
usage();
return;
}
String xmlFileName = args[0];
System.out.println("Input ==> " + xmlFileName);
////////////////////////////////////////////////////////
// DOM
////////////////////////////////////////////////////////
// get
DOMController domController = new DOMController(xmlFileName);
domController.parse(true);
Devices devices = domController.getDevices();
// sort (case 1)
Sorter.sortDevicesByNames(devices);
// save
String outputXmlFile = "output.dom.xml";
DOMController.saveToXML(devices, outputXmlFile);
System.out.println("Output ==> " + outputXmlFile);
////////////////////////////////////////////////////////
// SAX
////////////////////////////////////////////////////////
// get
// SAXController saxController = new SAXController(xmlFileName);
// saxController.parse(true);
// devices = saxController.getDevices();
//
// // sort (case 2)
// Sorter.sortDevicesByPrice(devices);
//
// // save
// outputXmlFile = "output.sax.xml";
//
// // other way:
// DOMController.saveToXML(devices, outputXmlFile);
// System.out.println("Output ==> " + outputXmlFile);
//
// ////////////////////////////////////////////////////////
// // StAX
// ////////////////////////////////////////////////////////
//
// // get
// STAXController staxController = new STAXController(xmlFileName);
// staxController.parse();
// devices = staxController.getDevices();
//
// // sort (case 3)
// Sorter.sortAnswersByContent(devices);
//
// // save
// outputXmlFile = "output.stax.xml";
// DOMController.saveToXML(devices, outputXmlFile);
// System.out.println("Output ==> " + outputXmlFile);
}
}
<file_sep>package ua.nure.danylenko.practice7.controller;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import ua.nure.danylenko.practice7.constants.Constants;
import ua.nure.danylenko.practice7.entity.Devices;
public class DOMController {
private String xmlFileName;
// main container
private Devices devices;
public DOMController(String xmlFileName) {
this.xmlFileName = xmlFileName;
}
public Devices getTest() {
return devices;
}
/**
* Parses XML document.
*
* @param validate
* If true validate XML document against its XML schema.
*/
public void parse(boolean validate)
throws ParserConfigurationException, SAXException, IOException {
// obtain DOM parser
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// set properties for Factory
// XML document contains namespaces
dbf.setNamespaceAware(true);
// make parser validating
if (validate) {
// turn validation on
dbf.setFeature(Constants.FEATURE_TURN_VALIDATION_ON, true);
// turn on xsd validation
dbf.setFeature(Constants.FEATURE_TURN_SCHEMA_VALIDATION_ON, true);
}
DocumentBuilder db = dbf.newDocumentBuilder();
// set error handler
db.setErrorHandler(new DefaultHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
// throw exception if XML document is NOT valid
throw e;
}
});
// parse XML document
Document document = db.parse(xmlFileName);
// get root element
Element root = document.getDocumentElement();
// create container
devices = new Devices();
// obtain questions nodes
NodeList questionNodes = root
.getElementsByTagName(XML.QUESTION.value());
// process questions nodes
for (int j = 0; j < questionNodes.getLength(); j++) {
Question question = getQuestion(questionNodes.item(j));
// add question to container
test.getQuestions().add(question);
}
}
/**
* Extracts question object from the question XML node.
*
* @param qNode
* Question node.
* @return Question object.
*/
private static Question getQuestion(Node qNode) {
Question question = new Question();
Element qElement = (Element) qNode;
// process question text
Node qtNode = qElement.getElementsByTagName(XML.QUESTION_TEXT.value())
.item(0);
// set question text
question.setQuestionText(qtNode.getTextContent());
// process answers
NodeList aNodeList = qElement.getElementsByTagName(XML.ANSWER.value());
for (int j = 0; j < aNodeList.getLength(); j++) {
Answer answer = getAnswer(aNodeList.item(j));
// add answer
question.getAnswers().add(answer);
}
return question;
}
/**
* Extracts answer object from the answer XML node.
*
* @param aNode
* Answer node.
* @return Answer object.
*/
private static Answer getAnswer(Node aNode) {
Answer answer = new Answer();
Element aElement = (Element) aNode;
// process correct
String correct = aElement.getAttribute(XML.CORRECT.value());
answer.setCorrect(Boolean.valueOf(correct));
// process content
String content = aElement.getTextContent();
answer.setContent(content);
return answer;
}
// //////////////////////////////////////////////////////
// Static util methods
// //////////////////////////////////////////////////////
/**
* Creates and returns DOM of the Test container.
*
* @param test
* Test object.
* @throws ParserConfigurationException
*/
public static Document getDocument(Test test) throws ParserConfigurationException {
// obtain DOM parser
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// set properties for Factory
// XML document contains namespaces
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
// create root element
Element tElement = document.createElement(XML.TEST.value());
// add root element
document.appendChild(tElement);
// add questions elements
for (Question question : test.getQuestions()) {
// add question
Element qElement = document.createElement(XML.QUESTION.value());
tElement.appendChild(qElement);
// add question text
Element qtElement =
document.createElement(XML.QUESTION_TEXT.value());
qtElement.setTextContent(question.getQuestionText());
qElement.appendChild(qtElement);
// add answers
for (Answer answer : question.getAnswers()) {
Element aElement = document.createElement(XML.ANSWER.value());
aElement.setTextContent(answer.getContent());
// set attribute
if (answer.isCorrect()) {
aElement.setAttribute(XML.CORRECT.value(), "true");
}
qElement.appendChild(aElement);
}
}
return document;
}
/**
* Saves Test object to XML file.
*
* @param test
* Test object to be saved.
* @param xmlFileName
* Output XML file name.
*/
public static void saveToXML(Test test, String xmlFileName)
throws ParserConfigurationException, TransformerException {
// Test -> DOM -> XML
saveToXML(getDocument(test), xmlFileName);
}
/**
* Save DOM to XML.
*
* @param document
* DOM to be saved.
* @param xmlFileName
* Output XML file name.
*/
public static void saveToXML(Document document, String xmlFileName)
throws TransformerException {
StreamResult result = new StreamResult(new File(xmlFileName));
// set up transformation
TransformerFactory tf = TransformerFactory.newInstance();
javax.xml.transform.Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
// run transformation
t.transform(new DOMSource(document), result);
}
public static void main(String[] args) throws Exception {
// try to parse NOT valid XML document with validation on (failed)
DOMController domContr = new DOMController(Constants.INVALID_XML_FILE);
try {
// parse with validation (failed)
domContr.parse(true);
} catch (SAXException ex) {
System.err.println("====================================");
System.err.println("XML not valid");
System.err.println("Test object --> " + domContr.getTest());
System.err.println("====================================");
}
// try to parse NOT valid XML document with validation off (success)
domContr.parse(false);
// we have Test object at this point:
System.out.println("====================================");
System.out.print("Here is the test: \n" + domContr.getTest());
System.out.println("====================================");
// save test in XML file
Test test = domContr.getTest();
DOMController.saveToXML(test, Constants.INVALID_XML_FILE + ".dom-result.xml");
}
}
| 751db2471295a56ade92ed933b1fd895d5314e99 | [
"Java"
] | 2 | Java | deLibertate/practice7 | 8c429b4a2099bd3bd8451e94b017e039ed535c88 | 6c0b2c85a20388e9e2c0499b0ab79e54c8cc0b5c |
refs/heads/master | <repo_name>shiluming/react-demo<file_sep>/README.md
This project about react demo.
##
<file_sep>/router-demo/src/components/News.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
class News extends Component {
constructor(props) {
super(props);
this.state = {
news:[
{
newId:1111,
details:"我是新闻一"
},
{
newId:2222,
details:"我是新闻2"
},
{
newId:3333,
details:"我是新闻3"
},
{
newId:4444,
details:"我是新闻4"
}
]
};
}
render() {
return (
<div>
<ul>
{
this.state.news.map((value,key)=>{
return (
<li key={key}><Link to={`/content/${value.newId}`}> {value.details} </Link></li>
)
})
}
</ul>
</div>
);
}
}
export default News;<file_sep>/router-demo/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from './components/Home';
import News from './components/News';
import product from './components/Product';
import Content from './components/Content';
class App extends Component {
render() {
return (
<Router>
<div>
<header className="header">
<Link to="/">Home</Link>
<Link to="/news">News</Link>
<Link to="/product">Product</Link>
</header>
<hr />
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
<Route path="/product" component={product} />
<Route path="/content/:newId" component={Content} />
</div>
</Router>
);
}
}
export default App;
| 21f088cd749bde3169ffaebed26a1a30a954e46f | [
"Markdown",
"JavaScript"
] | 3 | Markdown | shiluming/react-demo | 7445bb0c4b4a131eb89cf91c1fc7de500044ad9f | 97eb3c4edbfab9ce257d207081c7b33f23dbbd31 |
refs/heads/master | <file_sep># admin
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# run unit tests
npm run unit
# run e2e tests
npm run e2e
# run all tests
npm test
```
``` bash
## 项目简介
一、
框架:vue2.+
UI:elementUi
路由:vue-router
全局状态管理:vuex
二、富文本: vue-quill-editor
示例:
import { quillEditor } from 'vue-quill-editor'
<quill-editor
class="contactUs"
v-model="content"
ref="aboutUs"
:options="editorOption"
@blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
@change="onEditorChange($event)">
</quill-editor>
三、定义全局广播事件 $eventHub
//代码示例
//发送广播事件
this.$eventHub.$emit('mxx', '你的需要传送的数据')
//接收广播事件
this.$eventHub.$on('mxx', (item)=>{
console.log(item);
this.showMask = true;
});
四、网络请求:axios
五、时间格式化:dayjs
六、导航菜单动态生成、根据后台权限控制
七、api文件夹
http.js 封装的网络请求
//代码示例
// post
let data = await this.$api.post("forum",{
title:this.form.name,
sponsor:this.form.people,
sponsorPhone:this.form.phone,
sponsorEmail:this.form.email,
applyReason:this.form.reson,
scaleOfMark:this.form.desc
})
if(data.data.code){
this.$message({
message: '申请成功',
type: 'success'
});
}
// get
let {data} = await this.$api.get("forum/list",{
pageNum:this.currentPage,
pageSize:10,
order:"id",
orderType:"desc",
query:this.filters.name,
type:"1"
})
util.js 全局的方法 动态路由方法在这里
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
<file_sep>
import router from '../router/index'
let util = {};
if (process.env.NODE_ENV === 'development') {
util.isDebug = true;
} else {
util.isDebug = false;
}
//动态生成路由
util.GenerateRouter = (arr) => {
arr.forEach( item => {
if(item.childrenList){
item.childrenList.forEach(items => {
router.options.routes[0].children.push({
path:'/'+items.code,
name:items.name,
component: () => import('@/view/'+items.code+'.vue')
})
})
}
})
router.addRoutes(router.options.routes);//调用
}
// 对路由进行验证
util.routerValidation = ()=>{
router.beforeEach((to, from, next) => {
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
const route = ['index', 'list'];
let isLogin = localStorage.getItem('token'); // 是否登录
// 未登录状态;当路由到route指定页时,跳转至login
if (route.indexOf(to.name) >= 0) {
if (isLogin == null) {
router.push({ path: '/login', });
}
}
// 已登录状态;当路由到login时,跳转至home
localStorage.setItem('routerName', to.name)
if (to.name === 'login') {
if (isLogin != null) {
router.push({ path: '/', });;
}
}
next();
});
}
/**
* 补零
* @param {Number} num 数字
* @param {Number} totalLen 总长度
*/
util.fillZero = function(num, totalLen) {
return (Array(totalLen).join(0) + num).slice(-totalLen);
};
/**
* 打印日志
*/
util.log = (...rest) => {
if (!util.isDebug) {
return;
}
let d = new Date();
let dStr =
'[' +
// + d.getFullYear() + '-'
util.fillZero(d.getMonth() + 1, 2) +
'-' +
util.fillZero(d.getDate(), 2) +
' ' +
util.fillZero(d.getHours(), 2) +
':' +
util.fillZero(d.getMinutes(), 2) +
':' +
util.fillZero(d.getSeconds(), 2) +
'.' +
util.fillZero(d.getMilliseconds(), 2) +
']';
rest.unshift(dStr, location.hash);
// console.debug.apply(console, rest);
console.log.apply(console, JSON.parse(JSON.stringify(rest)));
};
util.number = function(val){
let arr = []
for(var i=1;i<=9;i++){
arr.push(Number(val-1+''+i))
}
arr.push(Number(val+''+0))
return arr;
}
export default util;
<file_sep>//获取状态值
export default {
getToken (state) {
return state.token
},
getRefreshToken(state){
return state.refreshToken
},
getNum (state) {
return state.num
},
getMenus (state){
return state.menus;
},
getImg (state){
return state.img;
},
// pushRouter(state){
// if(state.menus.length){
// state.menus.forEach(item=>{
// if(item.childrenList){
// item.childrenList.forEach(items => {
// this.$router.options.routes[0].children.push({
// path:items.url,
// name:items.code,
// component: () => import('@/view/'+items.code+'.vue')
// })
// })
// }
// })
// }
// }
}<file_sep>//定义广播事件的方法
const Event = {
SHOW_PREVIEW:'showPreview',
FORUMEDIT:'forumedit',
PDF:'showPdf'
};
const ManuscriptListStyle = {
0: '未审核',
1: '审核中',
2: '通过审核',
3: '查看结果'
}
module.exports = {
Event,
ManuscriptListStyle
}<file_sep>//引入需要挂载全局的组件
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import dayjs from 'dayjs'
import 'element-ui/lib/theme-chalk/index.css'// (根据版本路径不同会有差异,按照自己版本路径)
import store from './store/index.js'
import Axios from 'axios'
import api from './api/http'
import util from './api/utils'
import consts from './api/consts'
// import VueUeditorWrap from 'vue-ueditor-wrap'
Vue.use(ElementUI)
Vue.config.productionTip = false
//vue-tinymce-editor富文本配置
// import tinymce from 'vue-tinymce-editor'
// Vue.component('tinymce', tinymce)
//富文本
// import VueQuillEditor from 'vue-quill-editor'
// require styles 引入样式
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
// Vue.use(VueQuillEditor)
// Vue.component('vue-ueditor-wrap', VueUeditorWrap)
//修改原型链,全局使用axios,这样之后可在每个组件的methods中调用$axios命令完成数据请求
Vue.prototype.$axios = Axios;
Vue.prototype.$api = api;
Vue.prototype.$dayjs = dayjs;
Vue.prototype.$util = util;
Vue.prototype.$consts = consts;
// 对路由进行验证
util.routerValidation();
//防止vuex刷新后数据丢失问题
let dataList = JSON.parse(localStorage.getItem('menus'));
if(localStorage.getItem('homeImg')){
store.commit('homeImg',localStorage.getItem('homeImg'))
}
//解决刷新页面后动态路由丢失问题
if(dataList){
console.log("111");
util.GenerateRouter(dataList);
}
//设置全局广播事件
Vue.prototype.$eventHub= Vue.prototype.$eventHub || new Vue();
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
store,//加入sotre的配置
template: '<App/>'
})
| b39b65da70bb1e70570c5c0b0068911a82fdea95 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | MXX520/admin | 08fdd5ebd03e6fe3c00c511be795f52a74f980a4 | a4770b597219dd313ae335114098bbffbc085952 |
refs/heads/main | <file_sep># ProyectoFinalDB
Proyecto final
| 86136c0410d5e40bf64348e7e3dd223d1c0938c6 | [
"Markdown"
] | 1 | Markdown | lvm3632/ProyectoFinalDB | 64e8ba8e868948e602b0e6668a8b5d047f69056a | e240b7143fa7d26eaae14d816ae7fe12de7606b4 |
refs/heads/master | <repo_name>arichards4814/ruby-enumerables-reverse-each-word-lab-nyc-web-010620<file_sep>/reverse_each_word.rb
def reverse_each_word(string)
i = 0;
string = string.split
string2 = []
string.collect{|ele| string2.push(ele.reverse)}
string2.join(" ")
end
| 2e700b8b913c4d579f8aefe349583037104beb1c | [
"Ruby"
] | 1 | Ruby | arichards4814/ruby-enumerables-reverse-each-word-lab-nyc-web-010620 | 0cb80d2f916a6f8e92eb6fa7cf97f229ac8e3659 | 6b753374c79ff30aa2883753ad39cd03e3d150e1 |
refs/heads/master | <file_sep>'use strict';
const fuck = () => console.log('fuck');
console.fuck = fuck
export default fuck;
<file_sep># console.fuck v1.0.2
A helpful utility to log "fuck" to the console.
# Installation:
npm install console.fuck
<file_sep>'use strict';
// Utilities:
import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
// Test setup:
const expect = chai.expect;
chai.use(sinonChai);
// Under test:
import fuck from './console.fuck';
describe('console.fuck:', () => {
it('should call console.log with "fuck"', () => {
sinon.stub(console, 'log');
fuck();
expect(console.log).to.have.been.calledWith('fuck');
console.log.restore();
});
});
| f5e88c2dc4a451768b632a466419f2a39986348b | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | phenomnomnominal/console.fuck | 59da20adda6fa2c15e22c9a56b63bbbd4d4c4167 | 430b1244aa628bef9e58aa59c348bf64baa42f03 |
refs/heads/master | <repo_name>LeonelSantiago/WhichRestaurant<file_sep>/Infrastructure/Data/Repository/Repository.cs
using Infrastructure.Data._Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Data.Repository
{
public class Repository<T> : IRepository<T> where T : Entity
{
protected readonly WhichRestaurantDb _context;
public Repository(WhichRestaurantDb context)
{
_context = context;
}
public virtual T Add(T entity)
{
entity.IsEnable = 1;
_context.CreateSet<T>().Add(entity);
return entity;
}
public virtual void Edit(T entity)
{
_context.CreateSet<T>().Attach(entity);
entity.IsEnable = 1;
_context.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(IDeletable entity)
{
var entityToDelete = GetById(entity.Id);
_context.CreateSet<T>().Remove(entityToDelete);
}
public virtual void Disable(int id)
{
var entityToDisable = _context.CreateSet<T>().Single(u => u.Id == id);
entityToDisable.IsEnable = 1;
_context.Entry(entityToDisable).State = EntityState.Modified;
}
public virtual void Commit()
{
_context.SaveChanges();
}
public IQueryable<T> Get()
{
return _context.CreateSet<T>().Where(e => e.IsEnable == 1);
}
public T GetById(int id)
{
var entity = _context.CreateSet<T>().FirstOrDefault(e => e.Id == id);
entity = entity ?? (T)Activator.CreateInstance(typeof(T));
return entity;
}
public async Task<T> GetByIdAsync(int id)
{
var entity = await _context.CreateSet<T>().FirstOrDefaultAsync(e => e.Id == id);
entity = entity ?? (T)Activator.CreateInstance(typeof(T));
return entity;
}
public IQueryable<T> ExecuteRawQuery(string query, params object[] args)
{
return _context.CreateSet<T>().SqlQuery(query, args).AsQueryable();
}
public void ExecuteRawCommand(string command, params object[] args)
{
_context.Database.ExecuteSqlCommand(command, args);
}
public async Task ExecuteRawCommandAsync(string command, params object[] args)
{
await _context.Database.ExecuteSqlCommandAsync(command, args);
}
public IQueryable<TType> ExecuteRawQuery<TType>(string query, params object[] args)
{
return _context.Database.SqlQuery<TType>(query, args).AsQueryable();
}
public IQueryable<T> GetAll()
{
return _context.CreateSet<T>();
}
public T GetPersistedById(int id)
{
return _context.CreateSet<T>().Single(e => e.Id == id);
}
public async Task CommitAsync()
{
await _context.SaveChangesAsync();
}
public virtual void Save(T entity)
{
if (entity.Id == 0)
Add(entity);
else
Edit(entity);
}
}
}
<file_sep>/Infrastructure/Domain/Repository/GenericRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain.IRepository;
using Infrastructure.Domain._Core;
namespace Infrastructure.Domain.Repository
{
public class GenericRepository<T> :
IGenericRepository<T> where T : class
{
private readonly WhichRestaurantDb _context;
public GenericRepository(WhichRestaurantDb context)
{
_context = context;
}
public virtual IQueryable<T> GetAll()
{
IQueryable<T> query = _context.Set<T>();
return query;
}
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
IQueryable<T> query = _context.Set<T>().Where(predicate);
return query;
}
public virtual void Add(T entity)
{
_context.Set<T>().Add(entity);
}
public virtual void Delete(T entity)
{
_context.Set<T>().Remove(entity);
}
public virtual void Edit(T entity)
{
_context.Entry(entity).State = EntityState.Modified;
}
public virtual void Save()
{
_context.SaveChanges();
}
}
}
<file_sep>/WhichRestaurantApi/Controllers/MenuItemsApiController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Infrastructure.Data.Repository;
using Infrastructure.Domain.Entities;
namespace WhichRestaurantApi.Controllers
{
public class MenuItemsApiController : ApiController
{
private readonly Repository<MenuItem> _repository;
public MenuItemsApiController(Repository<MenuItem> repository)
{
_repository = repository;
}
[Route("")]
public IQueryable<MenuItem> GetMenuItems()
{
return _repository.GetAll();
}
[Route("{id}")]
public IHttpActionResult GetMenuItem(int id)
{
MenuItem menuItem = _repository.GetById(id);
if (menuItem == null)
{
return NotFound();
}
return Ok(menuItem);
}
[Route("Edit")]
public IHttpActionResult Edit([FromUri] MenuItem menuItem)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Edit(menuItem);
_repository.Save(menuItem);
return StatusCode(HttpStatusCode.OK);
}
[Route("Create")]
public IHttpActionResult Create([FromUri] MenuItem menuItem)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Add(menuItem);
_repository.Save(menuItem);
return CreatedAtRoute("DefaultApi", new { id = menuItem.Id }, menuItem);
}
}
}
<file_sep>/Infrastructure/Domain/Entities/Menu.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Domain.Entities
{
public class Menu : Entity
{
public string Description { get; set; }
}
}
<file_sep>/WhichRestaurantApi/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs
using System;
namespace WhichRestaurantApi.Areas.HelpPage.ModelDescriptions
{
public class ParameterAnnotation
{
public Attribute AnnotationAttribute { get; set; }
public string Documentation { get; set; }
}
}<file_sep>/WhichRestaurantApi/Controllers/RestaurantTypesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Infrastructure.Data.Repository;
using Infrastructure.Domain.Entities;
namespace WhichRestaurantApi.Controllers
{
public class RestaurantTypesController : ApiController
{
private readonly Repository<RestaurantType> _repository;
public RestaurantTypesController(Repository<RestaurantType> repository)
{
_repository = repository;
}
[Route("")]
public IQueryable<RestaurantType> GetRestaurantTypes()
{
return _repository.GetAll();
}
[Route("{id}")]
public IHttpActionResult GetRestaurantType(int id)
{
RestaurantType restaurantType = _repository.GetById(id);
if (restaurantType == null)
{
return NotFound();
}
return Ok(restaurantType);
}
[Route("Edit")]
public IHttpActionResult Edit([FromUri] RestaurantType restaurantType)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Edit(restaurantType);
_repository.Save(restaurantType);
return StatusCode(HttpStatusCode.OK);
}
[Route("Create")]
public IHttpActionResult Create([FromUri] RestaurantType restaurantType)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Add(restaurantType);
_repository.Save(restaurantType);
return CreatedAtRoute("DefaultApi", new { id = restaurantType.Id }, restaurantType);
}
}
}
<file_sep>/Infrastructure/Service/RestaurantService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Data._Core;
using Infrastructure.Domain.Entities;
namespace Infrastructure.Service
{
public class RestaurantService
{
private readonly IRepository<Restaurant> _repository;
public RestaurantService(IRepository<Restaurant> repository)
{
_repository = repository;
}
public async Task<Restaurant> GetRequest(int requestId)
{
var restaurant = await _repository.GetByIdAsync(requestId);
return restaurant;
}
public void Add(Restaurant restaurant)
{
_repository.Add(restaurant);
}
public void Edit(Restaurant restaurant)
{
_repository.Edit(restaurant);
}
public async Task SaveAsync(Restaurant restaurant)
{
await _repository.CommitAsync();
}
}
}
<file_sep>/Infrastructure/Domain/Entities/RestaurantType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Domain.Entities
{
public class RestaurantType : Entity
{
}
}
<file_sep>/WhichRestaurantApi/Controllers/MenusApiController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Infrastructure.Data.Repository;
using Infrastructure.Domain.Entities;
namespace WhichRestaurantApi.Controllers
{
public class MenusApiController : ApiController
{
private readonly Repository<Menu> _repository;
public MenusApiController(Repository<Menu> repository)
{
_repository = repository;
}
[Route("")]
public IQueryable<Menu> GetMenus()
{
return _repository.GetAll();
}
[Route("{id}")]
public IHttpActionResult GetRestaurant(int id)
{
Menu menu = _repository.GetById(id);
if (menu == null)
{
return NotFound();
}
return Ok(menu);
}
[Route("Edit")]
public IHttpActionResult Edit([FromUri] Menu menu)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Edit(menu);
_repository.Save(menu);
return StatusCode(HttpStatusCode.OK);
}
[Route("Create")]
public IHttpActionResult Create([FromUri] Menu menu)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Add(menu);
_repository.Save(menu);
return CreatedAtRoute("DefaultApi", new { id = menu.Id }, menu);
}
}
}
<file_sep>/Infrastructure/Domain/Entities/Restaurant.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Domain.Entities
{
public class Restaurant : Entity
{
public string Name { get; set; }
public string Description { get; set; }
public string Address { get; set; }
public string GoogleMapsLocation { get; set; }
public string PrimaryPhoneNumber { get; set; }
public string SecondaryPhoneNumber { get; set; }
public string WebSite { get; set; }
public string OpeningHour { get; set; }
public string ClosingHour { get; set; }
public int RestaurantType { get; set; }
public int MenuId { get; set; }
}
}
<file_sep>/Infrastructure/Data/_Core/IDeletable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.Data._Core
{
public interface IDeletable
{
int Id { get; set; }
}
}
<file_sep>/Infrastructure/Domain/_Core/WhichRestaurantDb.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain.Entities;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Infrastructure.Domain._Core
{
public class WhichRestaurantDb : IdentityDbContext
{
public WhichRestaurantDb() : base("DefaultConnection")
{
}
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<RestaurantType> RestaurantTypes { get; set; }
public DbSet<Menu> Menus { get; set; }
public DbSet<MenuItem> MenuItems { get; set; }
public DbSet<TEntity> CreateSet<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
}
}
<file_sep>/Infrastructure/Data/_Core/IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Data._Core
{
public interface IRepository<T> : IUnitOfWork where T: Entity
{
T Add(T entity);
void Edit(T entity);
void Delete(IDeletable entity);
void Save(T entity);
IQueryable<T> Get();
IQueryable<T> GetAll();
T GetById(int id);
Task<T> GetByIdAsync(int id);
T GetPersistedById(int id);
void Disable(int id);
IQueryable<T> ExecuteRawQuery(string query, params object[] args);
IQueryable<TType> ExecuteRawQuery<TType>(string query, params object[] args);
void ExecuteRawCommand(string command, params object[] args);
Task ExecuteRawCommandAsync(string command, params object[] args);
}
}
<file_sep>/WhichRestaurantApi/Controllers/RestaurantsApiController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Infrastructure.Data.Repository;
using Infrastructure.Domain.Entities;
using Infrastructure.Domain._Core;
namespace WhichRestaurantApi.Controllers
{
[RoutePrefix("api/restaurants")]
public class RestaurantsApiController : ApiController
{
private readonly Repository<Restaurant> _repository;
public RestaurantsApiController(Repository<Restaurant> repository)
{
_repository = repository;
}
[Route("")]
public IQueryable<Restaurant> GetRestaurants()
{
return _repository.GetAll();
}
[Route("{id}")]
public IHttpActionResult GetRestaurant(int id)
{
Restaurant restaurant = _repository.GetById(id);
if (restaurant == null)
{
return NotFound();
}
return Ok(restaurant);
}
[Route("Edit")]
public IHttpActionResult Edit([FromUri] Restaurant restaurant)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Edit(restaurant);
_repository.Save(restaurant);
return StatusCode(HttpStatusCode.OK);
}
[Route("")]
[HttpPost]
public IHttpActionResult Create([FromUri] Restaurant restaurant)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_repository.Add(restaurant);
_repository.Save(restaurant);
return CreatedAtRoute("DefaultApi", new { id = restaurant.Id }, restaurant);
}
}
}<file_sep>/Infrastructure/Domain/Entities/MenuItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Domain._Core;
namespace Infrastructure.Domain.Entities
{
public class MenuItem : Entity
{
public int MenuId { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
}
<file_sep>/WhichRestaurantWebApp/Utils/RequestHandler.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Web;
namespace WhichRestaurantWebApp.Utils
{
public class RequestHandler
{
private static string baseUrl = ConfigurationManager.AppSettings["WebApiEndPoint"];
private readonly string _apiKey = "<KEY>";
private readonly string _secret = "secret";
private string _token = "";
private string _errorString = "ERROR";
private static object _lockObject = new object();
private static RequestHandler _instance;
private RequestHandler()
{
}
public static RequestHandler Instance
{
get
{
if (_instance == null)
{
lock (_lockObject)
{
if (_instance == null)
_instance = new RequestHandler();
}
}
return _instance;
}
}
public async Task Get<T>(string url, dynamic parameters, Func<T, Task> Success, Func<HttpResponseMessage, Task> Failure) where T : new()
{
Url apiUrl = null;
if (parameters == null)
{
apiUrl = baseUrl.AppendPathSegment(url);
}
else
{
apiUrl = baseUrl.AppendPathSegment(url).SetQueryParams(parameters);
}
}
public async Task Get<T>(string url, dynamic parameters, Action<T> Success, Action<HttpResponseMessage> Failure)
{
Url apiUrl = null;
if (parameters == null)
{
apiUrl = baseUrl.AppendPathSegment(url);
}
else
{
apiUrl = baseUrl.AppendPathSegment(url).SetQueryParams(parameters);
}
using (var client = new HttpClient())
{
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
Success(result);
}
else
{
Failure(response);
}
}
}
public async Task Get(string url, dynamic parameters, Func<Task> Success, Func<HttpResponseMessage, Task> Failure)
{
Url apiUrl = null;
if (parameters == null)
{
apiUrl = baseUrl.AppendPathSegment(url);
}
else
{
apiUrl = baseUrl.AppendPathSegment(url).SetQueryParams(parameters);
}
using (var client = new HttpClient())
{
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
await Success();
}
else
{
await Failure(response);
}
}
}
public Task Get<T>(string url, Func<T, Task> Success, Func<HttpResponseMessage, Task> Failure) where T : new()
{
return Get(url, null, Success, Failure);
}
public Task Get<T>(string url, Action<T> Success, Action<HttpResponseMessage> Failure) where T : new()
{
return Get(url, null, Success, Failure);
}
public async Task Post<T>(string url, object parameters, Func<T, Task> Success, Func<HttpResponseMessage, Task> Failure) where T : new()
{
Url apiUrl = baseUrl.AppendPathSegment(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
var response = new HttpResponseMessage();
if (parameters == null)
{
response = await client.PostAsJsonAsync(apiUrl, new { });
}
else
{
response = await client.PostAsJsonAsync(apiUrl, parameters);
}
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
await Success(result);
}
else
{
await Failure(response);
}
}
}
public async Task Post<T>(string url, MultipartFormDataContent multiPartData, Action<T> Success, Action<HttpResponseMessage> Failure) where T : new()
{
Url apiUrl = baseUrl.AppendPathSegment(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
var response = new HttpResponseMessage();
if (multiPartData == null)
{
throw new InvalidOperationException("Multipart Data cannot be null");
}
else
{
response = await client.PostAsJsonAsync(apiUrl, multiPartData);
}
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
Success(result);
}
else
{
Failure(response);
}
}
}
}
public async Task Post<T>(string url, object parameters, Action<T> Success, Action<HttpResponseMessage> Failure) where T : new()
{
Url apiUrl = baseUrl.AppendPathSegment(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
var response = new HttpResponseMessage();
if (parameters == null)
{
response = await client.PostAsJsonAsync(apiUrl, new { });
}
else
{
response = await client.PostAsJsonAsync(apiUrl, parameters);
}
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
Success(result);
}
else
{
Failure(response);
}
}
}
public async Task Post<T, TResponse>(string url, object parameters, Action<T> Success, Action<TResponse> BadRequest, Action<HttpResponseMessage> Failure) where T : new()
{
Url apiUrl = baseUrl.AppendPathSegment(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
var response = new HttpResponseMessage();
if (parameters == null)
{
response = await client.PostAsJsonAsync(apiUrl, new { });
}
else
{
response = await client.PostAsJsonAsync(apiUrl, parameters);
}
switch (response.StatusCode)
{
case HttpStatusCode.OK:
var result = await response.Content.ReadAsAsync<T>();
Success(result);
break;
case HttpStatusCode.BadRequest:
var badRequestResult = await response.Content.ReadAsAsync<TResponse>();
BadRequest(badRequestResult);
break;
default:
Failure(response);
break;
}
}
}
public async Task Delete<T>(string url, Func<T, Task> Success, Func<HttpResponseMessage, Task> Failure) where T : new()
{
Url apiUrl = baseUrl.AppendPathSegment(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
var response = new HttpResponseMessage();
response = await client.DeleteAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
await Success(result);
}
else
{
await Failure(response);
}
}
}
}
} | ffa7fe018cf5361cef30b7924fb11bd3676facfa | [
"C#"
] | 16 | C# | LeonelSantiago/WhichRestaurant | 13d7009136793db7526c317878f21af10403476b | d67fc2b85ea9841ff38bfa8f018b71b4777760b0 |
refs/heads/master | <file_sep># headsUp.js #
Hide and show a fixed header at scrolling speed, inspired by iOS headers.
<file_sep>function headsUp(el) {
var elH = el.clientHeight,
offset = 0,
lastScroll = 0;
function makeOffset() {
var scrollY = document.documentElement.scrollTop || document.body.scrollTop,
diff = scrollY - lastScroll;
offset = (offset + diff > elH) ? elH : (scrollY < 0) ? 0 : offset + diff;
offset = (offset < 0) ? 0 : offset;
el.style.top = (-offset) + 'px';
lastScroll = scrollY;
}
if (window.addEventListener) return window.addEventListener('scroll', makeOffset);
window.attachEvent('onscroll', makeOffset);
}
var header = document.querySelectorAll('header')[0];
headsUp(header); | 7051757cb1c3145ed43b2425b09cce02ba886538 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | edwardpayton/headsUp | f24381c76cca8256014239fa6a1ae8b9e92018b3 | 48af949a3c3cad37eaddf6936889e3136d77438e |
refs/heads/main | <file_sep>import React from "react";
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import blogActions from "../redux/actions/blog.actions";
import { useParams } from "react-router-dom";
import Avatar from "@material-ui/core/Avatar";
import Moment from "react-moment";
import ReviewBlog from "../components/ReviewBlog";
import authActions from "../redux/actions/auth.actions";
import { makeStyles } from "@material-ui/core/styles";
import Reviews from "../components/Reviews";
import ReviewReactions from "../components/ReviewReactions";
import { Link } from "react-router-dom";
import ClipLoader from "react-spinners/ClipLoader";
const useStyles = makeStyles((theme) => ({
root: {
alignItems: "center",
display: "flex",
"& > *": {
margin: theme.spacing(1),
},
},
}));
function BlogDetailPage() {
const classes = useStyles();
const { blogId } = useParams();
const blogDetail = useSelector((state) => state.blog.selectedBlog);
const loading = useSelector((state) => state.blog.loadingSelectedBlog);
const dispatch = useDispatch();
const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
const [review, setReview] = useState("");
const loadingSubmit = useSelector((state) => state.blog.loadingSubmitReview);
const currentUserId = useSelector((state) => state.auth.user._id);
// console.log("Loading submit review", loadingSubmit);
// console.log("current user", currentUserId);
// console.log("blog", blogAuthorId);
useEffect(() => {
dispatch(blogActions.getSingleBlog(blogId));
dispatch(authActions.getCurrentUser());
}, [dispatch, blogId]);
const handleInputChange = (e) => {
setReview(e.target.value);
};
const handleSubmitReview = (e) => {
e.preventDefault();
dispatch(blogActions.createReview(blogId, review));
setReview("");
};
console.log("blog detail", blogDetail);
if (!(loading || blogDetail === undefined)) {
const reactions = blogDetail.reactions;
const id = blogDetail._id;
const blogAuthorId = blogDetail.author._id;
return (
<div>
{currentUserId === blogAuthorId ? (
<Link to={`/blogs/edit/${id}`}>
{" "}
<button
type="button"
class="btn btn-info mt-2"
style={{ marginLeft: "90%" }}
>
Edit
</button>
</Link>
) : (
<></>
)}
<div id="wrapper">
<div id="leftmenu">
<img
src={
blogDetail.images.length
? blogDetail.images[0]
: "https://i.ytimg.com/vi/2QWdjeMRMEw/hqdefault.jpg"
}
height="100%"
width="100%"
/>
</div>
<div id="maincontent" className="mt-2">
<div>
<div>
<div>
<div className={classes.root}>
<Avatar
aria-label="avatar"
src={blogDetail.author.avatarUrl}
className="ml-5"
margin="0px"
></Avatar>
<div
className="ml-2"
style={{ fontSize: "20px", fontWeight: "bold" }}
>
{blogDetail.author.name}
</div>
</div>
<div className="card-title">
{blogDetail.title}
<p className="card-text">{blogDetail.content}</p>
{<Moment fromNow>{blogDetail.createdAt}</Moment>}
</div>
</div>
</div>
<div>
<ReviewReactions
targetType="Blog"
id={id}
reactions={reactions}
/>
</div>
<div>
<Reviews targetType="Blog" reviews={blogDetail.reviews} />
</div>
<div>
{isAuthenticated && (
<ReviewBlog
review={review}
handleInputChange={handleInputChange}
handleSubmitReview={handleSubmitReview}
loading={loadingSubmit}
/>
)}
</div>
</div>
</div>
</div>
</div>
);
}
return (
<div>
<ClipLoader color="blue" loading={loading} size={150} />
</div>
);
}
export default BlogDetailPage;
<file_sep>import * as types from "../constants/blog.constants";
const initialState = {
// all blogs
blogPosts: [],
loading: true,
totalPages: null,
//single blog
selectedBlog: null,
loadingSelectedBlog: true,
loadingSubmitReview: false,
loadingSubmitReaction: true,
};
const blogReducer = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
// get Blogs
case types.GET_BLOGS_REQUEST:
return { ...state, loading: true };
case types.GET_BLOGS_SUCCESS:
return {
...state,
blogPosts: payload.blogs,
totalPages: payload.totalPages,
loading: false,
};
case types.GET_BLOGS_FAILURE:
return { ...state, loading: false };
// single blog
case types.GET_SINGLE_BLOGS_REQUEST:
return { ...state, loadingSelectedBlog: true };
case types.GET_SINGLE_BLOGS_SUCCESS:
return { ...state, loadingSelectedBlog: false, selectedBlog: payload };
case types.GET_SINGLE_BLOGS_FAILURE:
return { ...state, loadingSelectedBlog: false };
// create reviews
case types.CREATE_REVIEW_REQUEST:
return { ...state, loadingSubmitReview: true };
case types.CREATE_REVIEW_SUCCESS:
return {
...state,
loadingSubmitReview: false,
selectedBlog: {
...state.selectedBlog,
reviews: [...state.selectedBlog.reviews, payload],
},
};
case types.CREATE_REVIEW_FAILURE:
return { ...state, loadingSubmitReview: false };
case types.REACTION_REQUEST:
return { ...state, loadingSubmitReaction: true };
case types.REACTION_SUCCESS:
return {
...state,
selectedBlog: { ...state.selectedBlog, reactions: payload },
loadingSubmitReaction: false,
};
case types.REVIEW_REACTION_SUCCESS:
console.log("hehe", payload.reviewId);
return {
...state,
selectedBlog: {
...state.selectedBlog,
reviews: [
...state.selectedBlog.reviews.map((review) => {
if (review._id !== payload.reviewId) return review;
return { ...review, reactions: payload.reactions };
}),
],
},
loadingSubmitReaction: false,
};
case types.UPDATE_BLOG_REQUEST:
return { ...state, loading: true };
case types.UPDATE_BLOG_SUCCESS:
return {
...state,
selectedBlog: payload,
loading: false,
};
case types.UPDATE_BLOG_FAILURE:
return { ...state, loading: false };
case types.REACTION_FAILURE:
return { ...state, loadingSelectedBlog: false };
//delete blog:
case types.DELETE_BLOG_REQUEST:
return { ...state, loading: true };
case types.DELETE_BLOG_SUCCESS:
return {
...state,
loading: false,
selectedBlog: {},
};
case types.DELETE_BLOG_FAILURE:
return { ...state, loading: false };
default:
return state;
}
};
export default blogReducer;
<file_sep>import axios from "axios";
const api = axios.create({
baseURL: process.env.REACT_APP_BACKEND_API,
// baseURL: "https://social-blog-cs.herokuapp.com/api",
headers: {
"Accept": "text/plain",
"Content-Type": "application/json",
},
});
/**
* console.log all requests and responses
*/
api.interceptors.request.use(
(request) => {
console.log("Starting Request", request);
const token = localStorage.getItem("token")
if(token) {
request.headers['Authorization'] = 'Bearer ' + token;
}
return request;
},
function (error) {
console.log("REQUEST ERROR", error);
}
);
api.interceptors.response.use(
(response) => {
console.log("Response:", response);
if(response.data.data.accessToken) {
localStorage.setItem("token", response.data.data.accessToken)
}
return response;
},
function (error) {
error = error.response.data;
console.log("RESPONSE ERROR", error);
return Promise.reject({ message: error.errors.message});
}
);
export default api;
<file_sep>import React from "react";
import { Form , Col,Button} from "react-bootstrap";
const Search = ({ searchInput, handleSearchChange, handleSearchSubmit }) => {
return (
<div>
<Form onSubmit={handleSearchSubmit}>
<Form.Row>
<Col>
<Form.Control
type="text"
placeholder="Search..."
value={searchInput}
onChange={handleSearchChange}
/>
</Col>
<Col>
<Button variant="primary" type="submit">
Search
</Button>
</Col>
</Form.Row>
</Form>
</div>
);
};
export default Search;
<file_sep>import React from 'react'
const MessengerPage = () => {
return (
<div>
Messenger
</div>
)
}
export default MessengerPage
<file_sep>import React, { useEffect } from "react";
import { BrowserRouter, Link } from "react-router-dom";
import { Navbar, Nav, NavDropdown } from "react-bootstrap";
import LoginPage from "../containers/LoginPage";
import AdminPage from "../containers/Admin/AdminPage";
import ProfilePage from "../containers/Admin/AdminSideBar/ProfilePage";
import { useSelector, useDispatch } from "react-redux";
import logo from "../images/logo.png";
import authActions from "../redux/actions/auth.actions";
const PublicNavBar = () => {
const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
const loading = useSelector((state) => state.auth.loading);
const dispatch = useDispatch();
const logout = () => {
dispatch(authActions.logout());
};
const publicNav = (
<Nav>
<Nav.Link eventKey={"register"} as={Link} to="/register">
Register
</Nav.Link>
<Nav.Link eventKey={"login"} as={Link} to="/login">
Login
</Nav.Link>
</Nav>
);
const authNav = (
<Nav>
{/* <Nav.Link eventKey={"admin"} as={Link} to="/admin/profile">
Admin
</Nav.Link> */}
<NavDropdown title="Admin" id="collasible-nav-dropdown">
<NavDropdown.Item as={Link} to = "/admin/profile">Profile</NavDropdown.Item>
<NavDropdown.Item as={Link} to = "/admin/blog">Blogs</NavDropdown.Item>
<NavDropdown.Item as={Link} to = "/admin/friend">Friends</NavDropdown.Item>
<NavDropdown.Item as={Link} to = "/admin/messenger">Messenger</NavDropdown.Item>
</NavDropdown>
<Nav.Link eventKey={"logout"} as={Link} to="/" onClick={logout}>
Logout
</Nav.Link>
</Nav>
);
return (
<div>
<Navbar
collapseOnSelect
expand="lg"
style={{ backgroundColor: "#dffaf9" }}
variant="light"
>
<Navbar.Brand as={Link} to="/">
<img style={{ height: "2em" }} src={logo} atl="logo" />
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto"></Nav>
{!loading && <>{isAuthenticated ? authNav : publicNav}</>}
</Navbar.Collapse>
</Navbar>
</div>
);
};
export default PublicNavBar;
{
/* USE THESE FOR SPECIAL SORTING FEATURES IF POSSIBLE
<Nav.Link href=""></Nav.Link>
<Nav.Link href=""></Nav.Link>
<NavDropdown title="Dropdown" id="collasible-nav-dropdown">
<NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
<NavDropdown.Item href="#action/3.2">
Another action
</NavDropdown.Item>
<NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="#action/3.4">
Separated link
</NavDropdown.Item>
</NavDropdown> */
}
<file_sep># SOCIAL APP *
Created with love by <NAME>, <NAME>, and Prince ❤
View online at: https://katymovie.netlify.app/
Rest API built by Coderschool: https://social-blog-cs.herokuapp.com
This social blog application using React, Redux, Redux Thunk, and React Router. The idea is an application that helps user to share their experiences after a trip in a blog post. The other users can leave reviews/comments and give "reaction" (laugh, like, sad, love, angry) to the blog post.
### `Project Detail`
# Features:
* [x] User can see all the blog posts on the homepage, order by created time \
* [x] User can register to have an account \
* [x] User can log in with username and password \
* [x] After login user can write blog posts, edit and delete his/her own blog posts \
* [x] After login user can write reviews for blog posts \
* [x] Before submitting data to the server, the data should be validated \
* [x] User stays logged in after refreshing browser.
* [x] After login, user can react (laugh, like, sad, love, angry) to blog posts \
* [x] Pagination for blogs, reviews \
* [x] Searching and sorting of blogs
### Plan for **additional** features:
* [x] User can send friend request to another user \
* [x] User can accept/decline a friend request \
* [x] User can see list of his/her friends
## Time Spent and Lessons Learned
Time spent: **60** hours spent in total.
## License
Copyright [2021] [<NAME>]
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.
## Private Rest API built by Coderschool: https://social-blog-cs.herokuapp.com
<file_sep>import React from "react";
import { Container, Col, Row, Tab, Nav } from "react-bootstrap";
import ProfilePage from "../containers/Admin/AdminSideBar/ProfilePage";
import BlogTablePage from "../containers/Admin/AdminSideBar/BlogTablePage";
import FriendsPage from "../containers/Admin/AdminSideBar/FriendsPage";
import MessengerPage from "../containers/Admin/AdminSideBar/MessengerPage";
const AdminTabs = () => {
return (
<div className="mt-5">
<Tab.Container id="adminPage" defaultActiveKey="first">
<Row>
<Col sm={3}>
<Nav variant="pills" className="flex-column">
<Nav.Item>
<Nav.Link eventKey="a">Profile</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="b">Blogs</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="c">Friends</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="d">Messenger</Nav.Link>
</Nav.Item>
</Nav>
</Col>
<Col sm={9}>
<Tab.Content >
<Tab.Pane eventKey="a">
<ProfilePage />
</Tab.Pane>
<Tab.Pane eventKey="b">
<BlogTablePage />
</Tab.Pane>
<Tab.Pane eventKey="c">
<FriendsPage />
</Tab.Pane>
<Tab.Pane eventKey="d">
<MessengerPage />
</Tab.Pane>
</Tab.Content>
</Col>
</Row>
</Tab.Container>
</div>
);
};
export default AdminTabs;
<file_sep>import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import blogActions from "../../../redux/actions/blog.actions";
import authActions from "../../../redux/actions/auth.actions";
import ClipLoader from "react-spinners/ClipLoader";
import PaginationBar from "../../../components/PaginationBar";
import { Container, Table, Row, Col, FormCheck } from "react-bootstrap";
import Moment from "react-moment";
import { Link } from "react-router-dom";
import Search from "../../../components/Search";
const BlogTablePage = () => {
const [searchInput, setSearchInput] = useState("");
const [pageNum, setPageNum] = useState(1);
const [field_name, setField_name] = useState("");
const [myBlogOnly, setMyBlogOnly] = useState(false);
const blogs = useSelector((state) => state.blog.blogPosts);
const loading = useSelector((state) => state.blog.loading);
const totalPages = useSelector((state) => state.blog.totalPages);
const currentUser = useSelector((state) => state.auth.user);
const limit = 10;
const dispatch = useDispatch();
console.log("currentUser", currentUser._id);
useEffect(() => {
dispatch(authActions.getCurrentUser());
}, [dispatch]);
useEffect(() => {
dispatch(blogActions.getBlogs(pageNum, limit, field_name, myBlogOnly));
}, [dispatch, pageNum, limit, field_name,myBlogOnly]);
const handleSearchChange = (e) => {
setSearchInput(e.target.value);
};
const handleSearchSubmit = (e) => {
e.preventDefault();
if(searchInput !== "") {
setField_name(searchInput);
} else {
setField_name("")
}
};
const handleCheckMyBlogOnly = () => {
if (myBlogOnly) {
setMyBlogOnly(false);
} else {
setMyBlogOnly(currentUser._id);
}
};
return (
<div>
{loading ? (
<ClipLoader color="blue" loading={loading} size={150} />
) : (
<div>
<h1>Blog Manage</h1>
<Container>
<Row>
<Col md={4}>
<Search
searchInput={searchInput}
handleSearchChange={handleSearchChange}
handleSearchSubmit={handleSearchSubmit}
/>
;
</Col>
<Col
md={4}
className="d-flex justify-content-end align-items-start"
>
<FormCheck
type="checkbox"
label="My Blogs only"
checked={myBlogOnly}
onChange={handleCheckMyBlogOnly}
/>
</Col>
<Col
md={4}
className="d-flex justify-content-end align-items-start"
>
<Link className="btn btn-primary" to="/blogs/add">
Add
</Link>
</Col>
</Row>
<Row>
<Col>
<Table striped bordered hover>
<thead>
<tr >
<th>Title</th>
<th>Author</th>
<th>Review Count</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
{blogs.map((blog) => (
<tr key = {blog._id}>
<td>
<Link to={`/blogs/${blog._id}`}>{blog.title}</Link>
</td>
<td>{blog.author.name}</td>
<td>{blog.reviewCount}</td>
<td>{<Moment fromNow>{blog.createdAt}</Moment>}</td>
</tr>
))}
</tbody>
</Table>
</Col>
</Row>
</Container>
<PaginationBar
pageNum={pageNum}
setPageNum={setPageNum}
totalPages={totalPages}
/>
</div>
)}
</div>
);
};
export default BlogTablePage;
<file_sep>import React from "react";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
function ReviewBlog({
review,
handleInputChange,
handleSubmitReview,
loading,
}) {
return (
<div>
<Form onSubmit={handleSubmitReview}>
<Form.Group as={Row}>
<Form.Label htmlFor="review" column sm="2" className="ml-2">
Review:
</Form.Label>
<Col sm="7">
<Form.Control
id="review"
type="text"
value={review}
onChange={handleInputChange}
/>
</Col>
{loading ? (
<Button variant="primary" type="button" disabled>
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
Submitting ..
</Button>
) : (
<Button type="submit" disabled={!review}>
Submit
</Button>
)}
</Form.Group>
</Form>
</div>
);
}
export default ReviewBlog;
<file_sep>import React from "react";
import { useDispatch, useSelector } from "react-redux";
import blogActions from "../redux/actions/blog.actions";
function BlogDetail({ id }) {
const blogDetail = useSelector((state) => state.blog.selectedBlog);
const loading = useSelector((state) => state.blog.loadingSelectedBlog);
return <div>{id}</div>;
}
export default BlogDetail;
<file_sep>import * as types from "../constants/auth.constants";
import api from "../../apiService";
import { toast } from "react-toastify";
const login = (email, password) => async (dispatch) => {
dispatch({ type: types.LOGIN_REQUEST });
try {
const response = await api.post("/auth/login", {
email,
password,
});
if (response.data.success === true) {
dispatch({
type: types.LOGIN_SUCCESS,
payload: response.data.data.accessToken,
});
}
} catch (error) {
toast.configure();
toast.error("😥 Please check your email or password!", {
position: "top-right",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
dispatch({ type: types.LOGIN_FAILURE, payload: error.message });
}
};
const logout = () => (dispatch) => {
delete api.defaults.headers.common["authorization"];
localStorage.removeItem("token");
dispatch({ type: types.LOGOUT, payload: null });
};
const register = (name, email, password, avatarUrl) => async (dispatch) => {
dispatch({ type: types.REGISTER_REQUEST, payload: null });
try {
const res = await api.post("/users", { name, email, password, avatarUrl });
dispatch({ type: types.REGISTER_SUCCESS, payload: res.data.data });
toast.configure();
await toast.success(`Thank you for your registration, ${name}!`);
//go back to home temorarily
window.location.replace("http://localhost:3000/login");
} catch (error) {
dispatch({ type: types.REGISTER_FAILURE, payload: error });
}
};
const getCurrentUser = () => async (dispatch) => {
dispatch({ type: types.GET_CURRENT_USER_REQUEST, payload: null });
try {
const res = await api.get("/users/me");
dispatch({ type: types.GET_CURRENT_USER_SUCCESS, payload: res.data.data });
} catch (error) {
dispatch({ type: types.GET_CURRENT_USER_FAILURE, payload: error });
}
};
const updateBlog = (blogId, title, content, images) => async (dispatch) => {
dispatch({ type: types.UPDATE_BLOG_REQUEST, payload: null });
try {
const res = await api.put(`/blogs/${blogId}`, { title, content, images });
dispatch({
type: types.UPDATE_BLOG_SUCCESS,
payload: res.data.data,
});
toast.configure();
await toast.success(`You have just updated your blog`);
window.location.replace("http://localhost:3000/login");
} catch (error) {
dispatch({ type: types.UPDATE_BLOG_FAILURE, payload: error });
}
};
const updateProfile = (name, avatarUrl) => async (dispatch) => {
dispatch({ type: types.UPDATE_PROFILE_REQUEST });
try {
const url = "/users";
const res = await api.put(url, { name, avatarUrl });
if (res.data.success === true) {
dispatch({ type: types.GET_USER_SUCCESS, payload: res.data.data });
}
} catch (error) {
dispatch({ type: types.UPDATE_PROFILE_FAILURE, payload: error.message });
}
};
const authActions = {
login,
logout,
register,
getCurrentUser,
updateBlog,
updateProfile,
};
export default authActions;
<file_sep>export const LOGIN_REQUEST = "USER.LOGIN_REQUEST";
export const LOGIN_SUCCESS = "USER.LOGIN_SUCCESS";
export const LOGIN_FAILURE = "USER.LOGIN_FAILURE";
export const LOGOUT = "USER_LOGOUT ";
export const REGISTER_REQUEST = "REGISTER_REQUEST";
export const REGISTER_SUCCESS = "REGISTER_SUCCESS";
export const REGISTER_FAILURE = "REGISTER_FAILURE";
export const GET_CURRENT_USER_REQUEST = "GET_CURRENT_USER_REQUEST";
export const GET_CURRENT_USER_SUCCESS = "GET_CURRENT_USER_SUCCESS";
export const GET_CURRENT_USER_FAILURE = "GET_CURRENT_USER_FAILURE";
export const UPDATE_BLOG_REQUEST = "UPDATE_BLOG_REQUEST";
export const UPDATE_BLOG_SUCCESS = "UPDATE_BLOG_SUCCESS";
export const UPDATE_BLOG_FAILURE = "UPDATE_BLOG_FAILURE";
export const GET_USER_REQUEST = "GET_USER_REQUEST";
export const GET_USER_SUCCESS = "GET_USER_SUCCESS";
export const GET_USER_FAILURE = "GET_USER_FAILURE";
export const UPDATE_PROFILE_REQUEST = "UPDATE_PROFILE_REQUEST";
export const UPDATE_PROFILE_SUCCESS = "UPDATE_PROFILE_SUCCESS";
export const UPDATE_PROFILE_FAILURE = "UPDATE_PROFILE_FAILURE";
<file_sep>import React from 'react'
const FriendsPage = () => {
return (
<div>
Freinds
</div>
)
}
export default FriendsPage
<file_sep>import React, { useState, useEffect } from "react";
import { Link, useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import authActions from "../redux/actions/auth.actions";
import { Form, Button, Container, Row, Col } from "react-bootstrap";
import FaceIcon from "@material-ui/icons/Face";
import PublicNavBar from "../components/PublicNavBar";
const RegisterPage = () => {
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
password2: "",
avatarUrl: "",
});
const dispatch = useDispatch();
const loading = useSelector((state) => state.auth.loading);
const handleChange = (e) =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const handleSubmit = (e) => {
e.preventDefault();
const { name, email, password, password2, avatarUrl } = formData;
if (name === "" || email === "" || password === "" || password2 === "") {
alert("Please input all required information");
return;
}
if (password !== <PASSWORD>) {
alert("Password does not match");
return;
}
// TODO: handle Register
dispatch(authActions.register(name, email, password, avatarUrl));
};
const uploadWidget = () => {
window.cloudinary.openUploadWidget(
{
cloud_name: process.env.REACT_APP_CLOUDINARY_CLOUD_NAME,
upload_preset: process.env.REACT_APP_CLOUDINARY_PRESET,
},
function (error, result) {
if (error) console.log(error);
if (result && result.length && !error) {
setFormData({
...formData,
avatarUrl: result[0].secure_url,
});
}
}
);
};
return (
<div>
<PublicNavBar />
<Container>
<Row>
<Col md={{ span: 6, offset: 3 }}>
<div className="text-center mb-3">
<h1 className="text-danger"> Sign Up</h1>
<span>It’s quick and easy.</span> <FaceIcon />
</div>
<Form onSubmit={handleSubmit}>
<Form.Group>
<div className="text-center"></div>
</Form.Group>
<Form.Group>
<Form.Control
type="text"
placeholder="Name"
name="name"
value={formData.name}
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Control
type="email"
placeholder="Email Address"
name="email"
value={formData.email}
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Control
type="password"
placeholder="<PASSWORD>"
name="password"
value={formData.password}
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Control
type="<PASSWORD>"
placeholder="<PASSWORD>"
name="<PASSWORD>"
value={formData.password2}
onChange={handleChange}
/>
</Form.Group>
{formData.avatarUrl && (
<div className="mb-3">
<img
height="50%"
width="50%"
src={formData.avatarUrl}
className="avatar-lg"
alt="avatar"
/>
</div>
)}
<Button
variant="danger"
onClick={uploadWidget}
sm={3}
className="mb-3"
>
Upload profile picture
</Button>
{loading ? (
<Button
className="btn-block"
variant="primary"
type="button"
disabled
>
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
Loading...
</Button>
) : (
<Button
className="btn-block"
type="submit"
variant="primary"
sm={6}
>
Register
</Button>
)}
<p className="mt-2">
Already have an account? <Link to="/login">Sign In</Link>
</p>
</Form>
</Col>
</Row>
</Container>
</div>
);
};
export default RegisterPage;
<file_sep>export const REGISTER_REQUEST = "USER.REGISTER_REQUEST";
export const REGISTER_SUCCESS = "USER.REGISTER_SUCCESS";
export const REGISTER_FAILURE = "USER.REGISTER_FAILURE";
export const REACTION_REQUEST = "USER.REACTION_REQUEST";
export const REACTION_SUCCESS = "USER.REACTION_SUCCESS";
export const REACTION_FAILURE = "USER.REACTION_FAILURE";
<file_sep>import React, { useEffect } from "react";
import { Col, Container, Row } from "react-bootstrap";
import LoginForm from "../components/LoginForm";
import PublicNavBar from "../components/PublicNavBar";
import { useSelector } from "react-redux";
import { useHistory, Link, Redirect } from "react-router-dom";
import FaceIcon from "@material-ui/icons/Face";
const LoginPage = () => {
const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
//const history = useHistory();
if (!isAuthenticated) {
return (
<div>
<PublicNavBar />
<Container className="mt-5">
<Row className="justify-content-md-center">
<div className="text-center mb-3">
<h1 className="text-danger"> Welcome back</h1>
<span>
Sign in now to post blogs and catch up on Tweets from the people
you follow
</span>{" "}
<FaceIcon />
</div>
<Col xs={6}>
<LoginForm />
</Col>
</Row>
<span>
Don't have an account? <Link to="/register">Sign Up</Link>
</span>
</Container>
</div>
);
} else {
return <Redirect to="/" />;
}
};
export default LoginPage;
<file_sep>import React from "react";
//import { Card } from "react-bootstrap";
import Moment from "react-moment";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
import Grid from "@material-ui/core/Grid";
import Avatar from "@material-ui/core/Avatar";
import Typography from "@material-ui/core/Typography";
import { red } from "@material-ui/core/colors";
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: 345,
},
media: {
height: 0,
paddingTop: "56.25%", // 16:9
},
avatar: {
backgroundColor: red[500],
},
}));
const BlogCard = ({ blog, handleClickBlogCard }) => {
const classes = useStyles();
return (
<Grid style={{ cursor: "pointer" }} item xl={12}>
<Card
className={classes.root}
style={{ width: "25rem", height: "25em" }}
onClick={() => handleClickBlogCard(blog._id)}
>
<CardHeader
avatar={
<Avatar
aria-label="avatar"
className={classes.avatar}
src={blog.author.avatarUrl}
></Avatar>
}
title={blog.author.name}
/>
<CardMedia
className={classes.media}
image={
blog.images.length && blog.images !== null
? blog.images[0]
: "https://lh3.googleusercontent.com/proxy/tNq8UKiT4t5sO3XJPkuQHHtFnXphftuxNuacQmK7scoWKa4WmzZnYQMSMHrEBsEPGF3kipKQNK9TM1SCcuqODvEacHdV_F7ne5VPFF7gIbtY6nSWoQ"
}
title={blog.title}
height="100%"
/>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">
{blog.content.length <= 100
? blog.content
: blog.content.slice(0, 100) + "..."}
<br /> {<Moment fromNow>{blog.createdAt}</Moment>}
</Typography>
</CardContent>
</Card>
</Grid>
);
};
export default BlogCard;
<file_sep>import * as types from "../constants/blog.constants";
import api from "../../apiService";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const getBlogs = (pageNum, limit, field_name) => async (dispatch) => {
dispatch({ type: types.GET_BLOGS_REQUEST });
try {
let query = "";
if (field_name) {
query = `&title[$regex]=${field_name}&title[$options]=i`;
}
const url = `/blogs?page=${pageNum}&limit=${limit}${query}&sortBy[createdAt]=1`;
const res = await api.get(url);
console.log(" success", res.data.success);
if (res.data.success === true) {
console.log("data", res.data.data.totalPages);
dispatch({ type: types.GET_BLOGS_SUCCESS, payload: res.data.data });
}
} catch (error) {
dispatch({ type: types.GET_BLOGS_FAILURE, payload: error });
}
};
const getSingleBlog = (id) => async (dispatch) => {
dispatch({ type: types.GET_SINGLE_BLOGS_REQUEST });
try {
const res = await api.get(`/blogs/${id}`);
console.log("single data", res);
dispatch({ type: types.GET_SINGLE_BLOGS_SUCCESS, payload: res.data.data });
} catch (error) {
dispatch({ type: types.GET_SINGLE_BLOGS_FAILURE, payload: error });
}
};
const createReview = (blogId, review) => async (dispatch) => {
dispatch({ type: types.CREATE_REVIEW_REQUEST });
console.log("blog id");
try {
const res = await api.post(`/reviews/blogs/${blogId}`, {
content: review,
});
console.log("create blog", res.data.data);
dispatch({ type: types.CREATE_REVIEW_SUCCESS, payload: res.data.data });
} catch (error) {
dispatch({ type: types.CREATE_REVIEW_FAILURE, payload: error });
}
};
const createBlog = (newBlog) => async (dispatch) => {
dispatch({ type: types.CREATE_BLOG_REQUEST, payload: null });
try {
const res = await api.post("/blogs", newBlog);
dispatch({
type: types.CREATE_BLOG_SUCCESS,
payload: res.data.data,
});
toast.configure();
await toast.success("🦄 Woohoo, New Blog Has Been Created!", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
//go back to home temorarily
window.location.replace("http://localhost:3000/");
} catch (error) {
dispatch({ type: types.CREATE_BLOG_FAILURE, payload: error });
}
};
const sendReact = (targetType, targetId, emoji) => async (dispatch) => {
dispatch({ type: types.REACTION_REQUEST });
try {
const response = await api.post(`/reactions`, {
targetType,
targetId,
emoji,
});
if (targetType === "Blog") {
if (response.data.success === true) {
dispatch({ type: types.REACTION_SUCCESS, payload: response.data.data });
}
}
if (targetType === "Review") {
console.log("reviewingg reaction");
dispatch({
type: types.REVIEW_REACTION_SUCCESS,
payload: { reactions: response.data.data, reviewId: targetId },
});
}
} catch (error) {
dispatch({ type: types.REACTION_FAILURE, payload: error.message });
}
};
const updateBlog = (blogId, newBlog) => async (dispatch) => {
dispatch({ type: types.UPDATE_BLOG_REQUEST, payload: null });
try {
const res = await api.put(`/blogs/${blogId}`, newBlog);
console.log("new blog", newBlog);
dispatch({
type: types.UPDATE_BLOG_SUCCESS,
payload: res.data.data,
});
toast.configure();
await toast.success("🦄 Woohoo, Your Blog Has Been Updated!", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
window.location.replace("http://localhost:3000/");
} catch (error) {
dispatch({ type: types.UPDATE_BLOG_FAILURE, payload: error });
}
};
const deleteBlog = (blogId) => async (dispatch) => {
dispatch({ type: types.DELETE_BLOG_REQUEST });
try {
console.log("blogid", blogId);
const res = await api.delete(`/blogs/${blogId}`);
console.log("delete", res);
dispatch({
type: types.DELETE_BLOG_SUCCESS,
});
} catch (error) {
dispatch({ type: types.DELETE_BLOG_FAILURE });
}
};
const blogActions = {
getBlogs,
getSingleBlog,
createReview,
createBlog,
sendReact,
updateBlog,
deleteBlog,
};
export default blogActions;
<file_sep>import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import { Switch, Route } from "react-router-dom";
import HomePage from "./containers/HomePage";
import LoginPage from "./containers/LoginPage";
import RegisterPage from "./containers/RegisterPage";
import ProfilePage from "./containers/Admin/AdminSideBar/ProfilePage"
import BlogTablePage from "./containers/Admin/AdminSideBar/BlogTablePage"
import BlogDetailPage from "./containers/BlogDetailPage";
import AddBlog from "./containers/AddBlog";
import { BrowserRouter as Router } from "react-router-dom";
import PublicNavBar from "./components/PublicNavBar";
import { Row, Col } from "react-bootstrap";
import FriendsPage from "./containers/Admin/AdminSideBar/FriendsPage";
import MessengerPage from "./containers/Admin/AdminSideBar/MessengerPage";
function App() {
return (
<div className="App">
<Router>
{/* <Row>
<Col xs={12} className="">
<PublicNavBar />
</Col>
</Row> */}
<Switch>
<Route path="/admin/profile" component={ProfilePage} />
<Route path="/admin/blog" component={BlogTablePage} />
<Route path="/admin/friend" component={FriendsPage}/>
<Route path ="/admin/messenger" component={MessengerPage}/>
<Route exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route exact path="/blogs/:action/:blogId" component={AddBlog} />
<Route path="/blogs/add" component={AddBlog} />
<Route exact path="/blogs/:blogId" component={BlogDetailPage} />
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>import * as types from "../constants/users.constants";
// <<<<<<< katybranch
// // https://fontawesome.com/icons/photo-video?style=solid --find initial image file or upload photo button icon here
// // <i class="fas fa-photo-video"></i> --same icon image html from here
// const initialState = {
// avatarUrl: "",
// name: null,
// email: null,
// registered: false,
// =======
const initialState = {
user: {},
registered: false,
loading: false,
};
const userInfo = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case types.REGISTER_SUCCESS:
return {
...state,
name: payload.name,
email: payload.email,
registered: true,
};
case types.REGISTER_REQUEST:
return { ...state, loading: true };
case types.REGISTER_SUCCESS:
return {
...state,
loading: false,
user: payload.data,
registered: true,
};
default:
return state;
}
};
export default userInfo;
<file_sep>import React, { useEffect, useState } from "react";
import IconButton from "@material-ui/core/IconButton";
import ThumbUpIcon from "@material-ui/icons/ThumbUp";
import FavoriteIcon from "@material-ui/icons/Favorite";
import EmojiEmotionsIcon from "@material-ui/icons/EmojiEmotions";
import MoodBadIcon from "@material-ui/icons/MoodBad";
import SvgIcon from "@material-ui/core/SvgIcon";
import api from "../apiService";
import { useDispatch } from "react-redux";
import blogActions from "../redux/actions/blog.actions";
function ReviewReactions({ targetType, id, reactions }) {
const dispatch = useDispatch();
const updateNumReact = (emoji) => {
console.log("update react ne", { targetType, id, emoji });
dispatch(blogActions.sendReact(targetType, id, emoji));
};
return (
<div>
<IconButton
label="like"
onClick={() => {
updateNumReact("like");
}}
>
<ThumbUpIcon color="primary" />
</IconButton>
{reactions?.like}
<IconButton
label="love"
onClick={() => {
updateNumReact("love");
}}
>
<FavoriteIcon color="secondary" />
</IconButton>{" "}
{reactions?.love}
<IconButton
label="laugh"
onClick={() => {
updateNumReact("laugh");
}}
>
<EmojiEmotionsIcon
style={{ color: "#ffea00", backgroundColor: "black" }}
/>
</IconButton>{" "}
{reactions?.laugh}
<IconButton
label="sad"
onClick={() => {
updateNumReact("sad");
}}
>
<MoodBadIcon style={{ color: "#8561c5" }} />
</IconButton>{" "}
{reactions?.sad}
<IconButton
label="angry"
onClick={() => {
updateNumReact("angry");
}}
>
<SvgIcon style={{ color: "#e91e63" }}>
<path
fill="currentColor"
d="M22 14H21C21 10.13 17.87 7 14 7H13V5.73C13.6 5.39 14 4.74 14 4C14 2.9 13.11 2 12 2S10 2.9 10 4C10 4.74 10.4 5.39 11 5.73V7H10C6.13 7 3 10.13 3 14H2C1.45 14 1 14.45 1 15V18C1 18.55 1.45 19 2 19H3V20C3 21.11 3.9 22 5 22H19C20.11 22 21 21.11 21 20V19H22C22.55 19 23 18.55 23 18V15C23 14.45 22.55 14 22 14M7.5 18C6.12 18 5 16.88 5 15.5C5 14.68 5.4 13.96 6 13.5L9.83 16.38C9.5 17.32 8.57 18 7.5 18M16.5 18C15.43 18 14.5 17.32 14.17 16.38L18 13.5C18.6 13.96 19 14.68 19 15.5C19 16.88 17.88 18 16.5 18Z"
/>
</SvgIcon>{" "}
</IconButton>{" "}
{reactions?.angry}
</div>
);
}
export default ReviewReactions;
<file_sep>import * as types from "../constants/auth.constants";
const initialState = {
user: {},
loading: false,
isAuthenticated: !!localStorage.getItem("token"),
error: null,
};
const authReducer = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case types.REGISTER_REQUEST:
//login
case types.LOGIN_REQUEST:
case types.GET_CURRENT_USER_REQUEST:
return { ...state, loading: true };
case types.LOGIN_SUCCESS:
return { ...state, isAuthenticated: true, loading: false };
case types.REGISTER_SUCCESS:
return {
...state,
loading: false,
};
case types.GET_CURRENT_USER_SUCCESS:
return {
...state,
user: payload,
loading: false,
isAuthenticated: true,
};
case types.GET_CURRENT_USER_FAILURE:
return {
...state,
loading: false,
isAuthenticated: false,
};
case types.REGISTER_FAILURE:
case types.LOGIN_FAILURE:
return { ...state, error: payload, loading: false };
//get current user
case types.GET_USER_REQUEST:
return { ...state, loading: true };
case types.GET_USER_SUCCESS:
return { ...state, isAuthenticated: true, loading: false, user: payload };
case types.GET_USER_FAILURE:
return { ...state, loading: false };
//update profile
case types.UPDATE_PROFILE_REQUEST:
return { ...state, loading: true };
case types.UPDATE_PROFILE_SUCCESS:
return { ...state, user: { ...state.user, payload }, loading: false };
case types.UPDATE_PROFILE_FAILURE:
return { ...state, loading: false };
case types.GET_USER_REQUEST:
return { ...state, loading: true };
case types.GET_USER_SUCCESS:
return { ...state, isAuthenticated: true, loading: false, user: payload };
case types.GET_USER_FAILURE:
return { ...state, loading: false };
//logout
case types.LOGOUT:
return {
...state,
isAuthenticated: false,
user: null,
loading: false,
};
default:
return state;
}
};
export default authReducer;
<file_sep>import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import authActions from "../redux/actions/auth.actions";
const LoginForm = () => {
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
//const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
return (
<div>
<Form
onSubmit={(e) => {
e.preventDefault();
dispatch(authActions.login(email, password));
}}
>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="<PASSWORD>"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
</Form.Group>
<Button
className="mt-4"
style={{ width: "100%" }}
variant="primary"
type="submit"
>
Login
</Button>
</Form>
</div>
);
};
export default LoginForm;
<file_sep>import * as types from "../constants/users.constants";
import api from "../../apiService";
const userActions = {};
const register = (avatarUrl, name, email, password) => async(dispatch) => {
dispatch({type: types.REGISTER_REQUEST})
try {
console.log("register is working")
const response = await api.post("/users", {
avatarUrl,
name,
email,
password
})
console.log(response)
if(response.success === true) {
dispatch({type: types.REGISTER_SUCCESS, payload: response.data})
console.log(response.data);
console.log(response.success)
}
export default userActions;
| ba63dab1f9367ef0077ffe59d31ca4ebc14b97bb | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | katytran/SocialAPP | 6b5fbf164848b3b85e720c2ad2913a487233de42 | cb39a7427569f056764ccea250c76b9ec20944a5 |
refs/heads/master | <file_sep>import java.util.Deque;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.util.concurrent.*;
import java.io.*;
import java.lang.Math.*;
import java.util.Map;
import java.util.Stack;
import java.util.AbstractMap.*;
import java.io.PrintWriter;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import java.util.Arrays;
/*************************************************************************
* A class representing a rhomb in a patch.
* The SimpleRhombs may shift about relative to one another.
*************************************************************************/
public class SimpleRhomb implements Rhomb, Serializable {
/** For serialization. */
public static final long serialVersionUID = 5607L;
/**
* For plotting in the plane.
* A reference point indicating the position of the corner of the rhomb
* with even angles that has two outward-pointing arrows.
*/
public Point p;
/** A vector indicating the first outward-pointing edge from {@link #p}. */
public final Point v1;
/** A vector indicating the second outward-pointing edge from {@link #p}. */
public final Point v2;
/** The congruence class of rhomb. */
public final int type;
/** Orientation. */
public final int angle;
/** The four vertices, represented as integer vectors of length {@link Point#N()}-1. */
private Point[] vertices = new Point[4];
/** The scale for drawing. */
private double scale = RhombDisplay.SCALE;
/**
* The rhombs that share edges in common with this one. This is at most
* four rhombs. If some edges are on the boundary, we indicate that by
* putting nulls there.
* The rhombs that share a v1-edge are listed at positions 0 and 3, the rhombs
* that share a v2-edge are at 1 and 2. The ones that share an edge of one
* and lie at the bases of the edges of the other type are listed at 0 and 1.
*/
public final SimpleRhomb[] adjacent = new SimpleRhomb[4];
/** A polygon for drawing. */
private transient SimplePolygon2D rhomb;
/** Method for saving. */
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(p);
stream.writeObject(vertices);
}
/** Method for restoring a saved Join. */
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
p = (Point) stream.readObject();
vertices = (Point[]) stream.readObject();
rhomb = null;
setRhomb();
}
/** Method for restoring a saved SimpleRhomb. Empty. */
private void readObjectNoData() throws ObjectStreamException {
}
/**
* Public constructor.
* @param p A reference point indicating the corner of the rhomb with even angle and two outward-pointing arrows.
* @param v1 A vector representation of the first outward-pointing edge from p.
* @param v2 A vector representation of the second outward-pointing edge from p.
* @param type A number indicating the congruence class of the rhomb.
* @param angle An integer multiple of pi/{@link Point#N()} representing the
* angle the rhomb makes with the positive x-axis.
*/
public SimpleRhomb(Point p, Point v1, Point v2, int type, int angle) {
this.p = p;
this.v1 = v1;
this.v2 = v2;
this.type = type;
this.angle = angle;
vertices[0] = p;
vertices[1] = p.plus(v2);
vertices[2] = vertices[1].plus(v1);
vertices[3] = p.plus(v1);
// now make the rhomb
setRhomb();
}
/**
* Public static factory method.
* @param p A reference point indicating the corner of the rhomb with even angle and two outward-pointing arrows.
* @param v1 A vector representation of the first outward-pointing edge from p.
* @param v2 A vector representation of the second outward-pointing edge from p.
* @param type A number indicating the congruence class of the rhomb.
* @param angle An integer multiple of pi/{@link Point#N()} representing the
* angle the rhomb makes with the positive x-axis.
*/
public static SimpleRhomb createSimpleRhomb(Point p, Point v1, Point v2, int type, int angle) {
return new SimpleRhomb(p,v1,v2,type,angle);
}
/**
* This already is a SimpleRhomb, so return this.
*/
public SimpleRhomb createSimpleRhomb() {
return this;
}
/**
* Two SimpleRhombs are equal if they have the same type, the same angle, and the same corner.
*/
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
SimpleRhomb t = (SimpleRhomb) obj;
return ((this.p.equals(t.p))&&(this.type==t.type)&&(this.angle==t.angle));
}
/**
* Use the corner, the type, and the angle.
*/
public int hashCode() {
return p.hashCode() + 19*type + 361*angle;
}
/**
* Getter method.
* @return The type.
*/
public int getType() {
return type;
}
/**
* Getter method.
* @return The point.
*/
public Point getPoint(){
return p;
}
/**
* Getter method.
* @return The vertices.
*/
public Point[] getVert(){
return vertices;
}
/**
* Rotate a SimpleRhomb by the given angle
* @param rotationAngle
* @return rotated SimpleRhomb
*/
public SimpleRhomb rotate(int rotationAngle) {
Point newV1 = v1.rotate(rotationAngle);
Point newV2 = v2.rotate(rotationAngle);
Point newP = p.rotate(rotationAngle);
int newAngle = (angle + rotationAngle)%(2*Point.N());
return new SimpleRhomb(newP, newV1, newV2, type, newAngle);
}
/**
* Replace the given SimpleRhomb with null in the adjacent list for this.
* Do this when a rhomb is collapsed.
* @param neighbour The adjacent rhomb that is being removed. If it's null,
* there will be trouble.
*/
private void dropNeighbour(SimpleRhomb neighbour) {
for (int i = 0; i < 3; i++) {
if (neighbour.equals(adjacent[i])) {
adjacent[i] = null;
break;
}
}
}
/**
* Determine if this SimpleRhomb is on the edge of a pseudoline arrangement.
* @return true if, for each of the two Yarns, this is either the first or last SimpleRhomb.
*/
public boolean onEdge() {
return true;
}
/**
* Remove this SimpleRhomb. This method should only be used if this is on an edge.
*/
public void collapse() {
for (int i = 0; i < 3; i++) if (adjacent[i]!=null) adjacent[i].dropNeighbour(this);
}
/**
* Shift the point by a given vector. This means that, when we draw the rhomb
* represented by this SimpleRhomb, it will be shifted.
* @param vector The vector by which we shift point.
*/
public void shift(Point vector) {
p = p.plus(vector);
for (int i = 0; i < 4; i++) vertices[i] = vertices[i].plus(vector);
setRhomb();
}
/**
* Flip the positions of the given three rhombs.
* We assume, but do not check, that they form a hex.
* This method is called in {@link SimpleHex#flip}. The rhombs aren't shifted here; we shift
* them in that method instead.
* @param triple The three rhombs that we flip.
* @param directions For each rhomb in triple, do we shift it by the positive or the negative
* of the direction vector common to the two other rhombs?
* @return A list of {@link SimpleHex}es created or destroyed by this flip.
*/
public static List<Hex> flip(SimpleRhomb[] triple,boolean[] directions) {
List<Hex> output = new LinkedList<>();
// stores indices in the adjacent lists of the elements of triple.
// the number at [i][j] is the index in the adjacent list of triple[i]
// of triple[i+1+j (mod 3)].
int[][] r = new int[3][2];
// iterate over adjacent indices
for (int i = 0; i < 4; i++) {
// iterate over rhombs in the triple
for (int j = 0; j < 3; j++) {
if (triple[(j+1)%3].equals(triple[j].adjacent[i])) r[j][0] = i;
else if (triple[(j+2)%3].equals(triple[j].adjacent[i])) r[j][1] = i;
}
}
// we've made note of the outside rhombs. Now make switches.
// iterate over pairs of rhombs (there are three, each with
// indices of the form (i,i+1)).
for (int i = 0; i < 3; i++) {
// record the SimpleHexes that will be destroyed.
if (triple[i].adjacent[3-r[i][0]]!=null&&triple[i].adjacent[3-r[i][0]].shareEdge(triple[i].adjacent[3-r[i][1]])) {
output.add(new SimpleHex(triple[i],triple[i].adjacent[3-r[i][0]],triple[i].adjacent[3-r[i][1]]));
}
}
for (int i = 0; i < 3; i++) {
if (triple[i].adjacent[3-r[i][0]]!=null) triple[i].adjacent[3-r[i][0]].swapAdjacent(triple[i],triple[(i+1)%3]);
if (triple[(i+1)%3].adjacent[3-r[(i+1)%3][1]]!=null) triple[(i+1)%3].adjacent[3-r[(i+1)%3][1]].swapAdjacent(triple[(i+1)%3],triple[i]);
triple[i].adjacent[r[i][0]] = triple[(i+1)%3].adjacent[3-r[(i+1)%3][1]];
triple[(i+1)%3].adjacent[r[(i+1)%3][1]] = triple[i].adjacent[3-r[i][0]];
triple[i].adjacent[3-r[i][0]] = triple[(i+1)%3];
triple[(i+1)%3].adjacent[3-r[(i+1)%3][1]] = triple[i];
// shift the rhomb
triple[i].shift((directions[i]) ? triple[(i+1)%3].commonEdge(triple[(i+2)%3]) : Point.ZERO().minus(triple[(i+1)%3].commonEdge(triple[(i+2)%3])));
}
for (int i = 0; i < 3; i++) {
// record the SimpleHexes that will be created.
if (triple[i].adjacent[r[i][0]]!=null&&triple[i].adjacent[r[i][0]].shareEdge(triple[i].adjacent[r[i][1]])) {
output.add(new SimpleHex(triple[i],triple[i].adjacent[r[i][0]],triple[i].adjacent[r[i][1]]));
}
}
return output;
}
/**
* Reset the rhomb whenever it changes.
* The rhomb is determined entirely by other internal variables; this method resets
* the rhomb if those variables have changed.
*/
private void setRhomb() {
rhomb = new SimplePolygon2D(new Point2D[] {vertices[0].getPoint2D().scale(scale),vertices[1].getPoint2D().scale(scale),vertices[2].getPoint2D().scale(scale),vertices[3].getPoint2D().scale(scale)});
}
/**
* Reset the scale for drawing the Rhomb.
* @param s The new scale.
*/
public void setScale(double s) {
scale = s;
setRhomb();
}
/**
* Get the scale for drawing the Rhomb.
* @return The scale for drawing the Rhomb.
*/
public double getScale() {
return scale;
}
/**
* Find the edge direction vector that this and another rhomb have in common.
* @param other The other rhomb.
* @return The edge direction vector that this has in common with other.
* Return null if there is no common vector.
*/
public Point commonEdge(SimpleRhomb other) {
if (other==null) return null;
if (this.v1.equals(other.v1)||this.v1.equals(other.v2)) return v1;
else if (this.v2.equals(other.v1)||this.v2.equals(other.v2)) return v2;
else return null;
}
/**
* Determine if this shares an edge with another SimpleRhomb.
* @param other The other rhomb.
* @return true if this and other share an edge.
*/
public boolean shareEdge(SimpleRhomb other) {
if (other==null) return false;
boolean oneInCommon = false;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (this.vertices[i].equals(other.vertices[j])) {
if (oneInCommon) return true;
else oneInCommon = true;
break;
}
}
}
return false;
}
/**
* Getter method.
* @return A polygon object containing the 2d rhomb that this SimpleRhomb represents. (2 coordinates.)
*/
public SimplePolygon2D getRhomb() {
return rhomb;
}
/**
* Getter method.
* @return The angle that the base of this rhomb makes with the positive x-axis.
*/
public int getAngle() {
return angle;
}
/**
* Add another SimpleRhomb to the adjacency list.
* @param other The rhomb we add.
* @param a The angle that other makes with the positive x-axis.
* @param first Tells us if other is listed before this in a Yarn.
*/
public void addAdjacent(SimpleRhomb other, int a, boolean first) {
if ((a%(2*Point.N()))==angle) {
if (first) adjacent[0] = other;
else adjacent[3] = other;
} else {
if (first) adjacent[1] = other;
else adjacent[2] = other;
}
}
/**
* Replace a SimpleRhomb in the adjacency list with another one.
* @param out The rhomb we remove from the list.
* @param in The rhomb with which we replace it.
*/
private void swapAdjacent(SimpleRhomb out, SimpleRhomb in) {
for (int i = 0; i < 4; i++) {
if (out.equals(adjacent[i])) {
adjacent[i] = in;
break;
}
}
}
/**
* Method for debugging.
* Determine if this is doubly-adjacent to any other rhomb (it shouldn't be).
* @return true if this has another rhomb more than once in its adjacency list.
*/
private boolean duplicateAdjacent() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i==j) continue;
if (adjacent[i]!=null&&adjacent[i].equals(adjacent[j])) return true;
}
}
return false;
}
/**
* String representation for Postscript.
* @return A String giving instructions for how to draw this in Postscript.
*/
public String postscriptString() {
return "gsave " + p.postscriptString() + Point.order() + "orth translate " + (angle*(180.0/Point.N())) + " rotate t" + type + " grestore";
}
/**
* String representation for gap.
* @return A String containing various internal variables, formatted for use in gap.
*/
public String gapString() {
return " MkSubtile" + Point.N() + "( t, T, " + p + ", " + type + ", " + angle + " )";
}
/**
* String representation of this.
* @return A String representing this.
*/
public String toString() {
return "SimpleRhomb point : " + p + ". angle : " + angle + ". type: " + type + ".";
}
/**
* String representation of this, including all the rhombs to which it's adjacent.
* @return A String representing this and all its adjacent rhombs.
*/
public String adjacencyString() {
return this + "\nadjacent to : \n " + adjacent[0] + "\n " + adjacent[1] + "\n " + adjacent[2] + "\n " + adjacent[3];
}
/**
*
*/
public SimpleRhomb transform(int rot, Point move){
SimpleRhomb r = rotate(rot).translate(move);
return r;
}
/**
* Shift the point by a given vector. This means that, when we draw the rhomb
* represented by this SimpleRhomb, it will be shifted.
* @param move The vector by which we shift point.
*/
public SimpleRhomb translate(Point move) {
Point newP = p.plus(move);
SimpleRhomb r = createSimpleRhomb(newP, v1, v2, type, angle);
return r;
}
/**
* Return a List of {@link Point}s representing the inflation of this rhomb
* by the given factor, with edges distorted according to the given
* edge sequence.
* @param infl The inflation factor, represented as a matrix.
* @param edge The edge sequence used to distort the edges.
* @return infl * this, with its edges distorted according to the
* rule specified by edge.
*/
public List<Point> supertile(Point[] infl, int[] edge) {
int even = Point.N()+1-2*type;
List<Point> output = new ArrayList<>();
Point current = vertices[0].multiply(infl);
for (int i = 0; i < edge.length; i++) {
output.add(current);
current = current.plus(Point.createPoint(this.angle+edge[i]));
}
for (int i = 0; i < edge.length; i++) {
output.add(current);
current = current.plus(Point.createPoint(this.angle-even+edge[i]));
}
for (int i = 0; i < edge.length; i++) {
output.add(current);
current = current.plus(Point.createPoint(this.angle+Point.N()+edge[edge.length-i-1]));
}
for (int i = 0; i < edge.length; i++) {
output.add(current);
current = current.plus(Point.createPoint(this.angle-even+Point.N()+edge[edge.length-i-1]));
}
return output;
}
/**
* Return a SimlePolygon2D representing the inflation of this rhomb
* by the given factor, with edges distorted according to the given
* edge sequence.
* @param infl The inflation factor, represented as a matrix.
* @param edge The edge sequence used to distort the edges.
* @return infl * this, with its edges distorted according to the
* rule specified by edge.
*/
public SimplePolygon2D outline(Point[] infl, int[] edge) {
List<Point2D> output = new ArrayList<>();
for (Point p : supertile(infl,edge)) output.add(p.getPoint2D().scale(scale));
return new SimplePolygon2D(output);
}
} // end of class SimpleRhomb
<file_sep>Substitution Editor: A program for creating and editing rhombic substitution tilings
Compiling and running
Linux: compile: javac -cp '.:./javaGeom-0.11.2.jar' *.java
run: java -cp '.:./javaGeom-0.11.2.jar' Launcher
javadoc: javadoc -d javadoc/ *.java
Windows: compile: I don't know
run: I don't know
javadoc: I don't know
Mac: compile: javac -cp '.:./javaGeom-0.11.2.jar' *.java
run: java -cp '.:./javaGeom-0.11.2.jar' Launcher
javadoc: javadoc -d javadoc/ *.java
<file_sep>import java.io.*;
/**
* Constants that {@link WorkUnit}s can return.
* Created by <a href="http://www.people.fas.harvard.edu/~ekwan/"><NAME></a>.
*/
public interface Result extends Serializable
{
public static final Result JOB_FAILED = new Result() {
public String toString() { return "job failed"; } };
public static final Result JOB_INTERRUPTED = new Result() {
public String toString() { return "job was interrupted"; } };
public static final Result JOB_UNAVAILABLE = new Result() {
public String toString() { return "job result not available"; } };
public static final Result JOB_COMPLETE = new Result() {
public String toString() { return "job complete"; } };
public String toString();
}
<file_sep>//package Project;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.io.*;
import java.lang.Math.*;
import java.util.Map;
import java.util.Stack;
import java.util.AbstractMap.*;
import java.io.PrintWriter;
import math.geom2d.Point2D;
/*************************************************************************
* Represents a point in the module generated by the nth roots of unity
* in the complex plane.
* Each Point can be expressed as an integer combination of the vectors
* (cos (k pi/n), sin(k pi/n)). The main field is an int array, the kth
* entry of which is the coefficient of (cos (k pi/n), sin(k pi/n)).
*
*************************************************************************/
public class Point implements Serializable {
/** For serialization. */
public static final long serialVersionUID = 5511L;
/** All angles are integer multiples of 180/N. */
private static int N;
/** An array of coefficients. */
private final int[] point;
/** An array of all points that are a distance of 1 from the origin. */
private static Point[] STAR;
/** cos(i pi/N) */
private static double[] COS;
/** sin(i pi/N) */
private static double[] SIN;
/** The zero vector. */
private static Point Z;
/** A String representing the order of symmetry. */
private static String ORDER;
static { // initialize N
setN(7);
}
/**
* Set the order of symmetry.
* @param n The new order of symmetry.
*/
public static void setN(int n) {
if (n<5) throw new IllegalArgumentException("Trying to set N = " + n + ", which is too low (n >= 5 is required).");
N = n;
Point[] preStar = new Point[2*N];
for (int i = 0; i < N-1; i++) {
int[] plus = new int[N-1];
int[] minus = new int[N-1];
for (int j = 0; j < N-1; j++) {
plus[j] = (j==i) ? 1 : 0;
minus[j] = (j==i) ? -1 : 0;
}
preStar[i] = new Point(plus);
preStar[N+i] = new Point(minus);
}
int[] plus = new int[N-1];
int[] minus = new int[N-1];
for (int j = 0; j < N-1; j++) {
minus[j] = (j%2==1) ? -1 : 1;
plus[j] = (j%2==1) ? 1 : -1;
}
preStar[N-1] = new Point(plus);
preStar[2*N-1] = new Point(minus);
STAR = preStar;
double[] preCos = new double[N-1];
double[] preSin = new double[N-1];
for (int i = 0; i < N-1; i++) {
preCos[i] = Math.cos(i*Math.PI/((double)N));
preSin[i] = Math.sin(i*Math.PI/((double)N));
}
COS = preCos;
SIN = preSin;
Z = new Point(new int[N-1]);
// change the prefix string for postscript output
switch (N) {
case 5: ORDER = "pent";
break;
case 7: ORDER = "hept";
break;
case 9: ORDER = "nine";
break;
case 11: ORDER = "elf";
break;
default: ORDER = "unknown";
break;
}
// Change the colour palette
ColourPalette.setN(N);
} // end of static initialization
/**
* Get the order of symmetry.
* @return N.
*/
public static int N() {
return N;
}
/**
* Get the zero vector.
* @return A point representing the origin.
*/
public static Point ZERO() {
return Z;
}
/**
* Private constructor.
* @param p The coefficients of the Point we create.
*/
private Point(int[] p) {
if (p.length!=N-1) throw new IllegalArgumentException("Trying to create a Point with " + (N-1) + " entries, but only giving " + p.length + " entries as input.");
this.point = p;
}
/**
* Public static factory method.
* Returns the element of the unit circle that makes an angle of
* i pi/N with the positive x-axis.
* @param i The angle between the Point returned and the positive x-axis.
* @return The point on the unit circle that makes an angle of i with the positive x-axis.
*/
public static Point createPoint(int i) {
i = i%(2*N);
if (i < 0) i = i + 2*N;
return STAR[i];
}
/**
* Output a String consisting of the coefficients of the Point in a
* comma-separated list, enclosed in square brackets.
* @return The coefficients of the Point in a comma-separated list enclosed in square brackets.
*/
public String toString() {
String output = "[ ";
for (int i = 0; i < (N-2); i++) output += point[i] + ", ";
return output + point[N-2] + " ]";
} // end of toString
/**
* Output a String consisting of the coefficients of the Point in a
* space-separated list.
* @return The coefficients of the Point in a space-separated list.
*/
public String postscriptString() {
String output = "";
for (int i = 0; i < (N-1); i++) output += point[i] + " ";
return output;
} // end of postscriptString
/**
* Output a String describing the order of symmetry.
* @return "pent" if N == 5, "hept" if N == 11, etc.
*/
public static String order() {
return ORDER;
} // end of order
/**
* Output a String consisting of the coefficients of the Point in a
* comma-separated list with no brackets.
* @return The coefficients of the Point in a comma-separated list.
*/
public String matrixString() {
String output = "";
for (int i = 0; i < (N-2); i++) output += point[i] + ", ";
return output + point[N-2] + "";
} // end of matrixString
/**
* Output 2d Cartesian coordinates.
* @return An array of two doubles representing x- and y-coordinates of this point.
*/
public double[] project() {
double[] output = new double[2];
for (int i = 0; i < N-1; i++) {
output[0] += COS[i]*point[i];
output[1] += SIN[i]*point[i];
}
return output;
} // end of project
/**
* Output this Point as a Point2D.
* @return A Point2D representation of this point.
*/
public Point2D getPoint2D() {
double x = 0.0;
double y = 0.0;
for (int i = 0; i < N-1; i++) {
x += COS[i]*point[i];
y += SIN[i]*point[i];
}
return new Point2D(x,y);
} // end of getPoint2D
/**
* Output a gap-readable String representing an inflation matrix.
* This square matrix has N-1 rows, each enclosed in square brackets,
* with comma-separated entries.
* @param angles A list of angles, given as integer multiples of pi/N.
* The sum of the points on the unit circle corresponding to these angles
* is the inflation factor of the matrix.
* @return The matrix representation of multiplication by the inflation
* factor, expressed in terms of the N-1 vectors (cos(k pi/n), sin(k pi/n)).
*/
public static String gapString(int[] angles) {
boolean first = true;
String output = "[ ";
for (int i = 0; i < (N-1); i++) {
Point p = Z;
for (int j : angles) {
int index = (i+j)%(2*N);
p = p.plus(STAR[(index>=0) ? index : index + 2*N]);
}
if (!first) {
output += ", ";
} else {
first = false;
}
output += p;
}
return output + " ]";
} // end of gapString
/**
* Same as {@link #gapString(int[])}, but with row breaks
* indicated by new lines instead of square brackets.
*/
public static String matrixString(int[] angles) {
String output = "";
for (int i = 0; i < (N-1); i++) {
Point p = Z;
for (int j : angles) {
int index = (i+j)%(2*N);
p = p.plus(STAR[(index>=0) ? index : index + 2*N]);
}
output += p.matrixString() + "\n";
}
return output + "";
} // end of matrixString
/**
* Output a gap-readable String representing a rotation matrix.
* This square matrix has N-1 rows, each enclosed in square brackets,
* with comma-separated entries.
* @return The matrix representation of rotation by pi/n,
* expressed in terms of the N-1 vectors (cos(k pi/n), sin(k pi/n)).
*/
public static String gapString() {
boolean first = true;
String output = "[ ";
for (int i = 1; i < (N); i++) {
if (!first) {
output += ", ";
} else {
first = false;
}
output += STAR[i];
}
return output + " ]";
} // end of gapString
/**
* Two Points are equal if they are of the same length and have the
* same entries in each position.
*/
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
Point l = (Point) obj;
if (l.point.length!=this.point.length) return false;
for (int i = 0; i < N-1; i++) if (this.point[i]!=l.point[i]) return false;
return true;
}
/**
* Currently broken.
*/
public int hashCode() {
return 19;
}
/**
* Add another point to this one and return the result.
* The two original Points remain unchanged.
* @param p The Point we add to this one.
* @return The sum of this an p.
*/
public Point plus(Point p) {
int[] output = new int[N-1];
for (int i = 0; i < output.length; i++) output[i] = this.point[i]+p.point[i];
return new Point(output);
}
/**
* Subtract another point from this one and return the result.
* The two original Points remain unchanged.
* @param p The Point we subtract from this one.
* @return The difference of this an p.
*/
public Point minus(Point p) {
int[] output = new int[N-1];
for (int i = 0; i < output.length; i++) output[i] = this.point[i]-p.point[i];
return new Point(output);
}
/**
* Rotate this Point about the origin by the given angle.
* @param angle The angle of rotation.
* @return The Point that results from the rotation.
*/
public Point rotate(int angle) {
int[] output = new int[N-1];
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output.length; j++) {
output[i] += this.point[j]*STAR[(angle+j)%(2*N)].point[i];
}
}
return new Point(output);
}
/**
* Produce an inflation matrix (i.e., a sequence of {@link #N()}-1 Points)
* corresponding to a given edge sequence.
* @param seq A sequence of angles representing a vector
* reached by taking steps of unit length, starting at the origin.
* This vector should lie on the positive x-axis, and therefore
* represent a length.
* @return A matrix (array of Points), multiplication by which
* corresponds to inflation by the length represented by the given
* sequence.
*/
public static Point[] inflation(int[] seq) {
Point[] output = new Point[N-1];
Point base = Point.Z;
for (int i = 0; i < seq.length; i++) {
base = base.plus(STAR[(seq[i]%(2*N)<0) ? (seq[i]%(2*N))+2*N : (seq[i]%(2*N))]);
}
for (int i = 0; i < N-1; i++) {
output[i] = base.rotate(i);
}
return output;
}
/**
* View the given array of Points as a matrix, and multiply this Point
* by it. Intended for use in computing inflated Points.
* @param mat An Array of Points representing an inflation matrix.
* @return The inflation of this point by the given matrix.
*/
public Point multiply(Point[] mat) {
if (mat.length!=N-1) throw new IllegalArgumentException("Trying to multiply by a matrix of size " + mat.length + " when a matrix of size " + (N-1) + " is required.");
int[] output = new int[N-1];
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output.length; j++) {
output[i] += this.point[j]*mat[j].point[i];
}
}
return new Point(output);
}
/** For testing. */
public static void main(String[] args) {
System.out.println(gapString());
int[] ii = new int[] {0,0,0,1,-1,1,-1,1,-1,2,-2,2,-2,2,-2,3,-3,3,-3,4,-4};
System.out.println("Testing rotation:");
System.out.println(matrixString(ii));
Point test = createPoint(0);
for (int i = 0; i < STAR.length; i++) {
System.out.println(test.rotate(i).matrixString());
}
System.out.println("Testing inflation:");
for (Point p : Point.inflation(new int[] {0,1,-1,2,-2})) {
System.out.println(p.matrixString());
}
System.out.println("Testing multiplication:");
System.out.println(createPoint(3).plus(createPoint(5)).matrixString());
System.out.println(createPoint(3).plus(createPoint(5)).multiply(Point.inflation(new int[] {0,1,-1,2,-2})).matrixString());
}
} // end of class Point
<file_sep>import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.plaf.basic.*;
import java.io.*;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import math.geom2d.AffineTransform2D;
import math.geom2d.Box2D;
import javax.swing.event.*;
/**
* A panel with one copy of each prototile, with an unselectable checkbox
* button underneath. The buttons indicate whether or not the prototiles
* can be tiled with a given edge sequence.
*/
class PrototileChecker extends JPanel {
// dimensions
private static final int XBUFFER = 6;
private static final int YBUFFER = 6;
private final int PANE_HEIGHT;
private static final int COLOR_CHOOSER_WIDTH = 600; // a guess
/**
* The Launcher that contains this.
*/
private Launcher parent;
/**
* the prototiles.
*/
private List<RhombBoundary> RB;
/**
* pictures of the prototiles.
*/
private List<RhombDisplay> RD;
/**
* checkboxes for the prototiles.
*/
private List<JCheckBox> CB = new ArrayList<>();
/**
* utility field for constructing the layout.
*/
private GridBagConstraints c = new GridBagConstraints();
/**
* Determine if all prototiles can be tiled with the given edge sequence.
* @return true If all prototiles can be tiled.
*/
public boolean okay() {
for (JCheckBox cb : CB) if (!cb.isSelected()) return false;
return true;
}
/**
* Constructor.
* @param parent The Launcher that contains this.
*/
public PrototileChecker(Launcher parent) {
this.parent = parent;
this.PANE_HEIGHT = (int)parent.getContentPane().getSize().getHeight()-3*Launcher.BUTTON_HEIGHT;
RD = new ArrayList<RhombDisplay>();
CB = new ArrayList<JCheckBox>();
this.setLayout(new GridBagLayout());
changeN();
}
/**
* Respond to a change in the order of symmetry.
* This means changing the prototiles.
*/
public void changeN() {
for (RhombDisplay rd : RD) this.remove(rd);
for (JCheckBox cb : CB) this.remove(cb);
RB = RhombBoundary.prototileList();
int paneWidth = 2*Launcher.WIDTH/(Point.N()-1);
// change the dimensions of this
this.setSize(new Dimension(Launcher.WIDTH,PANE_HEIGHT+Launcher.BUTTON_HEIGHT));
this.setPreferredSize(new Dimension(Launcher.WIDTH,PANE_HEIGHT+Launcher.BUTTON_HEIGHT));
RD = RhombDisplay.displayList(RB,paneWidth,PANE_HEIGHT);
for (int i = 0; i < RD.size(); i++) {
RhombDisplay rd = RD.get(i);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = (int)rd.getPreferredSize().getHeight()-(int)rd.getMinimumSize().getHeight();
c.weightx = 0.5;
c.gridwidth = 1;
c.gridx = i;
c.gridy = 0;
// add the pictures
rd.setBackground(this.getBackground());
rd.setVisible(true);
this.add(rd,c);
}
CB.clear();
Dimension boxSize = new Dimension(paneWidth,PANE_HEIGHT);
for (int i = 0; i < RD.size(); i++) {
// add the CheckBoxes
JCheckBox b = new JCheckBox("",false);
c.fill = GridBagConstraints.HORIZONTAL;
c.fill = GridBagConstraints.VERTICAL;
c.ipady = Launcher.BUTTON_HEIGHT-(int)b.getMinimumSize().getHeight();
c.weightx = 0.5;
c.gridwidth = 1;
c.gridx = i;
c.gridy = 1;
b.setSelected(false);
b.setEnabled(false);
this.add(b,c);
CB.add(b);
}
}
/**
* Respond to a change in the edge sequence.
* This means changing the checkboxes to reflect whether or not
* the inflated prototiles can be tiled with the given edge
* sequence.
* @param seq The edge sequence.
*/
public void changeEdgeSequence(int[] seq) {
if (seq==null) {
for (int i = 0; i < RB.size(); i++) CB.get(i).setSelected(false);
return;
}
for (int i = 0; i < RB.size(); i++) {
RhombBoundary rb = RhombBoundary.createRhombBoundary(Point.N()-1-2*i,seq);
CB.get(i).setSelected(rb.valid());
}
}
/**
* Override.
*/
public Dimension getPreferredSize() {
return new Dimension(Launcher.WIDTH,4*Launcher.WIDTH/(3*(Point.N()-1)));
}
} // end of class PrototileChecker
/**
* A class for rendering the entries of a list of edge sequences.
*/
class EdgeSequenceRenderer<E> extends JLabel implements ListCellRenderer<E> {
public EdgeSequenceRenderer() {
setOpaque(true);
setHorizontalAlignment(LEFT);
setVerticalAlignment(CENTER);
}
/**
* This method produces a JLabel with text corresponding
* to the selected value.
* @return A JLabel with text corresponding to the selected value.
*/
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int[] selected = (int[])value;
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (selected != null) {
setText(Arrays.toString(selected));
setFont(list.getFont());
} else {
setText("Please select (or create) an edge sequence.");
setFont(list.getFont());
}
return this;
}
} // end of class EdgeSequenceRenderer
/**
* A class for rendering the entries of a list of Integers.
* Renders a String containing the list entry, with appropriate prefix
* suffix, that describes what the entry represents.
*/
class IntegerRenderer<E> extends JLabel implements ListCellRenderer<E> {
/** Prefix and suffix added to the label. */
private final String prefix;
private final String suffix;
public IntegerRenderer(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
setOpaque(true);
setHorizontalAlignment(LEFT);
setVerticalAlignment(CENTER);
}
/**
* This method produces a JLabel with text corresponding
* to the selected value, with a prefix and suffix added.
* @return A JLabel with text corresponding to the selected value,
* containing the String prefix + [Integer] + suffix.
*/
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
Integer selected = (Integer)value;
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (selected != null) {
setText(prefix + selected + suffix);
setFont(list.getFont());
} else {
setText("--");
setFont(list.getFont());
}
return this;
}
} // end of class IntegerRenderer
/**
* A class for editing the entries of a list of edge sequences.
*/
class EdgeSequenceEditor extends JTextField implements ComboBoxEditor {
public EdgeSequenceEditor() {
}
public void setItem(Object anObject) {
if (anObject != null) {
super.setText(Arrays.toString(((int[])anObject)));
} else {
super.setText("Please select (or create) an edge sequence.");
}
}
public Component getEditorComponent() {
return this;
}
public Object getItem() {
return parseString();
}
/** Utility method for recovering the object represented by the String. */
private int[] parseString() {
String[] s = getText().replaceAll("[^,-0123456789]","").split(",");
try {
int[] output = new int[s.length];
for (int i = 0; i < s.length; i++) output[i] = Integer.parseInt(s[i]);
return output;
} catch (NumberFormatException e) {
return null;
}
}
public void selectAll() {
super.selectAll();
}
public void addActionListener(ActionListener l) {
super.addActionListener(l);
}
public void removeActionListener(ActionListener l) {
super.removeActionListener(l);
}
} // end of class EdgeSequenceEditor
/**
* THIS IS THE MAIN CLASS.
* <br>
* <br>
* A window with boxes for selecting the order of symmetry ({@link Point#N()}) and the edge
* sequence. It displays all the prototiles for the given order of symmetry,
* each with a checkbox ticked if there exists a tiling of the prototile
* with the selected edge sequence. If all prototiles can be tiled, then
* a start button at the bottom is activated, and the user can press it to
* open a {@link SubstitutionEditor}.
*/
public class Launcher extends JFrame {
/** options for the JComboBoxes. */
private static final Integer[] SYMMETRIES = new Integer[] {5,7,9,11,13}; // no point in going past 13
private static final List<int[][]> ALL_EDGE_SEQUENCES;
private static final Integer[] MAX_SUBSTITUTIONS = new Integer[] {2,3,4,5};
/**
* The width of this window.
*/
public static final int WIDTH = 700;
/**
* The height of this window.
*/
public static final int HEIGHT = 300;
private final PrototileChecker checker;
private static JComboBox<Integer> N = new JComboBox<Integer>(SYMMETRIES);
private static final JComboBox<Integer> maxSubstitutions = new JComboBox<Integer>(MAX_SUBSTITUTIONS);
/**
* The height of the buttons in this window.
*/
public static final int BUTTON_HEIGHT = (int) maxSubstitutions.getPreferredSize().getHeight();
private JComboBox<int[]> edgeSequence;
private static final EdgeSequenceEditor editor = new EdgeSequenceEditor();
private JButton go;
// set the format for the labels in the list of symmetries
static {
ALL_EDGE_SEQUENCES = new ArrayList<int[][]>();
for (Integer i : SYMMETRIES) {
int[][] list = FileManager.readEdgeSequenceList(i);
ALL_EDGE_SEQUENCES.add(list);
}
N.setRenderer(new IntegerRenderer<Integer>("","-fold symmetry"));
}
/**
* Create and display a Launcher.
*/
public Launcher() throws java.awt.HeadlessException
{
// create the layout
this.setLayout(new GridBagLayout());
this.setSize(WIDTH, HEIGHT);
this.setLocationRelativeTo(null);
this.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
// make a final reference to this for passing to actionListeners
final Launcher L = this;
// make and add the symmetry selector
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 0;
N.setSelectedItem((Integer)Point.N());
N.addActionListener(new AbstractAction("Change N") {
public void actionPerformed( ActionEvent event ) {
Point.setN((int)L.N.getSelectedItem());
L.checker.changeN();
L.changeComboBox();
L.checker.changeEdgeSequence((int[])L.edgeSequence.getSelectedItem());
L.go.setEnabled(L.checker.okay());
L.validate();
L.repaint();
}
});
this.add(N, c);
// make and add the edge sequence selector
editor.addActionListener(new AbstractAction("Change edge sequence") {
public void actionPerformed( ActionEvent event ) {
L.edgeSequence.setSelectedItem(L.editor.getItem());
}
});
edgeSequence = new JComboBox<int[]>(ALL_EDGE_SEQUENCES.get(Arrays.asList(SYMMETRIES).indexOf((Integer)Point.N())));
edgeSequence.setRenderer(new EdgeSequenceRenderer<int[]>());
edgeSequence.setEditor(editor);
edgeSequence.setEditable(true);
edgeSequence.addActionListener(new AbstractAction("Change edge sequence") {
public void actionPerformed( ActionEvent event ) {
L.checker.changeEdgeSequence((int[])L.edgeSequence.getSelectedItem());
L.go.setEnabled(L.checker.okay());
L.validate();
L.repaint();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 0;
this.add(edgeSequence, c);
// make and add the checker
this.checker = new PrototileChecker(this);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = checker.getHeight()-(int)checker.getMinimumSize().getHeight();
c.weightx = 0.0;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 1;
this.add(checker, c);
// make and add the go button
this.go = new JButton("Go!");
go.addActionListener(new AbstractAction("Go!") {
public void actionPerformed( ActionEvent event ) {
final int[] path = (int[])L.edgeSequence.getSelectedItem();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
L.dispose();
SubstitutionEditor loaded = SubstitutionEditor.createSubstitutionEditor(path,(int)L.maxSubstitutions.getSelectedItem());
RhombDisplay.setEditor(loaded);
loaded.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
go.setEnabled(false);
c.weightx = 0.5;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
this.add(go, c);
// make and add the max substitutions selector
c.weightx = 0.0;
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 2;
maxSubstitutions.setSelectedItem((Integer)2);
maxSubstitutions.setRenderer(new IntegerRenderer<Integer>("Maximum "," substitutions"));
this.add(maxSubstitutions, c);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.validate();
this.repaint();
}
/**
* Change the edge sequence editor/selector that is currently showing
* to reflect the current value of {@link Point#N()}.
*/
public void changeComboBox() {
edgeSequence.removeAllItems();
for (int[] i : ALL_EDGE_SEQUENCES.get(Arrays.asList(SYMMETRIES).indexOf((Integer)Point.N()))) edgeSequence.addItem(i);
}
/**
* Start the program!
*/
public static void main(String[] args) {
Point.setN(7);
Launcher L = new Launcher();
}
} // end of class Launcher
<file_sep>import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.plaf.basic.*;
import java.io.*;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import math.geom2d.AffineTransform2D;
import math.geom2d.Box2D;
import javax.swing.event.*;
/**
* Listen for changes in the RhombColorChooser, then modify ColourPalette.
*/
class ColourChangeListener implements ChangeListener {
/**
* The RhombColourChooser to which this is listening.
*/
private final RhombColorChooser chooser;
public ColourChangeListener(RhombColorChooser rs) {
this.chooser = rs;
}
public void stateChanged(ChangeEvent e) {
ColourPalette.changeColour(chooser.getSelected(),chooser.getColor());
chooser.redrawEditor();
}
}
/**
* Listens to the radio buttons.
*/
class RhombSelectorListener implements ActionListener {
/**
* The common RhombSelector that all RhombSelectorListeners modify.
*/
public static RhombSelector parent;
/**
* The index of the colour to which this Listener corresponds.
*/
private final int index;
/**
* Constructor. Set the index.
* @param i The index in {@link ColourPalette} of the colour to which this
* Listener corresponds.
*/
public RhombSelectorListener (int i) {
this.index = i;
}
public void actionPerformed(ActionEvent e) {
parent.setSelected(index);
}
} // end of class RhombSelectorListener
/**
* A panel with one copy of each prototile, with a radio button underneath.
* The radio button that is currently selected identifies the prototile, the
* colour of which is being changed.
*/
class RhombSelector extends JPanel {
// dimensions
private static final int XBUFFER = 6;
private static final int YBUFFER = 6;
private static final int COLOR_CHOOSER_WIDTH = 600; // a guess
/**
* The RhombColorChooser that contains this.
*/
private RhombColorChooser parent;
/**
* pictures of the prototiles.
*/
private List<RhombDisplay> RD;
/**
* radio buttons for selecting a prototile.
*/
private ButtonGroup prototiles;
/**
* the index of the colour that is currently selected.
*/
private int selected = 0;
/**
* Get the index of the colour currently being edited.
* @return The index of the colour currently being edited.
*/
public int getSelected() {
return selected;
}
/**
* Set the index of the colour to edit.
* @param i The new index of the colour to edit.
*/
public void setSelected(int i) {
selected = i;
parent.setColor(ColourPalette.colour(i));
}
/**
* Constructor.
* @param parent The RhombColorChooser that contains this.
*/
public RhombSelector(RhombColorChooser parent) {
super(new GridLayout(2,Point.N()/2));
this.parent = parent;
RhombSelectorListener.parent = this;
List<RhombBoundary> rules = RhombBoundary.prototileList();
int paneWidth = 2*COLOR_CHOOSER_WIDTH/(Point.N()-1);
RD = RhombDisplay.displayList(rules,paneWidth,2*paneWidth/3);
prototiles = new ButtonGroup();
for (RhombDisplay rd : RD) {
// add the pictures
rd.setBackground(this.getBackground());
this.add(rd);
rd.setVisible(true);
}
for (int i = 0; i < RD.size(); i++) {
// add the radio buttons
JRadioButton b = new JRadioButton("",(i==0));
b.addActionListener(new RhombSelectorListener(i));
b.setHorizontalAlignment(SwingConstants.CENTER);
prototiles.add(b);
this.add(b);
}
}
} // end of class RhombSelector
/**
* A class for changing the colours of prototiles.
*/
public class RhombColorChooser extends JColorChooser
{
private final SubstitutionEditor SE;
private final RhombSelector selector;
/**
* Get the index of the colour currently being edited.
* @return The index of the colour currently being edited.
*/
public int getSelected() {
return selector.getSelected();
}
/**
* Redraw the SubstitutionEditor that called this.
*/
public void redrawEditor() {
SE.validate();
SE.repaint();
}
public RhombColorChooser(SubstitutionEditor s) throws java.awt.HeadlessException
{
super(ColourPalette.colour(0));
SE = s;
this.setPreviewPanel(new JPanel());
this.setVisible(true);
this.selector = new RhombSelector(this);
this.getSelectionModel().addChangeListener(new ColourChangeListener(this));
this.setPreviewPanel(selector);
this.validate();
this.repaint();
}
} // end of class RhombColorChooser
<file_sep>import java.util.Deque;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.util.concurrent.*;
import java.io.*;
import java.lang.Math.*;
import java.util.Map;
import java.util.Stack;
import java.util.AbstractMap.*;
import java.io.PrintWriter;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import java.util.Arrays;
/**
* This corresponds to a trio of rhombs, all of which share a common point and any two
* of which share a common edge. The union of three such rhombs is a hexagon, and that
* hexagon can be flipped by shifting all the rhombs to opposite sides of the hex.
*/
public class SimpleHex implements Hex, Serializable {
/** For serialization. */
public static final long serialVersionUID = 7513L;
/** A representation of this as a hexagon. */
private final SimplePolygon2D hex;
/** The three rhombs in this hex. */
public final SimpleRhomb[] rhombs = new SimpleRhomb[3];
/**
* A set of instructions for flipping the hex.
* For each rhomb in triple, do we shift it by the positive or the negative
* of the direction vector common to the two other rhombs?
*/
private final boolean[] directions = new boolean[3];
/**
* Public constructor. No checks.
* We make a hexagon out of the three given rhombs.
*/
public SimpleHex(SimpleRhomb r0, SimpleRhomb r1, SimpleRhomb r2) {
rhombs[0] = r0;
rhombs[1] = r1;
rhombs[2] = r2;
// Set the shift directions.
// There are four possibilities, depending on the orientations of the three edges
// that meet at the common vertex of all three rhombs.
// 1) They all point away from the common vertex.
// 2) Two point away, one points toward.
// 3) One points away, two point toward.
// 4) They all point toward.
// This can be determined by counting the number of distinct corner points p
// of the three rhombs.
// 1) Only one corner means that all edges point away.
// 2) Two distinct corners means that two point away, one points toward.
// Three distinct corners means either:
// 3) One points away, two point toward; or
// 4) they all point toward.
int corners = 3; // the number of distinct corners of the three rhombs
// the rhomb with a corner that doesn't match the other two, if there is such a rhomb:
int oddOne = -1;
if (rhombs[0].p.equals(rhombs[1].p)) {
corners--;
directions[0] = true;
directions[1] = true;
oddOne = 2;
}
if (rhombs[0].p.equals(rhombs[2].p)) {
corners--;
directions[0] = true;
directions[2] = true;
oddOne = 1;
}
if (rhombs[1].p.equals(rhombs[2].p)) {
corners--;
directions[1] = true;
directions[2] = true;
oddOne = 0;
}
// At this point there are three possible values for corners:
// 0: All three rhombs have the same corner.
// 2: Two rhombs share a corner, and the third rhomb has a different one.
// 3: All three rhombs have different corners.
// We make the hex differently in each case.
Point2D[] output = new Point2D[6];
Point current = Point.ZERO();
if (corners==0) {
current = rhombs[0].p.plus(rhombs[0].v2);
output[0] = current.getPoint2D();
current = current.plus(rhombs[0].v1);
output[1] = current.getPoint2D();
current = rhombs[0].p.plus(rhombs[0].v1);
output[2] = current.getPoint2D();
current = current.plus(rhombs[1].commonEdge(rhombs[2]));
output[3] = current.getPoint2D();
current = rhombs[0].p.plus(rhombs[1].commonEdge(rhombs[2]));
output[4] = current.getPoint2D();
current = current.plus(rhombs[0].v2);
output[5] = current.getPoint2D();
} else if (corners==2) {
current = rhombs[oddOne].p.plus(rhombs[oddOne].v2);
output[0] = current.getPoint2D();
current = current.plus(rhombs[oddOne].v1);
output[1] = current.getPoint2D();
current = rhombs[oddOne].p.plus(rhombs[oddOne].v1);
output[2] = current.getPoint2D();
current = current.minus(rhombs[(oddOne+1)%3].commonEdge(rhombs[(oddOne+2)%3]));
output[3] = current.getPoint2D();
current = current.minus(rhombs[oddOne].v1);
output[4] = current.getPoint2D();
current = current.plus(rhombs[oddOne].v2);
output[5] = current.getPoint2D();
} else if (corners==3) {
// Now we have to identify whether we're in case 3) or 4).
boolean allIn = true;
for (oddOne = 0; oddOne < 3; oddOne++) {
// we're doing our first assignment of current here
current = rhombs[oddOne].p.plus(rhombs[oddOne].v1);
if (current.equals(rhombs[(oddOne+1)%3].p)||current.equals(rhombs[(oddOne+2)%3].p)) {
allIn = false;
directions[oddOne] = true;
break;
}
}
oddOne = (oddOne<3) ? oddOne : 2;
output[0] = current.getPoint2D();
current = rhombs[oddOne].p;
output[1] = current.getPoint2D();
current = rhombs[oddOne].p.plus(rhombs[oddOne].v2);
output[2] = current.getPoint2D();
// here's the difference between case 3) and case 4).
current = (allIn) ? current.minus(rhombs[(oddOne+1)%3].commonEdge(rhombs[(oddOne+2)%3])) : current.plus(rhombs[(oddOne+1)%3].commonEdge(rhombs[(oddOne+2)%3]));
output[3] = current.getPoint2D();
current = current.plus(rhombs[oddOne].v1);
output[4] = current.getPoint2D();
current = current.minus(rhombs[oddOne].v2);
output[5] = current.getPoint2D();
} else {
throw new IllegalArgumentException("Strange hex.");
}
hex = new SimplePolygon2D(output);
} // end of constructor
/**
* Getter method.
* @return A list of the three rhombs in this hex.
*/
public Rhomb[] getJoins() {
return rhombs;
}
/**
* Getter method.
* @return A polygon equal to the union of the three rhombs.
*/
public SimplePolygon2D getHex() {
return hex;
}
/**
* Simplification method.
* @return This is already a SimpleHex, so just return this.
*/
public SimpleHex createSimpleHex(List<Rhomb> allJoins, List<Rhomb> newJoins) {
return this;
}
/**
* Determine if this represents a hexagon--i.e., if the three rhombs all touch one another.
* @return true if the three rhombs all touch one another.
*/
public boolean valid() {
int[] counts = new int[3];
for (int i = 0; i < 3; i++) {
if (rhombs[1].equals(rhombs[0].adjacent[i])||rhombs[2].equals(rhombs[0].adjacent[i]))
counts[0]++;
if (rhombs[0].equals(rhombs[1].adjacent[i])||rhombs[2].equals(rhombs[1].adjacent[i]))
counts[1]++;
if (rhombs[0].equals(rhombs[2].adjacent[i])||rhombs[1].equals(rhombs[2].adjacent[i]))
counts[2]++;
}
return (counts[0]==2&&counts[1]==2&&counts[2]==2);
}
/**
* Determine if this contains a given Rhomb.
* This only contains {@link SimpleRhomb}s, so any other type of Rhomb will return false.
* @param jj The Rhomb we're looking for.
* @return true if this contains jj, false otherwise.
*/
public boolean contains(Rhomb jj) {
return (rhombs[0].equals(jj)||rhombs[1].equals(jj)||rhombs[2].equals(jj));
}
/**
* Determine if this contains a {@link SimpleRhomb} in common with another SimpleHex.
* @param t The other SimpleHex.
* @return true if this contains a SimpleRhomb that t also contains.
*/
public boolean doubleOverlap(SimpleHex t) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (this.rhombs[i].equals(t.rhombs[j])) return true;
}
}
return false;
}
/**
* Two SimpleHexes are equal if they contain the same three SimpleRhombs.
*/
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
SimpleHex t = (SimpleHex) obj;
int count1 = 0;
int count2 = 0;
for (int i = 0; i < rhombs.length; i++) {
for (int j = 0; j < rhombs.length; j++) {
if (this.rhombs[i].equals(t.rhombs[j])) {
count1 += i+1;
count2 += j+1;
break;
}
}
}
return (count1==6&&count2==6);
}
/**
* Flip the Rhombs in this SimpleHex.
* @return A list of all SimpleHexes created or destroyed by this flip.
*/
public List<Hex> flip() {
List<Hex> output = SimpleRhomb.flip(rhombs,directions);
// change the directions for the next flip
directions[0] = !directions[0];
directions[1] = !directions[1];
directions[2] = !directions[2];
// for (int i = 0; i < 3; i++) {
// System.out.println(rhombs[i] + " Adjacent to : ");
// for (int j = 0; j < 4; j++) {
// System.out.println(rhombs[i].adjacent[j]);
// }
// }
return output;
}
} // end of class SimpleHex
<file_sep>import java.io.*;
import java.util.concurrent.*;
/**
* A simple interface representing a unit of work that can be done in parallel.
* Created by <a href="http://www.people.fas.harvard.edu/~ekwan/"><NAME></a>.
*/
public interface WorkUnit extends Callable<Result>, Serializable
{
/**
* The {@link Result} that you get when you call this work unit.
*/
public Result call();
public String toString();
}
<file_sep>import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.plaf.basic.*;
import java.io.*;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import math.geom2d.line.Line2D;
import math.geom2d.AffineTransform2D;
import math.geom2d.Box2D;
// a button located on a hexagon (three rhombs, any pair of which shares an edge)
class HexButton extends JButton {
private static final Color RED = new Color(1, 0, 0, 0.75f); //Red
private static final double scale = 0.6; // shrink the clickable area
private RhombBoundary r;
private RhombDisplay RD;
private static boolean dragging = false;
private static List<Hex> draggable = null;
private static Component lastEntered = null;
private final Hex t;
private SimplePolygon2D mouseHex;
private SimplePolygon2D drawHex;
private static int xmin;
private static int ymin;
boolean in = false;
// private constructor
private HexButton(Hex tt,RhombDisplay rd,RhombBoundary r) {
this.t = tt;
this.RD = rd;
this.r = r;
this.xmin = RD.getXMin();
this.ymin = RD.getYMin();
this.setup();
}
// private setup method for use in constructor
private void setup() {
this.drawHex = t.getHex().transform(AffineTransform2D.createScaling(RD.scale,RD.scale));
this.mouseHex = drawHex.transform(AffineTransform2D.createTranslation(xmin,ymin));
// this.mouseHex = drawHex.transform(AffineTransform2D.createTranslation(xmin+RD.WIDTH_SHIFT,ymin+RD.HEIGHT_SHIFT));
this.mouseHex = mouseHex.transform(AffineTransform2D.createScaling(mouseHex.centroid(),scale,scale));
this.setEnabled(true);
this.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e)
{
if (mouseHex.contains(e.getX(), e.getY())) {
if (dragging&&draggable.contains(t)) {
draggable = r.flipTriple(t);
RD.click(draggable);
draggable.add(t);
}
in = true;
RD.repaint();
}
}
public void mouseExited(MouseEvent e)
{
if(!mouseHex.contains(e.getX(), e.getY())) {
in = false;
RD.repaint();
}
}
// public void mouseClicked(MouseEvent e)
// {
// if(mouseHex.contains(e.getX(), e.getY())) {
// if (m!=null) {
// RD.click(m.addFrame(t));
// } else {
// RD.click(r.flipTriple(t));
// }
// }
// }
public void mousePressed(MouseEvent e)
{
if(mouseHex.contains(e.getX(), e.getY())) {
dragging = true;
draggable = r.flipTriple(t);
RD.click(draggable);
draggable.add(t);
}
}
public void mouseReleased(MouseEvent e)
{
dragging = false;
draggable = null;
}
});
}
// public static factory method
public static HexButton createHexButton(Hex t,RhombDisplay d,RhombBoundary r) {
return new HexButton(t,d,r);
}
// is this still a hexagon?
public boolean valid() {
return t.valid();
}
// is tt the Hex of this?
public boolean hasTriple(Hex tt) {
return t.equals(tt);
}
public boolean contains(int x, int y) {
if (mouseHex.contains((double)x,(double)y)) {
return true;
} else {
return false;
}
}
public void paintComponent(Graphics g)
{
if (in) {
Graphics2D g2;
g2 = (Graphics2D)g;
g2.setColor(RED);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawHex.fill(g2);
}
}
} // end of class HexButton
/**
* A class for drawing and modifying a patch of rhombs.
* The modifications happen when the user clicks on a trio of rhombs,
* which are an instance of a {@link Hex}. The rhombs in this Hex are
* then rotated, which changes the Hexes in this that can subsequently
* be modified.
*/
public class RhombDisplay extends JPanel implements ActionListener
{
/**
* Extra space added at the left and right of a patch when
* determining the window size.
*/
public static final int WIDTH_BUFFER = 20;
/**
* Extra space added at the top and bottom of a patch when
* determining the window size.
*/
public static final int HEIGHT_BUFFER = 20;
/**
* The default scale for drawing {@link SimpleRhomb}s.
*/
public static final double SCALE = 30.0;
private final RhombBoundary r;
private List<Rhomb> joins;
private List<HexButton> buttons;
private final int xmin;
private final int ymin;
private final int width;
private final int height;
/**
* The scale that is used for drawing {@link SimpleRhomb}s in this display.
*/
public final double scale;
private static SubstitutionEditor editor = null;
/**
* Default Constructor.
* Use the default {@link #SCALE} and infer the window size from the
* contents of r, with {@link #WIDTH_BUFFER} and {@link HEIGHT_BUFFER}
* added to the edges.
* @param r The underlying patch that this allows the user to edit.
*/
public RhombDisplay(RhombBoundary r) throws java.awt.HeadlessException
{
this(r,RhombDisplay.SCALE);
}
/**
* Constructor with custom dimensions for the window.
* @param r The underlying patch that this allows the user to edit.
* @param scale The factor by which the {@link SimpleRhomb}s of r are
* scaled.
* @param w The width of this component.
* @param h The height of this component.
*/
public RhombDisplay(RhombBoundary r, double scale, int w, int h) throws java.awt.HeadlessException
{
this.r = r;
this.scale = scale;
joins = r.getJoins();
width = w+WIDTH_BUFFER;
height = h+HEIGHT_BUFFER;
joins.get(0).setScale(scale);
Box2D box = joins.get(0).getRhomb().boundingBox();
for (Rhomb j : joins) {
j.setScale(scale);
box = box.union(j.getRhomb().boundingBox());
}
ymin = height/2 - (int)((box.getMinY()+box.getMaxY())/2);
xmin = width/2 - (int)((box.getMinX()+box.getMaxX())/2);
setup();
}
/**
* Constructor with custom scale for the {@link SimpleRhomb}s.
* @param r The underlying patch that this allows the user to edit.
* @param scale The factor by which the {@link SimpleRhomb}s of r are
* scaled.
*/
public RhombDisplay(RhombBoundary r, double scale) throws java.awt.HeadlessException
{
this.r = r;
this.scale = scale;
joins = r.getJoins();
joins.get(0).setScale(scale);
Box2D box = joins.get(0).getRhomb().boundingBox();
for (Rhomb j : joins) {
j.setScale(scale);
box = box.union(j.getRhomb().boundingBox());
}
width = (int)box.getWidth()+WIDTH_BUFFER;
height = (int)box.getHeight()+HEIGHT_BUFFER;
ymin = height/2 - (int)((box.getMinY()+box.getMaxY())/2);
xmin = width/2 - (int)((box.getMinX()+box.getMaxX())/2);
this.setPreferredSize(new Dimension(width,height));
setup();
}
// utility method for use in constructors
private void setup() throws java.awt.HeadlessException
{
setLayout(null);
buttons = new LinkedList<>();
for (Hex t : r.getTriples()) {
HexButton b = HexButton.createHexButton(t,this,this.r);
buttons.add(b);
add(b);
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(this, BorderLayout.CENTER);
setBackground(Color.WHITE);
}
/**
* Call this method whenever a {@link Hex} is clicked on.
* @param l The Hexes that can be dragged after this click.
*/
public void click(List<Hex> l) {
flushButtons(l);
repaint();
}
/**
* Refresh the list of buttons that can be clicked in this.
* @param l A List of Hexes to add and remove. For each element of l,
* if this already has a corresponding button, then we remove it,
* otherwise we create such a button and add it.
*/
public void flushButtons(List<Hex> l) {
for (Hex t : l) {
boolean add = true;
for (HexButton hb : buttons) {
if (hb.hasTriple(t)) {
remove(hb);
buttons.remove(hb);
add = false;
break;
}
}
if (add) {
HexButton b = HexButton.createHexButton(t,this,this.r);
buttons.add(b);
add(b);
}
}
if (editor!=null) editor.updatePatch();
}
/**
* Clear all the buttons and create new ones from the {@link RhombBoundary}
* in this.
*/
public void resetButtons() {
for (HexButton hb : buttons) remove(hb);
buttons.clear();
for (Hex t : r.getTriples()) {
HexButton hb = HexButton.createHexButton(t,this,this.r);
add(hb);
buttons.add(hb);
}
}
/**
* Get the width of this.
* @return The width of this.
*/
public int getWidth() {
return width;
}
/**
* Get the height of this.
* @return The height of this.
*/
public int getHeight() {
return height;
}
/**
* Get the minimum x-coordinate of any rhomb in this.
* @return The minimum x-coordinate of any rhomb in this.
*/
public int getXMin() {
return xmin;
}
/**
* Get the minimum y-coordinate of any rhomb in this.
* @return The minimum y-coordinate of any rhomb in this.
*/
public int getYMin() {
return ymin;
}
/**
* Get the underlying data structure for this patch.
* @return The underlying data structure for this patch.
*/
public RhombBoundary getBoundary() {
return r;
}
/**
* Draw this.
* @param g The graphis object on which we draw this.
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2;
g2 = (Graphics2D)g;
g2.setColor(Color.BLACK);
g2.translate(xmin,ymin);
// g2.translate(xmin+WIDTH_SHIFT,ymin+HEIGHT_SHIFT);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Rhomb j : joins) {
g2.setColor(ColourPalette.colour(j.getType()-1));
j.getRhomb().fill(g2);
g2.setColor(Color.BLACK);
j.getRhomb().draw(g2);
}
for (HexButton b : buttons) b.paintComponent(g2);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width,height);
}
/**
* Print a gap-readable version of the underlying data structure if the
* print button is pressed.
* @see RhombBoundary#gapString()
*/
public void actionPerformed(ActionEvent e) {
if ("print".equals(e.getActionCommand())) {
System.out.println(r.gapString());
}
}
/**
* Set the {@link SubstitutionEditor} to which all RhombDisplays point.
* When a RhombDisplay is changed, this change will be reflected in the
* {@link PatchDisplay} of e.
* @param e All RhombDisplays will now point to e.
*/
public static void setEditor(SubstitutionEditor e) {
editor = e;
}
/**
* Take a List of RhombBoundaries and return a List of the corresponding RhombDisplays,
* all given the same scale, which is chosen in such a way as to make each one fit in
* a pane of the given dimensions.
* @param rules The RhombBoundaries we want to put into RhombDisplays.
* @param paneWidth The width of the pane in which we want each one to fit.
* @param paneHeight The height of the pane in which we want each one to fit.
* @return A List of RhombDisplays generated from rules, each one scaled to fit
* in a pane of dimensions paneWidth x paneHeight.
*/
public static List<RhombDisplay> displayList(List<RhombBoundary> rules, int paneWidth, int paneHeight) {
// find out the maximum height and width of all the patches
double maxHeight = 0.0;
double maxWidth = 0.0;
double prescale = 1.0; // the scale of the given rhombs (hopefully all the same)
for (RhombBoundary r : rules) {
List<Rhomb> joins = r.getJoins();
prescale = joins.get(0).getScale();
Box2D box = joins.get(0).getRhomb().boundingBox();
for (Rhomb j : joins) {
box = box.union(j.getRhomb().boundingBox());
}
if (box.getHeight() > maxHeight) maxHeight = box.getHeight();
if (box.getWidth() > maxWidth) maxWidth = box.getWidth();
}
double scale = prescale*Math.min((paneWidth - RhombDisplay.WIDTH_BUFFER)/maxWidth,
(paneHeight - RhombDisplay.HEIGHT_BUFFER)/maxHeight);
List<RhombDisplay> RD = new ArrayList<RhombDisplay>();
for (int i = 0; i < rules.size(); i++) {
RhombDisplay display = new RhombDisplay(rules.get(i),scale,paneWidth-RhombDisplay.WIDTH_BUFFER,paneHeight-RhombDisplay.HEIGHT_BUFFER);
RD.add(display);
}
return RD;
}
} // end of class RhombDisplay
<file_sep>import java.util.Deque;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.util.concurrent.*;
import java.io.*;
import java.lang.Math.*;
import java.util.Map;
import java.util.Stack;
import java.util.AbstractMap.*;
import java.io.PrintWriter;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.polygon.Polygon2D;
import math.geom2d.Point2D;
import java.util.Arrays;
/**
* Three {@link Yarn}s that all intesect each other.
* Any one of these Yarns intersects the other two consecutively, with no other Yarn
* intersections ({@link Join}s) between.
* This corresponds to a trio of rhombs, all of which share a common point and any two
* of which share a common edge. The union of three such rhombs is a hexagon, and that
* hexagon can be flipped by reversing the order of all pairs of Yarn intersections.
* We do not check for these properties on construction; we merely assume that they
* are satisfied.
*/
public class Triple implements Hex, Serializable {
/** For serialization. */
public static final long serialVersionUID = 5512L;
/** The three Yarns. */
private final Yarn[] y;
/** The three Joins. */
public Join[] j;
/** A representation of this as a hexagon. */
private transient SimplePolygon2D hex;
/** Private constructor. */
private Triple(Yarn y0, Yarn y1, Yarn y2) {
y = new Yarn[] {y0,y1,y2};
j = new Join[] {y0.joinWith(y1),y1.joinWith(y2),y2.joinWith(y0)};
hex = makeHex();
}
/**
* Public static factory method.
* The three Yarns are assumed to Join each other, with no other Yarns in between Joins.
* This property is not enforced.
* @param y0 The first Yarn.
* @param y1 The second Yarn.
* @param y2 The third Yarn.
*/
public static Triple createTriple(Yarn y0, Yarn y1, Yarn y2) {
return new Triple(y0,y1,y2);
}
/**
* Public static factory method.
* Create a Triple from an array of three Yarns. We don't check to make
* sure the array is the right length, or the Yarns have the right
* adjacency properties.
* @param yy The array of three Yarns from which we build a Triple.
*/
public static Triple createTriple(Yarn[] yy) {
Yarn y0 = yy[0];
Yarn y1 = yy[1];
Yarn y2 = yy[2];
return new Triple(y0,y1,y2);
}
/** Method for saving. */
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
}
/** Method for restoring a saved Join. */
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
hex = makeHex();
}
/** Method for restoring a saved Join. Empty. */
private void readObjectNoData() throws ObjectStreamException {
}
/**
* Getter method.
* @return A list of the three Joins between the three Yarns.
*/
public Rhomb[] getJoins() {
return j;
}
/**
* Getter method.
* I hope to remove this soon.
* @return A list of the three Yarns that constitute this Triple.
*/
public Yarn[] getYarns() {
return y;
}
/**
* Getter method.
* @return A polygon equal to the union of the three rhombs represented by the three Joins.
*/
public SimplePolygon2D getHex() {
return hex;
}
/**
* Set the hexagon.
* @return A polygon equal to the union of the three rhombs represented by the three Joins.
*/
private SimplePolygon2D makeHex() {
Point[] p0 = j[0].getVertices();
Point[] p1 = j[1].getVertices();
Point[] p2 = j[2].getVertices();
int i1 = -1;
int j1 = -1;
int i2 = -1;
int j2 = -1;
try {
// find the indices where p0 and p1 overlap
outerloop:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (p0[i].equals(p1[j])) {
i1 = i;
j1 = j;
break outerloop;
}
}
}
// make sure these are listed such that the p0-vertices
// appear consecutively in a counter-clockwise traversal
if (p0[(i1==0) ? 3 : i1-1].equals(p1[(j1+1)%4])) {
i2 = i1;
i1 = (i1==0) ? 3 : i1-1;
j2 = j1;
j1 = (j1+1)%4;
} else {
i2 = (i1+1)%4;
j2 = (j1==0) ? 3 : j1-1;
}
Point2D[] output = new Point2D[6];
for (int k = 0; k < 4; k++) {
if (p2[k].equals(p0[i2])) {
output[0] = p0[(i2+1)%4].getPoint2D();
output[1] = p0[(i2+2)%4].getPoint2D();
output[2] = p1[(j2+1)%4].getPoint2D();
output[3] = p1[(j2+2)%4].getPoint2D();
output[4] = p2[(k+1)%4].getPoint2D();
output[5] = p2[(k+2)%4].getPoint2D();
return new SimplePolygon2D(output);
} else if (p2[k].equals(p0[i1])) {
output[0] = p1[(j1+1)%4].getPoint2D();
output[1] = p1[(j1+2)%4].getPoint2D();
output[2] = p0[(i1+1)%4].getPoint2D();
output[3] = p0[(i1+2)%4].getPoint2D();
output[4] = p2[(k+1)%4].getPoint2D();
output[5] = p2[(k+2)%4].getPoint2D();
return new SimplePolygon2D(output);
}
}
throw new IllegalArgumentException("Something's wrong with this hex.");
} catch (Exception e) {
return null;
}
}
/**
* Determine if this represents a hexagon--i.e., if the three Yarns still satisfy the adjacency conditions.
* @return true if the three Yarns satisfy the adjacency conditions, false otherwise.
*/
public boolean valid() {
return (y[0].consecutive(y[1],y[2])&&y[1].consecutive(y[2],y[0])&&y[2].consecutive(y[0],y[1]));
}
/**
* Determine if this contains a given Rhomb.
* This only contains Joins, so any other type of Rhomb will return false.
* @param jj The Rhomb we're looking for.
* @return true if this contains jj, false otherwise.
*/
public boolean contains(Rhomb jj) {
return (j[0].equals(jj)||j[1].equals(jj)||j[2].equals(jj));
}
/**
* Determine if this contains a given Yarn.
* @param yy The Yarn we're looking for.
* @return true if this contains yy, false otherwise.
*/
public boolean contains(Yarn yy) {
return (y[0].equals(yy)||y[1].equals(yy)||y[2].equals(yy));
}
/**
* Determine if this contains a given pair of Yarns (order doesn't matter).
* @param yy The first Yarn we're looking for.
* @param z The second Yarn we're looking for.
* @return true if this contains yy and z, false otherwise.
*/
public boolean contains(Yarn yy, Yarn z) {
if (y[0].equals(yy)) return (y[1].equals(z)||y[2].equals(z));
if (y[1].equals(yy)) return (y[2].equals(z)||y[0].equals(z));
if (y[2].equals(yy)) return (y[0].equals(z)||y[1].equals(z));
return false;
}
/**
* Determine if this contains two Yarns in common with another Triple.
* @param t The other Triple.
* @return true if this contains two Yarns that t also contains.
*/
public boolean doubleOverlap(Triple t) {
int overlaps = 0;
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < y.length; j++) {
if (this.y[i].equals(t.y[j])) overlaps++;
}
}
return overlaps>1;
}
/**
* Two Triples are equal if they contain the same three Yarns.
*/
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
Triple t = (Triple) obj;
int count1 = 0;
int count2 = 0;
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < y.length; j++) {
if (this.y[i].equals(t.y[j])) {
count1 += i+1;
count2 += j+1;
break;
}
}
}
return (count1==6&&count2==6);
}
/**
* Pass in a list of Joins that contains the three Joins in this Triple.
* Then create a SimpleHex out of the three SimpleRhombs at the corresponding
* positions in a list of SimpleRhombs.
* @param allJoins A list of joins that contains the three Joins that constitute this hex.
* @param newJoins A list of SimpleRhombs that correspond to the Joins in allJoins.
* @return A SimpleHex made from the three SimpleRhombs in newJoins that lie at the
* same indices as the Joins in this lie in allJoins.
*/
public SimpleHex createSimpleHex(List<Rhomb> allJoins, List<Rhomb> newJoins) {
int i = allJoins.indexOf(j[0]);
SimpleRhomb r0 = (SimpleRhomb)newJoins.get(i);
i = allJoins.indexOf(j[1]);
SimpleRhomb r1 = (SimpleRhomb)newJoins.get(i);
i = allJoins.indexOf(j[2]);
SimpleRhomb r2 = (SimpleRhomb)newJoins.get(i);
return new SimpleHex(r0,r1,r2);
}
/**
* Suppose this Triple has just been flipped.
* Create a list of new Triples that are created as a result.
* @return A list of Triples that share a Join (two Yarns) with this one.
*/
public List<Triple> newTriples() {
List<Triple> output = new LinkedList<>();
Yarn z1 = y[0].nextYarn(y[1],y[2]);
Yarn z2 = y[2].nextYarn(y[1],y[0]);
if (z1!=null&&z1.equals(z2)) output.add(new Triple(z1,y[0],y[2]));
z1 = y[0].nextYarn(y[2],y[1]);
z2 = y[1].nextYarn(y[2],y[0]);
if (z1!=null&&z1.equals(z2)) output.add(new Triple(z1,y[0],y[1]));
z1 = y[1].nextYarn(y[0],y[2]);
z2 = y[2].nextYarn(y[0],y[1]);
if (z1!=null&&z1.equals(z2)) output.add(new Triple(z1,y[1],y[2]));
return output;
}
/**
* Flip the Yarns in this Triple.
* Each Yarn has a list of other Yarns that it meets; this method reverses
* the positions of any two of the Yarns in this Triple in the list of the
* third Yarn.
* @return A list of all Triples created or destroyed by this flip.
*/
public List<Hex> flip() {
if (y[0].hits(y[1],y[2])==y[0].ccwStart(y[2])) {
y[0].joinWith(y[1]).shift(Point.createPoint(y[2].getStartAngle()));
} else {
y[0].joinWith(y[1]).shift(Point.createPoint(y[2].getEndAngle()));
}
if (y[1].hits(y[2],y[0])==y[1].ccwStart(y[0])) {
y[1].joinWith(y[2]).shift(Point.createPoint(y[0].getStartAngle()));
} else {
y[1].joinWith(y[2]).shift(Point.createPoint(y[0].getEndAngle()));
}
if (y[2].hits(y[0],y[1])==y[2].ccwStart(y[1])) {
y[2].joinWith(y[0]).shift(Point.createPoint(y[1].getStartAngle()));
} else {
y[2].joinWith(y[0]).shift(Point.createPoint(y[1].getEndAngle()));
}
y[0].swap(y[1],y[2]);
y[1].swap(y[2],y[0]);
y[2].swap(y[0],y[1]);
return Yarn.surroundingTriples(y[0],y[1],y[2]);
}
} // end of class Triple
<file_sep>import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.AbstractMap;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import math.geom2d.Point2D;
import math.geom2d.polygon.SimplePolygon2D;
import math.geom2d.Box2D;
/**
* A window containing a number of {@link RhombDisplay}s equal to
* ({@link Point#N()} - 1)/2, each of which represents the image under
* a substitution rule of one of the rhombic prototiles.
* There is a panel underneath containing a {@link PatchDisplay} depicting
* a generic patch of a tiling arising from this substitution.
* Modifying the rules causes the patch to change in real time.
*/
public class SubstitutionEditor extends JFrame {
private JPanel contentPane;
private List<RhombBoundary> rules;
private List<SimpleRhomb> rhombs;
private int substitutions;
private final int maxSubstitutions;
private int[] edge;
private Point[] infl;
private List<RhombDisplay> RD;
private PatchDisplay patch;
/** The width of this window. */
public static final int WIDTH = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
/** The height of this window. */
public static final int HEIGHT = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
/** The horizontal space between the edge of the window and the displays. */
public static final int XMARGE = 6;
/** The horizontal space between adjacent {@link RhombDisplay}s. */
public static final int XBUFFER = 10;
/**
* The vertical space between the {@link RhombDisplay}s on top and
* the {@link PatchDisplay} on the bottom.
*/
public static final int YBUFFER = 10;
/** The vertical space between the edge of the window and the displays. */
public static final int YMARGE = 6;
/** stuff associated to the menu */
private JMenuBar menuBar;
private JMenu file;
private JMenu edit;
private JMenu view;
private JMenuItem restart;
private JMenuItem saveImage;
private JMenuItem save;
private JMenuItem load;
private JMenuItem quit;
private JMenuItem colours;
private JCheckBox antialiasing;
private JCheckBox supertiles;
private ButtonGroup substitutionCount;
/**
* Create a new SubstitutionEditor from a saved state.
* @param fileName The name of the file containing the saved state.
* @return The SubstitutionEditor saved in fileName.
*/
public static SubstitutionEditor loadSubstitutionEditor(String fileName) {
SubstitutionEditorSaveState data = FileManager.loadSubstitutionEditor(fileName);
ColourPalette.setAll(data.colours);
List<SimpleRhomb> startPatch = standardSeed();
int maxSubstitutions = (data.maxSubstitutions>0) ? data.maxSubstitutions : 2;
SubstitutionEditor output = new SubstitutionEditor(startPatch,data.rules,data.edge,maxSubstitutions);
output.patch.antialiasing = data.antialiasing;
output.antialiasing.setSelected(output.patch.antialiasing);
output.patch.supertiles = data.supertiles;
output.supertiles.setSelected(output.patch.supertiles);
return output;
}
/**
* Output a standard seed for a substitution: a list consisting of a single big rhomb.
* @return A list containing only one SimpleRhomb, which has angle {@link Point#N()}/2
* or {@link Point#N()}/2 +1.
*/
public static List<SimpleRhomb> standardSeed() {
Point p = Point.ZERO();
Point v1 = Point.createPoint(0);
int even = (Point.N()%4==1) ? Point.N()/2 : Point.N()/2 + 1;
Point v2 = Point.createPoint(-even);
int type = (Point.N()-even+1)/2;
int angle = 0;
List<SimpleRhomb> output = new ArrayList<SimpleRhomb>();
output.add(SimpleRhomb.createSimpleRhomb(p, v1, v2, type, angle).rotate(0));
return output;
}
/**
* Constructor that takes a list of substitution rules as input.
*/
public SubstitutionEditor(List<SimpleRhomb> rhombs, List<RhombBoundary> RB, int[] edge, int maxSubstitutions) {
super(Point.N() + "-fold symmetry");
this.maxSubstitutions = maxSubstitutions;
this.rhombs = rhombs;
this.rules = RB;
this.edge = edge;
this.infl = Point.inflation(edge);
setup();
makeMenu();
}
/**
* Constructor with default maximum of 2 substitutions.
*/
public SubstitutionEditor(List<SimpleRhomb> rhombs, List<RhombBoundary> RB, int[] edge) {
this(rhombs, RB, edge, 2);
}
/**
* Constructor that takes only the edge sequence and seed as input.
*/
public SubstitutionEditor(List<SimpleRhomb> rhombs, int[] edge, int maxSubstitutions) {
super(Point.N() + "-fold symmetry");
this.maxSubstitutions = maxSubstitutions;
this.rhombs = rhombs;
this.edge = edge;
this.infl = Point.inflation(edge);
rules = new ArrayList<RhombBoundary>();
for (int i = 0; i < Point.N()/2; i++) {
RhombBoundary RB = RhombBoundary.createRhombBoundary(Point.N()-2*i-1,edge);
if (RB.valid()) rules.add(RB);
else throw new IllegalArgumentException("With the given edge sequence, the rhomb with even angle " + (Point.N()-2*i-1) + " cannot be tiled.");
}
setup();
makeMenu();
}
/**
* Static factory method.
*/
public static SubstitutionEditor createSubstitutionEditor(int[] edge, int maxSubstitutions) {
return new SubstitutionEditor(standardSeed(),edge,maxSubstitutions);
}
/**
* Static factory method, default maximum number of substitutions (2).
*/
public static SubstitutionEditor createSubstitutionEditor(int[] edge) {
return new SubstitutionEditor(standardSeed(),edge,2);
}
/**
* Utility function for use in the constructor.
*/
private void setup() {
substitutions = 2;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, WIDTH, HEIGHT);
// so that we can get the height of the content pane
setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
int paneWidth = (WIDTH - 2*XMARGE - (rules.size()-1)*XBUFFER)/rules.size();
int paneHeight = 2*(HEIGHT - 2*YBUFFER - YMARGE)/5;
RD = RhombDisplay.displayList(rules,paneWidth,paneHeight);
for (int i = 0; i < rules.size(); i++) {
RD.get(i).setBounds(XMARGE+i*(XBUFFER+paneWidth), YMARGE, paneWidth, paneHeight);
contentPane.add(RD.get(i));
}
int patchHeight = 3*(HEIGHT - 2*YBUFFER - YMARGE)/5;
patch = new PatchDisplay(rhombs, rules, maxSubstitutions, infl, edge, WIDTH-2*XMARGE, patchHeight-YMARGE);
patch.setBounds(XMARGE, YMARGE+YBUFFER+paneHeight, WIDTH-2*XMARGE, patchHeight-YMARGE);
patch.subRhomb(substitutions);
contentPane.add(patch);
}
/**
* Utility function for use in the constructor.
* Creates the menu.
*/
private void makeMenu() {
menuBar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
menuBar.add(file);
edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
menuBar.add(edit);
view = new JMenu("View");
view.setMnemonic(KeyEvent.VK_V);
menuBar.add(view);
substitutionCount = new ButtonGroup();
// final reference to this for inner functions
final SubstitutionEditor temp = this;
restart = new JMenuItem(new AbstractAction("New") {
public void actionPerformed( ActionEvent event ) {
switch (savePrompt()) {
case JOptionPane.YES_OPTION: save(temp);
break;
case JOptionPane.NO_OPTION: break;
case JOptionPane.CANCEL_OPTION: return;
default: return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
temp.dispose();
Launcher L = new Launcher();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
restart.setMnemonic(KeyEvent.VK_N);
restart.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_N, ActionEvent.CTRL_MASK));
file.add(restart);
saveImage = new JMenuItem(new AbstractAction("Save image") {
public void actionPerformed( ActionEvent event )
{
FileDialog fDialog = new FileDialog(temp, "Save image", FileDialog.SAVE);
fDialog.setDirectory("./images");
fDialog.setVisible(true);
if (fDialog.getDirectory()==null||fDialog.getFile()==null) return;
String path = fDialog.getDirectory() + fDialog.getFile() + ((fDialog.getFile().endsWith(".ps")) ? "" : ".ps");
FileManager.postscriptDump(path,temp.patch);
}
});
file.add(saveImage);
save = new JMenuItem(new AbstractAction("Save") {
public void actionPerformed( ActionEvent event )
{
save(temp);
}
});
save.setMnemonic(KeyEvent.VK_S);
save.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, ActionEvent.CTRL_MASK));
file.add(save);
load = new JMenuItem(new AbstractAction("Open") {
public void actionPerformed( ActionEvent event ) {
switch (savePrompt()) {
case JOptionPane.YES_OPTION: save(temp);
break;
case JOptionPane.NO_OPTION: break;
case JOptionPane.CANCEL_OPTION: return;
default: return;
}
final SubstitutionEditor loaded = open(temp);
if (loaded==null) return;
else {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
temp.dispose();
RhombDisplay.setEditor(loaded);
loaded.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
});
load.setMnemonic(KeyEvent.VK_O);
load.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, ActionEvent.CTRL_MASK));
file.add(load);
quit = new JMenuItem(new AbstractAction("Quit") {
public void actionPerformed( ActionEvent event ) {
switch (savePrompt()) {
case JOptionPane.YES_OPTION: save(temp);
break;
case JOptionPane.NO_OPTION: break;
case JOptionPane.CANCEL_OPTION: return;
default: return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
temp.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
quit.setMnemonic(KeyEvent.VK_Q);
quit.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
file.add(quit);
colours = new JMenuItem(new AbstractAction("Change colours") {
public void actionPerformed( ActionEvent event )
{
final List<Color> oldColours = ColourPalette.copy();
final JDialog colourDialog = JColorChooser.createDialog(temp,"Colour palette",true,new RhombColorChooser(temp),
// the action performed on "OK"
new AbstractAction("Accept colours") {
public void actionPerformed( ActionEvent event ) {
}
},
// the action performed on "Cancel"
new AbstractAction("Cancel colours") {
public void actionPerformed( ActionEvent event ) {
ColourPalette.set(oldColours);
temp.updatePatch();
for (RhombDisplay rd : temp.RD) rd.repaint();
}
}
);
colourDialog.setVisible(true);
}
});
edit.add(colours);
antialiasing = new JCheckBox(new AbstractAction("Antialiasing") {
public void actionPerformed( ActionEvent event )
{
temp.patch.antialiasing = !temp.patch.antialiasing;
revalidate();
repaint();
}
});
antialiasing.setSelected(temp.patch.antialiasing);
view.add(antialiasing);
supertiles = new JCheckBox(new AbstractAction("Supertiles") {
public void actionPerformed( ActionEvent event )
{
temp.patch.supertiles = !temp.patch.supertiles;
revalidate();
repaint();
}
});
supertiles.setSelected(temp.patch.supertiles);
view.add(supertiles);
view.addSeparator();
for (int i = 0; i <= maxSubstitutions; i++) {
final int I = i;
JRadioButtonMenuItem button = new JRadioButtonMenuItem(new AbstractAction("Level " + I) {
public void actionPerformed( ActionEvent event )
{
patch.resetRhomb();
substitutions = I;
patch.subRhomb(substitutions);
contentPane.updateUI();
}
});
button.setSelected(substitutions==I);
substitutionCount.add(button);
view.add(button);
}
setJMenuBar(menuBar);
menuBar.setVisible(true);
}
/**
* Utility method for saving.
* This dumps the essential data from the editor.
* @return {@link SubstitutionEditorSaveState} containing essential fields
* needed to reconstruct this.
*/
public SubstitutionEditorSaveState dump() {
return new SubstitutionEditorSaveState(rules,edge,ColourPalette.copy(),patch.antialiasing,patch.supertiles,maxSubstitutions);
}
/**
* Update the {@link PatchDisplay} in this.
* Calls {@link PatchDisplay#update(int)}.
*/
public void updatePatch(){
patch.update(substitutions);
}
/**
* Return the SimpleRhombs that are showing in the window.
*/
public List<SimpleRhomb> getPatch(){
return patch.getPatch();
}
/**
* Static method for producing a pop-up prompt asking the user
* if he or she wants to save before proceeding.
* @return One of YES_OPTION, NO_OPTION, or CANCEL_OPTION from
* JOptionPane.
*/
public static int savePrompt(){
return JOptionPane.showConfirmDialog(null,"This action will close the current file. Do you want to save first?","Warning", JOptionPane.YES_NO_CANCEL_OPTION);
}
/**
* Static method for producing a pop-up prompt to save the given
* SubstitutionEditor.
* @param editor The current editor, which the user might wish
* to save.
*/
public static void save(SubstitutionEditor editor) {
FileDialog fDialog = new FileDialog(editor, "Save", FileDialog.SAVE);
fDialog.setDirectory("./saves");
fDialog.setVisible(true);
if (fDialog.getDirectory()==null||fDialog.getFile()==null) return;
String path = fDialog.getDirectory() + fDialog.getFile() + ((fDialog.getFile().endsWith(".sub")) ? "" : ".sub");
FileManager.saveSubstitutionEditor(path,editor.dump());
}
/**
* Static method for producing a pop-up prompt to open a saved
* SubstitutionEditor.
* @param editor The SubstitutionEditor that called this method.
* @return The editor that the user chooses to open. If the user
* cancels, this returns null.
*/
public static SubstitutionEditor open(SubstitutionEditor editor) {
FileDialog fDialog = new FileDialog(editor, "Open", FileDialog.LOAD);
fDialog.setDirectory("./saves");
fDialog.setVisible(true);
if (fDialog.getDirectory()==null||fDialog.getFile()==null) return null;
final String path = fDialog.getDirectory() + fDialog.getFile();
return loadSubstitutionEditor(path);
}
/**
* Take a screenshot, save it to file.
*/
public void SaveAction(){
try {
Robot robot = new Robot();
String format = "jpg";
String fileName = "PartialScreenshot." + format;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle captureRect = new Rectangle(106, 485, 1220, 400);
BufferedImage screenFullImage = robot.createScreenCapture(captureRect);
ImageIO.write(screenFullImage, format, new File(fileName));
System.out.println("A partial screenshot saved!");
} catch (AWTException | IOException ex) {
System.err.println(ex);
}
}
} // end of class SubstitutionEditor
| 7741517919155b0ad6d7f9da591079e19dbdec7e | [
"Java",
"Text"
] | 11 | Java | maloneyg/Substitution-Editor | 593d095f4f593dc9fa3724942056196db78da4f5 | 060f5741e2bffddc4db060a1a69a721c9b113b9c |
refs/heads/master | <repo_name>ujjawala397/reactburger<file_sep>/src/containers/BurgerBuilder/BurgerBuilder.js
import React, { Component } from 'react';
import Reactaux from '../../hoc/Reactaux';
import Burger from '../../components/Burger/Burger';
import BuildControls from '../../components/Burger/BuildControls/BuildControls';
const INGREDIENTS_PRICES={
salad:0.5,
cheese:0.4,
meat:1.3,
bacon:0.7
}
class BurgerBuilder extends Component {
// constructor(props) {
// super(props);
// this.state = {...}
// }
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice:4
}
addIngredientHandler=(type)=>{
const oldCount=this.state.ingredients[type];
const updatedCount=oldCount+1;
const updatedIngredients={
...this.state.ingredients
};
updatedIngredients[type]=updatedCount;
const priceAddition=INGREDIENTS_PRICES[type];
const oldPrice=this.state.totalPrice;
const newPrice=oldPrice+priceAddition;
this.setState({totalPrice:newPrice,ingredients:updatedIngredients})
}
removeIngredientHandler=(type)=>{
}
render () {
return (
<Reactaux>
<Burger ingredients={this.state.ingredients} />
<BuildControls ingredientAdded={this.addIngredientHandler}/>
</Reactaux>
);
}
}
export default BurgerBuilder; | 6e264058af36b3cd0dea1311bb00e06b5a8057f9 | [
"JavaScript"
] | 1 | JavaScript | ujjawala397/reactburger | a674173d4cf94588c38a03d5e610e4b4be4f8048 | d0225cc060bb0b281808997d1bb0d7d4e3a0ef39 |
refs/heads/master | <repo_name>dasizeman/golang_tools<file_sep>/tools.go
package tools
import (
"bufio"
"math/rand"
"os"
"time"
)
func init() {
// Seed the random numbers from the clock
rand.Seed(time.Now().UnixNano())
}
// IntMax returns the larger of the two provided integers
func IntMax(a, b int) int {
if a >= b {
return a
}
return b
}
// IntMin returns the smaller of the two provided integers
func IntMin(a, b int) int {
if a <= b {
return a
}
return b
}
// RandomInt returns a random integer in the range [min, max]
func RandomInt(min, max int) int {
return rand.Intn(max+1-min) + min
}
// ReadFileToStrings reads the lines in a text file to
// a slice of strings. It does not check if the input
// is actually a text file
func ReadFileToStrings(path string) ([]string, error) {
var lines []string
inFile, err := os.Open(path)
if err != nil {
return lines, err
}
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, err
}
// Simple "generic" stack
// -----------------------------------------
// Stack is a stack that can hold any value, but
// you have to type assert yourself
type Stack struct {
data []interface{}
topIdx int
}
// Peek returns the item at the top of the stack without popping it
func (stack *Stack) Peek() interface{} {
return stack.data[stack.topIdx-1]
}
// Pop pops the top item off the stack
func (stack *Stack) Pop() interface{} {
value := stack.Peek()
stack.topIdx--
return value
}
// Push pushes a new item to the top of the stack
func (stack *Stack) Push(value interface{}) {
stack.topIdx++
if stack.topIdx > len(stack.data) {
stack.data = append(stack.data, value)
} else {
stack.data[stack.topIdx-1] = value
}
}
// IsEmpty returns true if the stack is empty
func (stack *Stack) IsEmpty() bool {
return stack.topIdx <= 0
}
// Height returns the number of items on the stack
func (stack *Stack) Height() int {
return stack.topIdx
}
// StackQueue is a queue made from two stacks
type StackQueue struct {
enqueueStack, dequeueStack Stack
}
// Enqueue adds an item to the queue
func (queue *StackQueue) Enqueue(item interface{}) {
queue.enqueueStack.Push(item)
}
// Dequeue removes an item from the queue
func (queue *StackQueue) Dequeue() interface{} {
if queue.dequeueStack.IsEmpty() &&
!queue.enqueueStack.IsEmpty() {
queue.swapStacks()
}
if queue.IsEmpty() {
return nil
}
return queue.dequeueStack.Pop()
}
func (queue *StackQueue) swapStacks() {
for !queue.enqueueStack.IsEmpty() {
queue.dequeueStack.Push(queue.enqueueStack.Pop())
}
}
// IsEmpty returns true if the queue is empty
func (queue *StackQueue) IsEmpty() bool {
return queue.dequeueStack.IsEmpty() &&
queue.enqueueStack.IsEmpty()
}
// Length returns the number of items in the queue
func (queue *StackQueue) Length() int {
return queue.enqueueStack.Height() +
queue.dequeueStack.Height()
}
| be63b2aae697e7c37ec6c3dbb6e08ef49b039d57 | [
"Go"
] | 1 | Go | dasizeman/golang_tools | ad678deba0904edb4ec6215d96760fa0d72357fc | e6d0c40d7409969dda3290f0f697831b3f0bb2a7 |
refs/heads/master | <file_sep>$(document).ready(function () {
$(document).on("click", ".loadButton ", function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://vblog.test/v1/post/show",
dataType: "jsonp",
data: {
id: $(this).data('id'),
api_token: $(".container").data('api_token')
},
jsonpCallback: "show",
success: function (data) {
$("#postEditEditorArea").val(data['text']);
$("#postEditEditorArea").cleditor();
$('#editTitle').val(data['title']);
$("#editPost").attr("data-id",data['id']);
$("#listPosts").hide();
$("#editPost").show();
}
});
});
});
<file_sep><?php
/**
* Created by PhpStorm.
* User: Jakub
* Date: 12.02.2021
* Time: 14:30
*/
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'title', 'text',
];
public $timestamps = [
'updated_at', 'created_at'
];
public function getListPerPage()
{
return $this->latest()->take(25)->get();
}
public function getOne(int $id)
{
return $this->findOrFail($id);
}
public function createNew(string $title, string $text)
{
$this->create([
'title' => $title,
'text' => $text,
]);
}
}<file_sep>$(document).ready(function () {
$("#addButton").click(function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://vblog.test/v1/post",
dataType: "jsonp",
data: {
api_token: $(".container").data('api_token'),
title: $('#addTitle').val(),
text: $('#postAddEditorArea').val()
},
jsonpCallback: "store",
success: function (data) {
alert("post added");
}
});
});
});<file_sep>$.views.converters("upper", function (val) {
const newDate = new Date(val);
return (newDate.toLocaleDateString('de-DE'));
});
$.templates("myTemplate",
"<h2 style='color: #e60000;'>{{:title}}</h2>" +
"<p>{{:text}}</p>" +
"<span class='badge'>{{upper:created_at}}</span>" +
"<hr>");<file_sep><?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//VALIDACJA!!!
//Błedy
private $postModel;
public function __construct(Post $postModel)
{
$this->postModel = $postModel;
}
public function index()
{
return response()
->json($this->postModel->getListPerPage())
->setCallback('index');
}
public function show(Request $request)
{
return response()
->json($this->postModel->getOne($request->get('id')))
->setCallback('show');
}
public function store(Request $request)
{
$this->postModel->createNew($request->get('title'), $request->get('text'));
return response()
->json("OK")
->setCallback('store');
}
public function update(Request $request)
{
$blogPost = $this->postModel->getOne($request->get('id'));
$blogPost->title = $request->get('title');
$blogPost->text = $request->get('text');
$blogPost->save();
return response()
->json("OK")
->setCallback('update');
}
public function destroy(Request $request)
{
$blogPost = $this->postModel->getOne($request->get('id'));
$result = $blogPost->delete();
return response()
->json($result)
->setCallback('destroy');
}
}
<file_sep>$(document).ready(function () {
$("#editButton").click(function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://vblog.test/v1/post/update",
dataType: "jsonp",
data: {
api_token: $(".container").data('api_token'),
id: $('#editPost').data('id'),
title: $('#editTitle').val(),
text: $('#postEditEditorArea').val()
},
jsonpCallback: "update",
success: function (data) {
alert("post changed");
}
});
});
});<file_sep>$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://vblog.test/v1/posts",
dataType: "jsonp",
jsonpCallback: "index",
success: function (data) {
$.each(data, function (key, value) {
$("#posts").append($.templates.myTemplate(value));
});
}
});
});<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/v1/posts/', 'PostController@index');
$router->get('/v1/login/', 'UserController@login');
$router->group(['prefix' => '/v1/', 'middleware' => 'auth'],
function () use ($router) {
$router->get('/post/show', 'PostController@show');
$router->get('/post', 'PostController@store');
$router->get('/post/update', 'PostController@update');
$router->get('/post/delete', 'PostController@destroy');
});
<file_sep><?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
//VALIDACJA!!!
//Błedy
//auth
private $userModel;
public function __construct(User $userModel)
{
$this->userModel = $userModel;
}
public function login(Request $request)
{
$loggedUser = $this->userModel->where('username', $request->get('username'))->where('password', $request->get('password'))->firstOrFail();
$loggedUser->api_token = $this->generateApiToken(16);
$loggedUser->save();
return response()
->json(['api_token' => $loggedUser->api_token])
->setCallback('postLogin');
}
private function generateApiToken(int $length)
{
return base_convert(bin2hex(random_bytes($length)), 16, 36);
}
}
<file_sep>$(document).ready(function () {
$("#loginButton").click(function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://vblog.test/v1/login",
dataType: "jsonp",
data: {username: $('#username').val(), password: $('#<PASSWORD>').val()},
jsonpCallback: "postLogin",
success: function (data) {
$(".container").data('api_token', data['api_token']);
$("#formContent").hide();
$("#adminPanel").show();
}
});
});
}); | 216a4ab975306d2f35b0ea5b702a822cc19204cd | [
"JavaScript",
"PHP"
] | 10 | JavaScript | q-u-o-s-a/vblog | 24aae3a472d68f93e1d59ddd69b4e670a87aeaf1 | 5f36d77b8b8104cb1ee59e6d69cff7d6a5cb7f24 |
refs/heads/master | <repo_name>highsare/TeamKim<file_sep>/app/src/main/java/com/example/teamkim/customview/PopUpView.java
package com.example.teamkim.customview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by SCITMASTER on 2018-03-07.
*/
/*Class extended View Class for showing and animating images*/
public class PopUpView extends View implements View.OnTouchListener, View.OnClickListener, View.OnDragListener{
protected Bitmap Image;
protected Rect position;
protected float x,y;
public PopUpView(Context context) {
super(context);
}
public PopUpView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public void setImage(int imageSourceId) {
this.Image = BitmapFactory.decodeResource(getResources(),imageSourceId);
}
public Bitmap getImage() {
return Image;
}
public void setPosition(Rect position) {
this.position = position;
this.x = position.exactCenterX();
this.y = position.exactCenterY();
}
public Rect getPosition() {
return position;
}
public float getX(){
return x;
}
public float getY() {
return y;
}
@Override
public void setX(float x) {
this.x = x;
}
@Override
public void setY(float y) {
this.y = y;
}
/*Called in XML*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
protected void hideView(){
this.setVisibility(INVISIBLE);
}
@Override
public void onClick(View view) {
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
@Override
public boolean onDrag(View view, DragEvent dragEvent) {
return false;
}
}
<file_sep>/app/src/main/java/com/example/teamkim/customview/Stone.java
package com.example.teamkim.customview;
import android.graphics.Bitmap;
import android.graphics.Rect;
/**
* Created by SCITMASTER on 2018-03-06.
*/
public class Stone {
public static final int R = 20;
public static final int MASS = 1;
private Bitmap image;
private Rect rect;
private double veloX,veloY;
private float coordX,coordY;
public Stone(Bitmap image,double veloX, double veloY, float coordX, float coordY) {
this.image = image;
this.veloX = veloX;
this.veloY = veloY;
this.coordX = coordX;
this.coordY = coordY;
this.rect = new Rect((int)coordX-R,(int)coordY-R,(int)coordX+R,(int)coordY+R);
}
public float getDistance(){
return Math.abs((float) Math.sqrt((double)(Math.getExponent(this.coordX - 400F)+Math.getExponent(this.coordY - 1200F))));
}
public double getAngle(){
return Math.atan2(veloX,veloY);
}
public double getVelocity(){
return Math.sqrt(Math.pow(this.veloX,2) +Math.pow(this.veloY,2));
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public Rect getRect() {
return rect;
}
public void setRect(float coordX, float coordY) {
this.rect = new Rect((int)coordX-R,(int)coordY-R,(int)coordX+R,(int)coordY+R);
}
public double getVeloX() {
return veloX;
}
public void setVeloX(double veloX) {
this.veloX = veloX;
}
public double getVeloY() {
return veloY;
}
public void setVeloY(double veloY) {
this.veloY = veloY;
}
public float getCoordX() {
return coordX;
}
public void setCoordX(float coordX) {
this.coordX = coordX;
}
public float getCoordY() {
return coordY;
}
public void setCoordY(float coordY) {
this.coordY = coordY;
}
@Override
public String toString() {
return "Stone{" +
"rect=" + rect +
", veloX=" + veloX +
", veloY=" + veloY +
", coordX=" + coordX +
", coordY=" + coordY +
'}';
}
}
<file_sep>/app/src/main/java/com/example/teamkim/ingame/SpinField.java
package com.example.teamkim.ingame;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.example.teamkim.customview.PopUpView;
import com.example.teamkim.ingame.InGameActivity;
import java.util.ArrayList;
/**
* Created by SCITMASTER on 2018-03-07.
*/
public class SpinField extends PopUpView {
private float nextX;
private ArrayList<Float> xList,yList;
private String direcX;
public SpinField(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
xList = new ArrayList<>();
yList = new ArrayList<>();
direcX = "STAY";
this.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
xList.add(motionEvent.getX());
yList.add(motionEvent.getY());
break;
case MotionEvent.ACTION_MOVE:
xList.add(motionEvent.getX());
yList.add(motionEvent.getY());
break;
case MotionEvent.ACTION_UP:
this.setX(0);
this.setY(0);
nextX = xList.get(0) - xList.get(xList.size()-1);
if (nextX > 0){
direcX = "LEFT";
if (InGameActivity.spin > -2) {
InGameActivity.spin--;
}
}else{
direcX="RIGHT";
if (InGameActivity.spin < 2) {
InGameActivity.spin++;
}
}
xList.removeAll(xList);
yList.removeAll(yList);
break;
}
return true;
}
}
<file_sep>/app/src/main/java/com/example/teamkim/MainActivity.java
package com.example.teamkim;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.teamkim.customview.Stone;
import com.example.teamkim.ingame.InGameActivity;
// TODO: 2018-03-10 [Main] replace Views
public class MainActivity extends AppCompatActivity {
public static boolean newGame,isPosition,isEnd,isLoad;
public static int viewNum,endNum,turn,spin;
public static int[] p1ScoreBoard,p2ScoreBoard;
public static String player1_Name,player2_Name;
public static float[] p1_sListX,p1_sListY,p2_sListX,p2_sListY;
public static float aimX,aimY;
public static String first;
public static Stone currentStone;
AudioAttributes audioAttributes;
SoundPool soundPool;
Button btn_toSetting;
Bitmap redStone,yelStone;
Intent toInGameActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
toInGameActivity = new Intent(this,InGameActivity.class);
audioAttributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
soundPool = new SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(1).build();
soundPool.load(MainActivity.this,R.raw.bgm_main,1);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
soundPool.play(1, 1, 1, 1, -1, 1);
}
});
btn_toSetting = findViewById(R.id.btn_toSetting);
newGame = true;
isPosition = false;
isEnd = false;
isLoad = false;
viewNum = 1;
endNum = 1;
turn = 1;
spin = 0;
p1ScoreBoard = new int[4];
p2ScoreBoard = new int[4];
for (int i = 0 ; i < 4; i++){
p1ScoreBoard[i] = 0;
p2ScoreBoard[i] = 0;
}
player1_Name = "<NAME>";
player2_Name = "<NAME>";
p1_sListX = new float[4];
p1_sListY = new float[4];
p2_sListX = new float[4];
p2_sListY = new float[4];
for (int i = 0; i < 4; i++){
p1_sListX[i] = -50;
p1_sListY[i] = -50;
p2_sListX[i] = -50;
p2_sListY[i] = -50;
}
aimX = 0;
aimY = 0;
first = "PLAYER1";
redStone = BitmapFactory.decodeResource(getResources(),R.drawable.red_stone);
yelStone = BitmapFactory.decodeResource(getResources(),R.drawable.yel_stone);
currentStone = new Stone(redStone,0,0,-50,-50);
}
public void startGame(@Nullable View view){
soundPool.stop(1);
toInGameActivity.putExtra("newGame", newGame);
toInGameActivity.putExtra("isEnd", isEnd);
toInGameActivity.putExtra("isPosition", isPosition);
toInGameActivity.putExtra("isLoad", isLoad);
toInGameActivity.putExtra("viewNum", viewNum);
toInGameActivity.putExtra("endNum", endNum);
toInGameActivity.putExtra("turn",turn);
toInGameActivity.putExtra("spin", spin);
toInGameActivity.putExtra("player1_Name", player1_Name);
toInGameActivity.putExtra("player2_Name", player2_Name);
toInGameActivity.putExtra("p1_sListX", p1_sListX);
toInGameActivity.putExtra("p1_sListY", p1_sListY);
toInGameActivity.putExtra("p2_sListX", p2_sListX);
toInGameActivity.putExtra("p2_sListY",p2_sListY);
toInGameActivity.putExtra("aimX", aimX);
toInGameActivity.putExtra("aimY", aimY);
toInGameActivity.putExtra("first",first);
startActivity(toInGameActivity);
}
Handler turnHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
toInGameActivity.putExtra("newGame", newGame);
toInGameActivity.putExtra("isEnd", isEnd);
toInGameActivity.putExtra("isPosition", isPosition);
toInGameActivity.putExtra("isLoad", isLoad);
toInGameActivity.putExtra("viewNum", viewNum);
toInGameActivity.putExtra("endNum", endNum);
toInGameActivity.putExtra("turn",turn);
toInGameActivity.putExtra("spin", spin);
toInGameActivity.putExtra("player1_Name", player1_Name);
toInGameActivity.putExtra("player2_Name", player2_Name);
toInGameActivity.putExtra("p1_sListX", p1_sListX);
toInGameActivity.putExtra("p1_sListY", p1_sListY);
toInGameActivity.putExtra("p2_sListX", p2_sListX);
toInGameActivity.putExtra("p2_sListY",p2_sListY);
toInGameActivity.putExtra("aimX", aimX);
toInGameActivity.putExtra("aimY", aimY);
toInGameActivity.putExtra("first",first);
}
};
class NextTurn extends Thread {
@Override
public void run() {
while (isEnd){
turnHandler.sendEmptyMessage(0);
isEnd = false;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
<file_sep>/app/src/main/java/com/example/teamkim/ingame/DefaultField.java
package com.example.teamkim.ingame;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.example.teamkim.R;
import com.example.teamkim.customview.PopUpView;
import com.example.teamkim.customview.Stone;
import com.example.teamkim.ingame.InGameActivity;
/**
* Created by SCITMASTER on 2018-03-06.
*/
// TODO: 2018-03-10 Get image or situation info
// TODO: 2018-03-10 Show info about situation
/*Show Macth's Situation*/
public class DefaultField extends PopUpView {
Bitmap redStone,yelStone;
@SuppressLint("ClickableViewAccessibility")
public DefaultField(Context context, @Nullable AttributeSet attributeSet){
super(context, attributeSet);
redStone = BitmapFactory.decodeResource(getResources(), R.drawable.red_stone);
yelStone = BitmapFactory.decodeResource(getResources(), R.drawable.yel_stone);
//Cood of Stones
//Score
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0 ; i < 4; i++){
if (InGameActivity.p1_sListX[i] > 0) {
float x = InGameActivity.p1_sListX[i];
float y = InGameActivity.p1_sListY[i];
Rect rect = new Rect((int)x- Stone.R,(int)y-Stone.R,(int)x+Stone.R,(int)y+Stone.R);
canvas.drawBitmap(redStone,null,rect,null);
}
if (InGameActivity.p2_sListX[i] > 0) {
float x = InGameActivity.p2_sListX[i];
float y = InGameActivity.p2_sListY[i];
Rect rect = new Rect((int)x-Stone.R,(int)y-Stone.R,(int)x+Stone.R,(int)y+Stone.R);
canvas.drawBitmap(yelStone,null,rect,null);
}
}
}
} | 89c70ae8f27f6d468ab8cb40a09b04bdb382347d | [
"Java"
] | 5 | Java | highsare/TeamKim | 491b3a403a259ee3f50292359a9124e50cc80315 | b5a6c21972295db398ab7dce1b851a6f1715ea46 |
refs/heads/master | <file_sep>using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace ergo
{
public class HttpProxy : TcpProxy
{
private const int CONNECTION_ENDED_WAIT = 30000;
protected override void ProcessClientConnection(TcpClient client)
{
NetworkStream clientStream = client.GetStream();
StreamReader clientReader = new StreamReader(clientStream);
StreamWriter clientWriter = new StreamWriter(clientStream);
TcpClient server = null;
NetworkStream serverStream = null;
StreamReader serverReader = null;
StreamWriter serverWriter = null;
try
{
// Get the first line of the HTTP request which will tell us what to do
// and where to go. We can use stream reader here because the first request
// will always be UTF8.
string request = clientReader.ReadLine();
ParseRequestDetails(request, out string method, out string host, out int port, out string httpVersion);
ConnectToRemote(
host,
port,
out server,
out serverStream,
out serverReader,
out serverWriter);
if (method == "CONNECT")
{
// If its a connect request this doesn't need to be sent to the remote
// so just read it off the stream.
while (String.IsNullOrEmpty(clientReader.ReadLine()) == false) ;
SendConnectResponse(clientWriter, httpVersion);
}
else
{
// If we aren't using CONNECT then we have already read the first line
// that we want to send to the server. We cant just write it alone as the
// server while reject it. We need to send the entire header all at once.
serverWriter.WriteLine(request);
string line;
while (String.IsNullOrEmpty(line = clientReader.ReadLine()) == false)
{
serverWriter.WriteLine(line);
}
serverWriter.WriteLine();
serverWriter.Flush();
}
// Tunnels streams into each other sync. This is basically a transparent proxy.
// When both are done then the connections have been closed.
Task clientToServerTask = clientStream.CopyToAsync(serverStream);
Task serverToClientTask = serverStream.CopyToAsync(clientStream);
Task.WaitAny(
clientToServerTask,
serverToClientTask);
Task.WaitAll(
new Task[] { clientToServerTask, serverToClientTask },
CONNECTION_ENDED_WAIT);
}
finally
{
try
{
DisposeConnection(client, clientStream, clientReader, clientWriter);
DisposeConnection(server, serverStream, serverReader, serverWriter);
}
catch
{
}
}
}
/// <summary>
/// Parses the first line of a HTTP request to get the action and address info
/// </summary>
private void ParseRequestDetails(
string request,
out string method,
out string host,
out int port,
out string httpVersion)
{
string[] requestParts = request.Split(' ');
method = requestParts[0];
httpVersion = requestParts[2];
Uri uri = new Uri(requestParts[1]);
// CONNECT doesnt send the scheme, because it isnt needed.
// But Uri cant parse URLs without a scheme, so we just add one.
if (method == "CONNECT")
{
uri = new Uri("http://" + requestParts[1]);
}
host = uri.Host;
port = uri.Port;
}
private void SendConnectResponse(StreamWriter writer, string httpVersion)
{
writer.WriteLine(httpVersion + " 200 Connection established");
writer.WriteLine();
writer.Flush();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace ergo
{
public abstract class TcpProxy
{
private IList<TcpListener> _listeners = new List<TcpListener>();
public IList<IPEndPoint> ListenerAddresses { get; } = new List<IPEndPoint>();
public void Start()
{
if (ListenerAddresses.Count > 0)
{
_listeners.Clear();
foreach (IPEndPoint address in ListenerAddresses)
{
TcpListener listener = new TcpListener(address);
listener.Start();
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
_listeners.Add(listener);
}
}
}
public void Stop()
{
foreach (TcpListener listener in _listeners)
{
listener.Stop();
}
}
private void OnAcceptConnection(IAsyncResult asyncResult)
{
TcpListener listener = (TcpListener)asyncResult.AsyncState;
try
{
TcpClient client = listener.EndAcceptTcpClient(asyncResult);
Task.Run(() => { ProcessClientConnection(client); });
}
catch (ObjectDisposedException)
{
return;
}
// Start the call to accept another connection
if (listener != null)
{
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
}
}
protected void ConnectToRemote(
string host,
int port,
out TcpClient server,
out NetworkStream stream,
out StreamReader reader,
out StreamWriter writer)
{
server = new TcpClient();
server.Connect(host, port);
stream = server.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
}
protected void DisposeConnection(
TcpClient client,
NetworkStream stream,
StreamReader reader,
StreamWriter writer)
{
if (writer != null)
{
writer.Close();
writer.Dispose();
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
if (stream != null)
{
stream.Close();
stream.Dispose();
}
if (client != null)
{
client.Close();
}
}
protected abstract void ProcessClientConnection(TcpClient client);
}
}
<file_sep># ergo
A simple HTTP proxy library for .NET framework.
Currently designed for "outbound" connections only (i.e. something on your machine / server talking through the proxy to the outside world).
Supports HTTPS and CONNECT.
## Getting Started
### Prerequisites
Requires .NET framework 4.6.1 or later.
### Installing
Simply download ergo.dll and add it as a reference in your C# project.
## Usage
To create a HTTP proxy:
```
var proxy = new HttpProxy();
var ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.1"), port);
proxy.ListenerAddresses.Add(ipEndPoint);
```
To start the proxy:
```
proxy.Start();
```
To stop the proxy:
```
proxy.Stop();
```
| 6307799763eb2eec7062df81ce56998805813c7c | [
"Markdown",
"C#"
] | 3 | C# | River-Prince/ergo | 7e5597c639b1e7a5c0b8219942e137b3616d47fa | b6c4d90aec6d59f0985c041f0fb54bf555b1866c |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux'
import {CircularProgress} from 'material-ui';
class Loading extends Component {
render() {
return (
<div style={{position: 'absolute'}}>
{this.props.loading ? <CircularProgress /> : ''}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
loading: state.postModule.loading
};
};
const PostLoading = connect(mapStateToProps)(Loading);
export default PostLoading;<file_sep>import React, {Component} from 'react';
import {Link, IndexLink} from 'react-router';
// import logo from './logo.svg';
import './Header.css';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';
class Header extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
handleClose = () => this.setState({open: false});
render() {
return (
<header>
<AppBar title={<span>...</span>}
onLeftIconButtonTouchTap={this.handleToggle}
iconElementRight={<FlatButton label="Login" />}
/>
<Drawer
//containerStyle={{top: 64}}
open={this.state.open}
docked={false}
onRequestChange={(open) => this.setState({open})}>
<IndexLink to="/" activeClassName="active">
<MenuItem onTouchTap={this.handleClose}>Home</MenuItem>
</IndexLink>
<Link to="/post" activeClassName="active">
<MenuItem onTouchTap={this.handleClose}>Post</MenuItem>
</Link>
</Drawer>
</header>
);
}
}
export default Header;
<file_sep>import React, {Component} from 'react';
import {RaisedButton, IconButton, Toolbar, ToolbarGroup, ToolbarTitle} from 'material-ui';
import {connect} from 'react-redux';
import {VIEW_MODE, CREATE_MODE, EDIT_MODE} from './posts-actions';
import {deletePosts, changeMode} from './posts-actions';
class PToolbar extends Component {
onCreateClick = ()=> {
this.props.changeMode(CREATE_MODE);
};
onEditClick = ()=> {
this.props.changeMode(EDIT_MODE);
};
onDeleteClick = ()=> {
this.props.deletePosts(this.props.selectedIds[0]);
};
render() {
return (
<Toolbar>
<ToolbarGroup>
<ToolbarTitle text="Post"/>
</ToolbarGroup>
{this.props.mode ===VIEW_MODE &&(
<ToolbarGroup>
<RaisedButton label="Create" onTouchTap={this.onCreateClick}/>
<RaisedButton label="Edit" onTouchTap={this.onEditClick} disabled={this.props.selectedIds.length !== 1}/>
<RaisedButton label="Delete" onTouchTap={this.onDeleteClick} disabled={this.props.selectedIds.length !== 1 || this.props.loading > 0}/>
</ToolbarGroup>
)}
</Toolbar>
)
}
}
const mapStateToProps = (state) => {
return {
selectedIds: state.postModule.selectedIds,
mode: state.postModule.mode,
loading : state.postModule.loading
};
};
const mapDispatchToProps = (dispatch) => {
return {
deletePosts: (id) => {
dispatch(deletePosts(id));
},
changeMode: (mode) => {
dispatch(changeMode(mode))
}
}
};
const PostToolbar = connect(mapStateToProps, mapDispatchToProps)(PToolbar);
export default PostToolbar;<file_sep>import React from 'react';
import { render } from 'react-dom'
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {Router, browserHistory} from 'react-router';
import injectTapEventPlugin from 'react-tap-event-plugin';
import routes from './routes';
import reducers from './reducers';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger'
// import 'bootstrap/dist/css/bootstrap.css';
// import 'bulma/css/bulma.css';
import './index.css';
injectTapEventPlugin();
const logger = createLogger();
const store = createStore(
reducers,
applyMiddleware(thunk, logger)
);
render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('root')
);<file_sep>import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<div className="hero-foot">
<div className="container">
<div className="tabs is-centered">
<ul>
<li><a><NAME></a></li>
</ul>
</div>
</div>
</div>
);
}
}
export default Footer;<file_sep>import React, {Component} from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux';
import * as actions from './posts-actions';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
class Posts extends Component {
constructor(props) {
super(props);
this.state = {
fixedHeader: true,
selectable: true,
multiSelectable: false,
enableSelectAll: false,
showCheckboxes: true,
height: '600px'
};
}
componentWillMount() {
this.props.actions.fetchPosts();
}
renderPosts(posts) {
return posts.map((post) => {
return (
<TableRow key={post.id} selected={post.selected}>
<TableRowColumn>
<Link to={`/post/${post.id}`}>{post.title}</Link>
</TableRowColumn>
<TableRowColumn>{post.body}</TableRowColumn>
</TableRow>
);
});
}
onRowSelection = (selection)=>{
const selectedIds = [];
if(Array.isArray(selection)){
selection.forEach((index) => {
let post = this.props.posts[index];
selectedIds.push(post.id);
})
}
this.props.actions.selectPosts(selectedIds);
};
render() {
const {posts} = this.props;
return (
<Table {...this.state} onRowSelection={this.onRowSelection}>
<TableHeader>
<TableRow>
<TableHeaderColumn>Title</TableHeaderColumn>
<TableHeaderColumn>Body</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody deselectOnClickaway={false}>
{this.renderPosts(posts)}
</TableBody>
</Table>
);
}
}
const mapStateToProps = (state) => {
return {
posts: state.postModule.posts
};
};
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(actions, dispatch)
});
const PostList = connect(mapStateToProps, mapDispatchToProps)(Posts);
export default PostList;<file_sep>import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import PostPage from './posts/PostPage';
import PostForm from './posts/PostForm';
import PostDetailPage from './posts/PostDetailPage';
import HomePage from './home/HomePage'
import AboutPage from './about/AboutPage'
import NotFoundPage from './not-found/NotFoundPage'
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="post" component={PostPage}/>
<Route path="post/new" component={PostForm} />
<Route path="post/:id" component={PostDetailPage} />
<Route path="about" component={AboutPage} />
<Route path="*" component={NotFoundPage} />
</Route>
);<file_sep>import * as constants from './posts-constants';
import axios from 'axios';
// Export Constants
export const REQUEST_START = 'REQUEST_START';
export const REQUEST_ERROR = 'REQUEST_ERROR';
export const REQUEST_END = 'REQUEST_END';
export const FETCH_SUCCESS = 'FETCH_SUCCESS';
export const DELETE_SUCCESS = 'DELETE_SUCCESS';
export const CREATE_SUCCESS = 'CREATE_SUCCESS';
export const UPDATE_SUCCESS = 'UPDATE_SUCCESS';
export const CHANGE_MODE = 'CHANGE_MODE';
export const VIEW_MODE = 'VIEW_MODE';
export const CREATE_MODE = 'CREATE_MODE';
export const EDIT_MODE = 'EDIT_MODE';
export const SELECT = 'SELECT';
//common sync action
function requestStart() {
return {
type: REQUEST_START
}
}
function requestEnd() {
return {
type: REQUEST_END
}
}
export function requestError(error) {
return {
type: REQUEST_ERROR,
error,
};
}
//async action
//fetch posts
export function fetchPosts() {
return (dispatch) => {
dispatch(requestStart());
return axios.get('/api/v1/posts')
.then(res => dispatch(fetchPostsSuccess(res.data)))
.catch(error => dispatch(requestError(error)))
.then(()=> dispatch(requestEnd()));
};
}
//sync action
//fetch posts success
export function fetchPostsSuccess(posts) {
return {
type: FETCH_SUCCESS,
posts,
};
}
//async action
//delete posts
export function deletePosts(id) {
return (dispatch) => {
dispatch(requestStart());
return axios({
method: 'delete',
data: id,
url: `/api/v1/posts/${id}`,
})
.then(res => {
dispatch(deletePostsSuccess(res.data.id));
dispatch(selectPosts([]));
})
.catch(error => dispatch(requestError(error)))
.then(()=> dispatch(requestEnd()));
};
}
//fetch posts success
export function deletePostsSuccess(id) {
return {
type: DELETE_SUCCESS,
id,
};
}
//Create
export function createPost(post) {
return (dispatch) => {
dispatch(requestStart());
return axios({
method: 'post',
data: post,
url: '/api/v1/posts',
})
.then(res => {
dispatch(createSuccess(res.data));
dispatch(changeMode(VIEW_MODE));
dispatch(selectPosts([]));
})
.catch(error => dispatch(requestError(error)))
.then(()=> dispatch(requestEnd()));
}
}
export function createSuccess(post) {
return {
type: CREATE_SUCCESS,
post,
};
}
//Update
export function updatePost(post) {
return (dispatch) => {
dispatch(requestStart());
return axios({
method: 'put',
data: post,
url: `/api/v1/posts/${post.id}`,
})
.then(res => {
dispatch(updateSuccess(res.data));
dispatch(changeMode(VIEW_MODE));
dispatch(selectPosts([]));
})
.catch(error => dispatch(requestError(error)))
.then(()=> dispatch(requestEnd()));
}
}
export function updateSuccess(post) {
return {
type: UPDATE_SUCCESS,
post,
};
}
//Change mode
export function changeMode(mode) {
return {
type: CHANGE_MODE,
mode
}
}
//Select Post
export function selectPosts(ids) {
return {
type: SELECT,
ids
}
}
<file_sep>export const NAME = 'postModule';
//Change mode
export const CHANGE_MODE = 'CHANGE_MODE';
export const VIEW_MODE = 'VIEW_MODE';
export const CREATE_MODE = 'CREATE_MODE';
export const EDIT_MODE = 'EDIT_MODE';
//Select post
export const SELECT_POSTS = 'SELECT_POSTS';<file_sep>import React, { Component } from 'react';
import {connect} from 'react-redux'
import PostList from './PostList'
import PostForm from './PostForm'
import PostToolbar from './PostToolbar'
import PostLoading from './PostLoading'
import {CREATE_MODE, EDIT_MODE} from './posts-constants';
class PostIndex extends Component {
renderContent() {
let mode = this.props.mode;
switch (mode){
case CREATE_MODE:
return <PostForm />;
case EDIT_MODE:
return <PostForm />;
default:
return <PostList />;
}
}
render(){
return (
<div>
<PostLoading />
<PostToolbar/>
{this.renderContent()}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
mode: state.postModule.mode
};
};
const PostPage = connect(mapStateToProps)(PostIndex);
export default PostPage;<file_sep>import React, { Component } from 'react';
import {connect} from 'react-redux'
import {find} from './posts-reducers'
class Detail extends Component {
render() {
return(
<div>
<h1>Detail</h1>
Title: {this.props.current.title}
Body: {this.props.current.body}
</div>
)
}
}
const mapStateToProps = (state, props) => {
return {
current: find(state, props.params.id)
};
};
const PostDetailPage = connect(mapStateToProps)(Detail);
export default PostDetailPage;<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as actions from './posts-actions';
import {VIEW_MODE, CREATE_MODE, EDIT_MODE} from './posts-constants';
import {RaisedButton, TextField, Card, CardHeader, CardActions, CardText, CardTitle} from 'material-ui'
class Form extends Component {
constructor(props) {
super(props);
this.state = this.isEdit() ? this.props.current : {title: '', body: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
isCreate = ()=> {
return this.props.mode === CREATE_MODE;
};
isEdit = ()=> {
return this.props.mode === EDIT_MODE;
};
handleSubmit(e) {
e.preventDefault();
if (this.isCreate()) {
this.props.actions.createPost(this.state);
} else {
this.props.actions.updatePost(this.state);
}
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onCancelClick = ()=> {
this.props.actions.changeMode(VIEW_MODE);
this.props.actions.selectPosts([]);
};
render() {
return (
<from onSubmit={this.handleSubmit}>
<Card>
<CardTitle title={this.isCreate() ? "Create Post" : "Update Post"}/>
<CardText>
<TextField value={this.state.title} onChange={this.handleChange} name="title" hintText="Title"
floatingLabelText="Title"/>
<br/>
<TextField value={this.state.body} onChange={this.handleChange} name="body" hintText="Body"
floatingLabelText="Body"/>
</CardText>
<CardActions>
<RaisedButton label={this.isCreate() ? "Create" : "Update"} primary={true} onTouchTap={this.handleSubmit}/>
<RaisedButton label="Cancel" onTouchTap={this.onCancelClick}/>
</CardActions>
</Card>
</from>
);
}
}
const mapStateToProps = (state) => ({
current: state.postModule.current,
mode: state.postModule.mode
});
///PostForm Container
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(actions,dispatch)
});
const PostForm = connect(mapStateToProps, mapDispatchToProps)(Form);
export default PostForm;<file_sep>import * as constants from './posts-constants';
import {
REQUEST_START, REQUEST_ERROR, REQUEST_END,
FETCH_SUCCESS, DELETE_SUCCESS, CREATE_SUCCESS, UPDATE_SUCCESS,
CHANGE_MODE, VIEW_MODE, SELECT
} from './posts-actions';
const INITIAL_STATE = {
posts: [],
loading: 0,
error: '',
selectedIds: [],
current: null,
mode: VIEW_MODE
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case REQUEST_START:
return {...state, loading: state.loading + 1 };
case REQUEST_ERROR :
return {...state, error: action.error};
case REQUEST_END:
return {...state, loading: state.loading - 1};
case FETCH_SUCCESS:
return {...state, posts: action.posts};
case DELETE_SUCCESS:
return {...state, posts: state.posts.filter(post => post.id !== action.id)};
case CREATE_SUCCESS:
return {...state, posts: [...state.posts, action.post]};
case UPDATE_SUCCESS:
return {...state, posts: [...state.posts.filter(post => post.id !== action.id), action.post]};
//change mode
case CHANGE_MODE:
return {
...state,
mode: action.mode
};
//select posts
case SELECT:
return {
...state,
selectedIds: [...action.ids],
current: state.posts.find(post => post.id === action.ids[0])
};
default:
return state;
}
}
// Get all posts
export const findAll = state => state.postModule.posts;
// Get post by id
export const find = (state, id) => state.postModule.posts.find(post => post.id === id);
export const getCurrentMode = (state) => state.postModule.mode; | ef1bb2f88c56ff5043bd889e3b6e9350c37d09b5 | [
"JavaScript"
] | 13 | JavaScript | hao-hm/blog-redux | a15079173697e8b65e3bfaa0d47af81dfdf5dbc4 | 20580d5eee27c184881d99f5caabfa09f9e04bb2 |
refs/heads/master | <repo_name>Dmilham/Burger<file_sep>/db/seeds.sql
INSERT INTO burgers (burger_name,devouered ) VALUES ('Ham Burger',false);
INSERT INTO burgers (burger_name,devouered ) VALUES ('Cheese Burger',false);
INSERT INTO burgers (burger_name,devouered ) VALUES ('Bacon Cheeseburger',false);
<file_sep>/controllers/burgers_controller.js
var express = require('express');
var router = express.Router();
var burger = require('../models/burger.js');
router.get('/', function (req, res) {
res.redirect('/index');
});
router.get('/index', function (req, res) {
burger.all(function (data) {
var object = { burger: data };
res.render('index', object);
});
});
router.post('/index/create', function (req, res) {
console.log(req.body.entry);
burger.insert(req.body.entry ,function () {
res.redirect('/index');
});
});
router.put('/index/update/:id', function (req, res) {
burger.update(req.params.id , function () {
res.redirect('/index');
});
});
module.exports = router;<file_sep>/models/burger.js
var orm = require ('../config/orm.js')
var burger = {
all: function (cb) {
orm.selectAll(function (allRes) {
cb(allRes);
});
},
insert: function(name, cb){
orm.insertOne(name, function(oneRes){
cb(oneRes);
});
},
update: function (id, cb){
orm.updateOne( id, function (upRes) {
cb(upRes);
});
}
};
module.exports = burger;<file_sep>/db/schema.sql
-- creates our database called burgers_db
CREATE DATABASE burgers_db;
-- Utilize the new burgers_db database
USE burgers_db;
-- Creates a table called burger and enters these parameters
CREATE TABLE burgers
(
id int NOT NULL AUTO_INCREMENT,
burger_name varchar(255) NOT NULL,
devouered boolean NOT NULL,
date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
| caa8f3ab4e471f970cf095ad0317153171b736e7 | [
"JavaScript",
"SQL"
] | 4 | SQL | Dmilham/Burger | 7fed3a663cd95c05deeb2cb483eeb6036b27b1d6 | 3a2c388dcac8d1d096a973c0dfc6c38603a8ea33 |
refs/heads/master | <file_sep>#include <iostream>
using namespace std;
void BubbleSort (int arr[], int n)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n-i-1; ++j)
{
if (arr[j] > arr[j+1])
{
arr[j] = arr[j]+arr[j+1];
arr[j+1] = arr[j]-arr[j + 1];
arr[j] = arr[j]-arr[j + 1];
}
}
}
}
int main()
{
int n, i, arr[n];
cout << "Enter the array size: ";
cin >> n;
cout << "Enter the " << n << " elements: ";
for(i = 0; i < n; i++)
cin >> arr[i];
cout << endl << "Your data: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
BubbleSort(arr, n);
cout << endl << "\nAfter using selection or bubble sort... " << endl;
cout << "\nSorted Data: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int add(int, int), subtract(int, int), multiply(int, int), divide(int, int), modulo(int, int);
int main()
{
int menu, a, b, sum, diff, prod;
double rem, quo;
char ans;
cout << "Menu: " << endl;
cout << "\t1. Add" << endl;
cout << "\t2. Subtract" << endl;
cout << "\t3. Multiply" << endl;
cout << "\t4. Divide" << endl;
cout << "\t5. Modulus" << endl;
do{
cout << endl << "Enter your choice: ";
cin >> menu;
cout << "Enter your two numbers: ";
cin >> a >> b;
if(menu==1)
{
sum = add(a, b);
cout << "Sum = " << sum;
}
else if(menu==2)
{
diff = subtract(a, b);
cout << "Difference = " << diff;
}
else if(menu==3)
{
prod = multiply(a, b);
cout << "Product = " << prod;
}
else if(menu==4)
{
quo = divide(a, b);
cout << "Quotient = " << quo;
}
else if(menu==5)
{
rem = modulo(a, b);
cout << "Remainder = " << rem;
}
else
cout << "Invalid input. Please choose from 1 - 5.";
cout << endl << "Do you want to continue? (Y/N): ";
cin >> ans;
}
while(ans == 'Y' || ans == 'y');
return 0;
}
int add(int a, int b)
{
int add;
add = a + b;
return add;
}
int subtract(int a, int b)
{
int subtract;
subtract = a - b;
return subtract;
}
int multiply(int a, int b)
{
int multiply;
multiply = a * b;
return multiply;
}
int divide(int a, int b)
{
int divide;
divide = a / b;
return divide;
}
int modulo(int a, int b)
{
int modulo;
modulo = a % b;
return modulo;
}
| b172096577a9fc884f6f1b9cd632783297095fee | [
"C++"
] | 2 | C++ | rannadiche/Experiment-4 | 51f90a9b4a82ce00675e7fc4b90dfddb153e9c17 | 8a5b91ff4e9dd262f8b64a22951251c51a1f9eca |
refs/heads/master | <repo_name>neurosity/angular-openbci-rx<file_sep>/src/app/app.component.ts
import { Component, OnDestroy } from '@angular/core';
import { fromEvent } from 'rxjs/observable/fromEvent';
import * as io from 'socket.io-client';
@Component({
selector: 'app-root',
template: `<time-series [stream$]="stream$"></time-series>`
})
export class AppComponent implements OnDestroy {
wsEvent = 'metric/eeg';
socket = io('http://localhost:4301');
stream$ = fromEvent(this.socket, this.wsEvent);
ngOnDestroy () {
this.socket.removeListener(this.wsEvent);
}
}
<file_sep>/src/app/time-series/index.ts
export { TimeSeriesComponent } from './time-series.component';
<file_sep>/src/app/time-series/time-series.component.ts
import { Component, Input, ElementRef } from '@angular/core';
import { OnInit, OnDestroy } from '@angular/core';
import { SmoothieChart, TimeSeries } from 'smoothie';
import { ChartService } from '../shared/chart.service';
import { interval } from 'rxjs/observable/interval';
import { zip, tap, mergeMap } from 'rxjs/operators';
const channelsByBoard = {
cyton: 8,
ganglion: 4
};
@Component({
selector: 'time-series',
templateUrl: 'time-series.component.html',
styleUrls: ['time-series.component.css'],
})
export class TimeSeriesComponent implements OnInit {
constructor(private view: ElementRef, private chartService: ChartService) {}
@Input() stream$;
boardName = 'ganglion';
channels = channelsByBoard[this.boardName];
plotDelay = 1000;
amplitudes = [];
amplitudes$;
colors = this.chartService.getColors();
options = this.chartService.getChartSmoothieDefaults();
canvases = Array(this.channels).fill(0).map(() => new SmoothieChart(this.options));
lines = Array(this.channels).fill(0).map(() => new TimeSeries());
ngAfterViewInit () {
const channels = this.view.nativeElement.querySelectorAll('canvas');
this.canvases.forEach((canvas, index) => {
canvas.streamTo(channels[index], this.plotDelay);
});
}
ngOnInit () {
this.addTimeSeries();
this.amplitudes$ = this.stream$
.pipe(
mergeMap(samples => (samples as any)),
zip(interval(4), sample => sample)
).subscribe(sample => this.updateAmplitude(sample));
this.stream$.subscribe(buffer => {
(buffer as any).forEach(sample => this.draw(sample));
});
}
addTimeSeries () {
this.lines.forEach((line, index) => {
this.canvases[index].addTimeSeries(line, {
lineWidth: 2,
strokeStyle: this.colors[index].borderColor
});
});
}
draw (sample) {
sample.data.forEach((amplitude, index) => {
this.lines[index].append(sample.timestamp, amplitude);
});
}
updateAmplitude (sample) {
sample.data.forEach((amplitude, index) => {
this.amplitudes[index] = amplitude.toFixed(2);
});
}
}
<file_sep>/src/server/ganglion.js
const { Ganglion } = require('openbci-observable');
const { voltsToMicrovolts, bufferTime } = require('eeg-pipes');
const io = require('socket.io')(4301);
(async function init () {
const brain = new Ganglion({ verbose: true });
await brain.connect();
await brain.start();
brain.stream
.pipe(voltsToMicrovolts(), bufferTime(1000))
.subscribe(eeg => {
console.log(eeg);
io.emit('metric/eeg', eeg);
});
})();
| b2a09b1d819b50b849475f353abc2d5fd58f1434 | [
"JavaScript",
"TypeScript"
] | 4 | TypeScript | neurosity/angular-openbci-rx | cee21e494e505e406ae4f5fa9fca7d5f1b8fd755 | 8a13e7a12e76be415f1a0518e6a5c73ad3f12662 |
refs/heads/main | <repo_name>sushilparti/gildedroseexpands<file_sep>/src/main/java/com/sushil/exception/InsufficientQuantityException.java
package com.sushil.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class InsufficientQuantityException extends RuntimeException {
public InsufficientQuantityException(String exception) {
super(exception);
}
}
<file_sep>/src/main/java/com/sushil/exception/CustomExceptionHandler.java
package com.sushil.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.ArrayList;
import java.util.List;
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse(ExceptionMessages.GENERAL_ERROR_MESSAGE, details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ItemNotFoundException.class)
public final ResponseEntity<Object> handleItemNotFoundException(ItemNotFoundException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse(ExceptionMessages.ITEM_NOT_FOUND_ERROR_MESSAGE, details);
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(InsufficientQuantityException.class)
public final ResponseEntity<Object> handleInsufficientQuantityException(InsufficientQuantityException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse(ExceptionMessages.INVALID_QUANTITY_ERROR_MESSAGE, details);
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(PaymentException.class)
public final ResponseEntity<Object> handlePaymentException(PaymentException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse(ExceptionMessages.PAYMENT_ERROR_MESSAGE, details);
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
}
<file_sep>/src/main/java/com/sushil/config/SurgePricingConfig.java
package com.sushil.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.math.BigDecimal;
@Configuration
public class SurgePricingConfig {
@Value("${pricesurge.countThreshold}")
private int countThreshold;
@Value("${pricesurge.priceMultiplierPercent}")
private BigDecimal priceMultiplierPercent;
private final BigDecimal hundredValue = new BigDecimal(100);
public int getCountThreshold() {
return countThreshold;
}
public void setCountThreshold(int countThreshold) {
this.countThreshold = countThreshold;
}
public BigDecimal getPriceMultiplierPercent() {
return priceMultiplierPercent;
}
public void setPriceMultiplierPercent(BigDecimal priceMultiplierPercent) {
this.priceMultiplierPercent = priceMultiplierPercent;
}
public BigDecimal getHundredValue() {
return hundredValue;
}
}
<file_sep>/src/main/java/com/sushil/domain/OrderRequest.java
package com.sushil.domain;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class OrderRequest {
@NotEmpty(message = "Please provide an item name")
private String itemName;
@NotNull
@NotEmpty(message = "Please provide item quantity")
private int quantity;
public OrderRequest(String itemName, int quantity) {
this.itemName = itemName;
this.quantity = quantity;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
<file_sep>/src/main/java/com/sushil/repository/InventoryRepository.java
package com.sushil.repository;
import com.sushil.domain.Inventory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface InventoryRepository extends JpaRepository<Inventory, String> {
@Override
Optional<Inventory> findById(String id);
@Modifying
@Query(value = SQLQueries.updateInventoryQuery)
int updateItemQuantity(@Param("name") String itemName, @Param("quantity") int quantity);
}
<file_sep>/src/main/java/com/sushil/domain/OrderStatus.java
package com.sushil.domain;
public enum OrderStatus {
PENDING,
CONFIRMED,
SHIPPING,
COMPLETE
}
<file_sep>/README.md
**The Gilded Rose Expands**
This application supports the following endpoints:
1) **ListInventoryItems** - (GET) /v1/items
* This endpoint provides a list of all the items in the inventory with respective details
* Unsecured Endpoint
2) **GetItem** - (GET) /v1/item/{itemName}
* This endpoint provides details about a specific item
* Unsecured Endpoint
3) **PurchaseItem** - (POST) /v1/buy
* This endpoint allows the user the buy an item in the specified quantity
* Secured Endpoint
**How to Build/Run The Application**
Use Maven to build the application from command prompt
`mvn clean install`
Run the application from command prompt `mvn spring-boot:run`
**How to Use The Application**
1. Open Postman
2. Create a following request to list Inventory Items:
`GET localhost:8080/v1/items` and press Send. The list of inventory items will be displayed in the response section. Does not require any request parameter/object.
Sample Response:
`[
{
"name": "Irish Ale",
"description": "Ale from Ireland",
"price": 11,
"inventory": {
"name": "Irish Ale",
"quantity": 110
}
},
{
"name": "Bread",
"description": "Fresh Baked Bread",
"price": 3.60,
"inventory": {
"name": "Bread",
"quantity": 5
}
}
]`
3. Create a following request to list Inventory Items:
`GET localhost:8080/v1/item/Bread` and press Send. The item Bread and all its details will be displayed in the response section. Requires the item name as the path variable.
Sample Response:
`{
"name": "Bread",
"description": "Fresh Baked Bread",
"price": 3.60,
"inventory": {
"name": "Bread",
"quantity": 5
}
}`
4. Create a following request to purchase an item:
`POST localhost:8080/v1/buy and press Send. A request to purchase the item will be created, and the response will be available in the response section.
As this endpoint is secured, it will require basic auth credentials as part of the header. Please use Authorization tab in the Postman to add credentials.
In addition, this request also expects a request body. Make sure to add that in the body section.
Sample Request:
`{ "itemName" : "Bread",
"quantity" : 2
}`
Sample Response:
`{
"orderId": "a9324f08-96b7-4424-bdd3-e915cd293bdb",
"itemName": "Bread",
"quantity": 2,
"orderStatus": "PENDING"
}`
**Few Notes about this Application**
1. This application is built using Java and Spring Boot. It utilizes an in-memory database for simplicity. I avoided the usage of any other dependencies/tools.
2. This application is built using MVC(Model-View-Controller) pattern. This pattern provides a good separation of the layers which in turn lead to increased flexibility, code maintainability and independent testing.
3. For authentication, I chose Basic Authentication through Spring Security as it is simple to implement. However, as it is not secure, in the future, I would like to secure it with SSL or use a token based authentication system depending on the requirements.
4. For data format, I used JSON as it is simple, easy to use, readable, lightweight and is supported by most browsers.
5. Data for testing is being created through resources/data.sql file. Ths file could be edited in order to add more data.
6. Jacoco plugin is used for test coverage.
7. There is no functionality to cancel the orders.
8. Once an order is successful, the user is provided with the OrderResponse which contains the order details. This response is also being saved in a database table as a reference for all the orders. A unique orderId is being generated for every order.
Future Enhancements:
This project could be improved as most of the projects could. I took the design decisions in order to maintain code quality and development speed.
If given more time, I would enhance this project in the following ways:
* Use Swagger to add API documentation
* Use tools like Lombok to remove boilerplate code
* Improve Security of the endpoint - Add SSL to Basic Authentication or move to another mechanism (Form Based / Token Based)
* Improve testing
* Add more functionality such as payment support
Surge Pricing:
* This application implements Surge pricing through an in memory ConcurrentHashMap.
* Every time a user views a specific item, the hashmap is updated for that entry. If the hashMap entry exceeds the threshold, then surgePricing is enabled.
* When a user sends a request to purchase an item, a request is made to get the latest price. If the price surge is in effect, the price is multiplied with a configurable surge multiplier, and the user is billed for that amount.
* When a user requests an item, the application checks the latest price and provides that in the item details.
* A scheduled task is configured to run every hour (configurable), to clear the view counter and disable the surgePricing if in effect. A new counter will start for the new hour.<file_sep>/src/main/java/com/sushil/service/OrderService.java
package com.sushil.service;
import com.sushil.domain.Inventory;
import com.sushil.domain.OrderRequest;
import com.sushil.domain.OrderResponse;
import com.sushil.exception.ExceptionMessages;
import com.sushil.exception.ItemNotFoundException;
import com.sushil.exception.PaymentException;
import com.sushil.repository.InventoryRepository;
import com.sushil.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Optional;
@Service
public class OrderService {
private InventoryRepository inventoryRepository;
private OrderRepository orderRepository;
private SurgePricingService surgePricingService;
private ItemService itemService;
@Autowired
public OrderService(InventoryRepository inventoryRepository, OrderRepository orderRepository,
SurgePricingService surgePricingService, ItemService itemService) {
this.inventoryRepository = inventoryRepository;
this.orderRepository = orderRepository;
this.surgePricingService = surgePricingService;
this.itemService = itemService;
}
@Transactional
public Optional<OrderResponse> purchaseItem(OrderRequest orderRequest) {
Optional<Inventory> itemInventory = inventoryRepository.findById(orderRequest.getItemName());
if (!itemInventory.isPresent()) {
throw new ItemNotFoundException(ExceptionMessages.ITEM_NOT_FOUND_EXCEPTION_MESSAGE_DETAIL);
}
//check if requested number of quantity is less than the quantity in inventory
if (itemInventory.isPresent() && (itemInventory.get().getQuantity() >= orderRequest.getQuantity())) {
int updatedQuantity = itemInventory.get().getQuantity() - orderRequest.getQuantity();
BigDecimal itemPrice = surgePricingService.getLatestPrice(itemService.getItemPrice(orderRequest.getItemName()));
if (processPayment(itemPrice)) {
inventoryRepository.updateItemQuantity(orderRequest.getItemName(), updatedQuantity);
OrderResponse orderResponse = new OrderResponse(orderRequest.getItemName(), orderRequest.getQuantity());
orderRepository.save(orderResponse);
return Optional.of(orderResponse);
} else {
throw new PaymentException(ExceptionMessages.INVALID_PAYMENT_EXCEPTION_MESSAGE_DETAIL);
}
} else {
return Optional.empty();
}
}
private boolean processPayment(BigDecimal amount) {
//Payment Processing Logic to be added as a future enhancement
return true;
}
}
<file_sep>/src/test/java/com/sushil/controller/ItemControllerTest.java
package com.sushil.controller;
import com.sushil.domain.Item;
import com.sushil.exception.ItemNotFoundException;
import com.sushil.service.ItemService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@ExtendWith(MockitoExtension.class)
public class ItemControllerTest {
@InjectMocks
ItemController itemController;
@Mock
private ItemService itemService;
private String validItemName;
private String invalidItemName;
private Item item;
private List<Item> listOfItems;
@BeforeEach
public void init() {
item = new Item("Bread", "Fresh Baked Bread", new BigDecimal(2.50));
validItemName = "Bread";
invalidItemName = "invalidItem";
listOfItems = new ArrayList<Item>();
listOfItems.add(item);
}
@Test
public void getItemTest_shouldReturnSuccessCode() {
Mockito.when(itemService.getItem(validItemName)).thenReturn(Optional.of(item));
ResponseEntity<Item> itemResponseEntity = itemController.getItem(validItemName);
Assertions.assertThat(itemResponseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
}
@Test
public void getItemsTest_shouldReturnSuccessCode() {
Mockito.when(itemService.getInventoryList()).thenReturn(listOfItems);
ResponseEntity<List<Item>> listOfItemsResponse = itemController.getListOfItems();
Assertions.assertThat(listOfItemsResponse.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
}
@Test
public void ifItemNotExists_shouldThrowItemNotFoundException() {
Mockito.when(itemService.getItem(invalidItemName)).thenReturn(Optional.empty());
org.junit.jupiter.api.Assertions.assertThrows(ItemNotFoundException.class, () -> {
itemController.getItem(invalidItemName);
});
}
}
<file_sep>/src/main/java/com/sushil/service/SurgePricingService.java
package com.sushil.service;
import com.sushil.config.SurgePricingConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.concurrent.ConcurrentHashMap;
@Service
@EnableScheduling
public class SurgePricingService {
private static ConcurrentHashMap<String, Integer> itemViewCounter;
private boolean isSurged;
private final SurgePricingConfig surgePricingConfig;
@Autowired
public SurgePricingService(SurgePricingConfig surgePricingConfig) {
this.itemViewCounter = new ConcurrentHashMap<String, Integer>();
this.surgePricingConfig = surgePricingConfig;
}
private void updateVisitCounter(String itemName) {
if (!itemViewCounter.containsKey(itemName)) {
itemViewCounter.put(itemName, 1);
} else {
itemViewCounter.put(itemName, itemViewCounter.get(itemName) + 1);
}
}
@Scheduled(fixedRateString = "${pricesurge.timeThreshold}")
private void clearVisitCounter() {
itemViewCounter.clear();
setSurged(false);
}
public void processSurge(String itemName) {
updateVisitCounter(itemName);
if (isPriceSurgeRequired(itemName)) {
setSurged(true);
}
}
private boolean isPriceSurgeRequired(String itemName) {
return itemViewCounter.get(itemName) > surgePricingConfig.getCountThreshold();
}
public BigDecimal getLatestPrice(BigDecimal itemBasePrice) {
//if surge pricing is in effect, return price with surge multiplier, otherwise return as it is
if (isSurged()) {
return itemBasePrice.add(itemBasePrice
.multiply(surgePricingConfig.getPriceMultiplierPercent())
.divide(surgePricingConfig.getHundredValue()));
}
return itemBasePrice;
}
public boolean isSurged() {
return isSurged;
}
public void setSurged(boolean surged) {
isSurged = surged;
}
public static ConcurrentHashMap<String, Integer> getItemViewCounter() {
return itemViewCounter;
}
}
<file_sep>/src/main/java/com/sushil/repository/SQLQueries.java
package com.sushil.repository;
//This class will be used to store all sql queries in one place for easier maintenance
public class SQLQueries {
public static final String updateInventoryQuery = "update Inventory inv set inv.quantity = :quantity where inv.name = :name";
}
<file_sep>/src/main/java/com/sushil/exception/ExceptionMessages.java
package com.sushil.exception;
public class ExceptionMessages {
public static final String INSUFFICIENT_QUANTITY_EXCEPTION_MESSAGE_DETAIL = "This item is currently not available in the requested quantity";
public static final String ITEM_NOT_FOUND_EXCEPTION_MESSAGE_DETAIL = "Invalid Item. This item is not available";
public static final String INVALID_PAYMENT_EXCEPTION_MESSAGE_DETAIL = "Payment could not be completed. Please try again!";
public static final String GENERAL_ERROR_MESSAGE = "Server Error";
public static final String ITEM_NOT_FOUND_ERROR_MESSAGE = "Item Not Found";
public static final String INVALID_QUANTITY_ERROR_MESSAGE = "Item Quantity Unavailable";
public static final String PAYMENT_ERROR_MESSAGE = "Payment Failure";
}
<file_sep>/src/test/java/com/sushil/service/OrderServiceTest.java
package com.sushil.service;
import com.sushil.domain.Inventory;
import com.sushil.domain.OrderRequest;
import com.sushil.domain.OrderResponse;
import com.sushil.exception.ItemNotFoundException;
import com.sushil.repository.InventoryRepository;
import com.sushil.repository.OrderRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.util.Optional;
@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {
@Mock
private InventoryRepository inventoryRepository;
@Mock
private OrderRepository orderRepository;
@Mock
private SurgePricingService surgePricingService;
@Mock
private ItemService itemService;
@InjectMocks
private OrderService orderService;
private Inventory itemInventory;
private String itemName;
private OrderRequest validOrderRequest;
private OrderRequest invalidOrderRequest;
private OrderRequest invalidItemOrderRequest;
private BigDecimal mockPrice;
@BeforeEach
public void init() {
mockPrice = new BigDecimal(11);
itemInventory = new Inventory("testItem", 10);
itemName = itemInventory.getName();
validOrderRequest = new OrderRequest("testItem", 3);
invalidOrderRequest = new OrderRequest("testItem", 15);
invalidItemOrderRequest = new OrderRequest("invalidItem", 15);
}
@Test
public void shouldBeAbleToPurchaseValidItem() {
Mockito.when(itemService.getItemPrice(itemName)).thenReturn(new BigDecimal(10));
Mockito.when(surgePricingService.getLatestPrice(Mockito.any())).thenReturn(mockPrice);
Mockito.when(inventoryRepository.findById(itemName)).thenReturn(Optional.of(itemInventory));
Optional<OrderResponse> orderResponse = orderService.purchaseItem(validOrderRequest);
Assertions.assertNotNull(orderResponse.get().getOrderId());
}
@Test
public void shouldNotBeAbleToPurchaseItemWithInvalidQuantity() {
Mockito.when(inventoryRepository.findById(itemName)).thenReturn(Optional.of(itemInventory));
Optional<OrderResponse> orderResponse = orderService.purchaseItem(invalidOrderRequest);
Assertions.assertFalse(orderResponse.isPresent());
}
@Test
public void ifItemNotExists_shouldThrowItemNotFoundException() {
Mockito.when(inventoryRepository.findById(invalidItemOrderRequest.getItemName())).thenReturn(Optional.empty());
Assertions.assertThrows(ItemNotFoundException.class, () -> {
orderService.purchaseItem(invalidItemOrderRequest);
});
}
}
<file_sep>/src/main/java/com/sushil/exception/PaymentException.java
package com.sushil.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class PaymentException extends RuntimeException {
public PaymentException(String exception) {
super(exception);
}
}
<file_sep>/src/test/java/com/sushil/controller/OrderControllerTest.java
package com.sushil.controller;
import com.sushil.domain.OrderRequest;
import com.sushil.domain.OrderResponse;
import com.sushil.service.OrderService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.Optional;
@ExtendWith(MockitoExtension.class)
public class OrderControllerTest {
private OrderRequest orderRequest;
private OrderResponse orderResponse;
@InjectMocks
private OrderController orderController;
@Mock
private OrderService orderService;
@BeforeEach
public void init() {
orderRequest = new OrderRequest("Cookies", 10);
orderResponse = new OrderResponse("Cookies", 10);
}
@Test
public void shouldReturnSuccessStatusCode() {
Mockito.when(orderService.purchaseItem(orderRequest)).thenReturn(Optional.of(orderResponse));
ResponseEntity<OrderResponse> orderResponseEntity = orderController.purchaseItem(orderRequest);
Assertions.assertThat(orderResponseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
}
}
<file_sep>/src/main/resources/data.sql
DROP TABLE IF EXISTS item;
CREATE TABLE item (
name VARCHAR(300) PRIMARY KEY,
description VARCHAR(600) NOT NULL,
price DECIMAL NOT NULL
);
INSERT INTO item (name, description, price) VALUES
('Spiced Mead', 'Spiced Mead from the Northern Tribes', 25.50),
('Irish Ale', 'Ale from Ireland', 11),
('Bread', 'Fresh Baked Bread', 3.60);
DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (
name VARCHAR(300) PRIMARY KEY,
quantity INT NOT NULL
);
INSERT INTO inventory (name, quantity) VALUES
('Spiced Mead', 30),
('Irish Ale', 110),
('Bread', 5);<file_sep>/src/main/java/com/sushil/controller/ItemController.java
package com.sushil.controller;
import com.sushil.domain.Item;
import com.sushil.exception.ExceptionMessages;
import com.sushil.exception.ItemNotFoundException;
import com.sushil.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RestController;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/v1")
public class ItemController {
private ItemService itemService;
@Autowired
public ItemController(ItemService itemService) {
this.itemService = itemService;
}
@RequestMapping(method = RequestMethod.GET, path = "/items", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Item>> getListOfItems() {
return ResponseEntity.ok(itemService.getInventoryList());
}
@RequestMapping(method = RequestMethod.GET, path = "/item/{itemName}")
public ResponseEntity<Item> getItem(@PathVariable String itemName) {
Optional<Item> item = itemService.getItem(itemName);
if (item.isPresent()) {
return ResponseEntity.ok().body(item.get());
} else {
throw new ItemNotFoundException(ExceptionMessages.ITEM_NOT_FOUND_EXCEPTION_MESSAGE_DETAIL);
}
}
}
<file_sep>/src/test/java/com/sushil/model/ListOfItems.java
package com.sushil.model;
import com.sushil.domain.Item;
import java.util.List;
public class ListOfItems {
private List<Item> listOfItems;
public List<Item> getListOfItems() {
return listOfItems;
}
}
<file_sep>/src/main/java/com/sushil/service/ItemService.java
package com.sushil.service;
import com.sushil.domain.Item;
import com.sushil.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Service
public class ItemService {
private ItemRepository itemRepository;
private SurgePricingService surgePricingService;
@Autowired
public ItemService(ItemRepository itemRepository, SurgePricingService surgePricingService) {
this.itemRepository = itemRepository;
this.surgePricingService = surgePricingService;
}
public List<Item> getInventoryList() {
return itemRepository.findAll();
}
public Optional<Item> getItem(String itemName) {
Optional<Item> item = itemRepository.findById(itemName);
if (item.isPresent()) {
//Update Surge Counter with every visit by the customer
surgePricingService.processSurge(itemName);
item.get().setPrice(surgePricingService.getLatestPrice(item.get().getPrice()));
return item;
} else {
return Optional.empty();
}
}
public BigDecimal getItemPrice(String itemName) {
return itemRepository.findById(itemName).get().getPrice();
}
}
<file_sep>/src/test/java/com/sushil/integration/ItemControllerIntegrationTest.java
package com.sushil.integration;
import com.sushil.Application;
import com.sushil.config.SurgePricingConfig;
import com.sushil.domain.Item;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.jdbc.Sql;
import java.util.List;
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ItemControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private SurgePricingConfig surgePricingConfig;
@Sql(scripts = {"classpath:data.sql"})
@Test
public void testGetInventoryItemsApi_Success() {
ResponseEntity<List<Item>> listOfItems = restTemplate
.exchange("/v1/items", HttpMethod.GET, null, new ParameterizedTypeReference<List<Item>>() {
});
Assertions.assertEquals(listOfItems.getBody().size(), 3);
Assertions.assertEquals(listOfItems.getStatusCode(), HttpStatus.OK);
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void testGetItemApi_Success() {
ResponseEntity<Item> itemResponse = restTemplate.getForEntity("/v1/item/Bread", Item.class);
Assertions.assertEquals(itemResponse.getBody().getName(), "Bread");
Assertions.assertEquals(itemResponse.getStatusCode(), HttpStatus.OK);
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void testGetItemApi_Invalid() {
ResponseEntity<Item> itemResponse = restTemplate.getForEntity("/v1/item/Cheesecake", Item.class);
Assertions.assertEquals(itemResponse.getStatusCode(), HttpStatus.NOT_FOUND);
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void testGetItemApi_Valid_PriceShouldSurgeAfterCountThreshold() {
surgePricingConfig.setCountThreshold(3);
ResponseEntity<Item> itemResponse1 = restTemplate.getForEntity("/v1/item/Bread", Item.class);
restTemplate.getForEntity("/v1/item/Bread", Item.class);
restTemplate.getForEntity("/v1/item/Bread", Item.class);
ResponseEntity<Item> itemResponse2 = restTemplate.getForEntity("/v1/item/Bread", Item.class);
//this should return -1 as first BigDecimal should be less than second
int comparePrices = itemResponse1.getBody().getPrice().compareTo(itemResponse2.getBody().getPrice());
//verify if the result from comparing two BigDecimal prices is as expected
Assertions.assertEquals(comparePrices, -1);
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void testGetItemApi_Valid_PriceShouldNotSurgeBeforeCountThreshold() {
surgePricingConfig.setCountThreshold(3);
ResponseEntity<Item> itemResponse1 = restTemplate.getForEntity("/v1/item/Bread", Item.class);
ResponseEntity<Item> itemResponse2 = restTemplate.getForEntity("/v1/item/Bread", Item.class);
Assertions.assertEquals(itemResponse1.getBody().getPrice(), itemResponse2.getBody().getPrice());
}
}
<file_sep>/src/test/java/com/sushil/integration/OrderControllerIntegrationTest.java
package com.sushil.integration;
import com.sushil.Application;
import com.sushil.domain.OrderRequest;
import com.sushil.domain.OrderResponse;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.web.client.ResourceAccessException;
import java.util.Base64;
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OrderControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
private static final String userName = "john";
private static final String password = "<PASSWORD>";
private int validQuantity = 2;
private int invalidQuantity = 50;
@Sql(scripts = {"classpath:data.sql"})
@Test
public void purchaseItemsApi_Authenticated() {
OrderRequest orderRequest = new OrderRequest("Bread", validQuantity);
HttpEntity<?> httpEntity = new HttpEntity<>(orderRequest, getRequestHeaders());
ResponseEntity<OrderResponse> orderResponse = restTemplate
.exchange("/v1/buy", HttpMethod.POST, httpEntity, OrderResponse.class);
Assertions.assertEquals(orderResponse.getStatusCode(), HttpStatus.OK);
Assertions.assertNotNull(orderResponse.getBody().getOrderId());
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void purchaseItemsApi_NotAuthenticated() {
OrderRequest orderRequest = new OrderRequest("Bread", validQuantity);
HttpEntity<?> httpEntity = new HttpEntity<>(orderRequest);
Assertions.assertThrows(ResourceAccessException.class, () -> {
ResponseEntity<OrderResponse> orderResponse = restTemplate
.exchange("/v1/buy", HttpMethod.POST, httpEntity, OrderResponse.class);
});
}
@Sql(scripts = {"classpath:data.sql"})
@Test
public void purchaseItemsApi_InvalidQuantity() {
OrderRequest orderRequest = new OrderRequest("Bread", invalidQuantity);
HttpEntity<?> httpEntity = new HttpEntity<>(orderRequest, getRequestHeaders());
ResponseEntity<OrderResponse> orderResponse = restTemplate
.exchange("/v1/buy", HttpMethod.POST, httpEntity, OrderResponse.class);
Assertions.assertEquals(orderResponse.getStatusCode(), HttpStatus.BAD_REQUEST);
}
private HttpHeaders getRequestHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add("Authorization", "Basic " + getCredentials());
return httpHeaders;
}
private String getCredentials() {
return Base64.getEncoder().encodeToString(StringUtils.getBytesUtf8(String.format("%s:%s",
getUserName(),
getPassword())));
}
public static String getUserName() {
return userName;
}
public static String getPassword() {
return <PASSWORD>;
}
}
| 7faa31411f5ea07252cc4d518e636bbfd1f8a3a0 | [
"Markdown",
"Java",
"SQL"
] | 21 | Java | sushilparti/gildedroseexpands | aae977f8abd1eb507db275e29d897022d94fc8f9 | eb1c1e51c474b3512db267d89f3f6473daa25b29 |
refs/heads/master | <file_sep>//
// ViewController.swift
// TuyetDiceCasino
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var scoreCounter = 0
var scoreResetToZero = 0
//var maxScore = 100
@IBOutlet weak var leftDice: UIImageView!
@IBOutlet weak var rightDice: UIImageView!
@IBOutlet weak var scoreCounterLabel: UILabel!
@IBAction func startOver(_ sender: UIButton) {
scoreCounter = 0
scoreCounterLabel.text = String(scoreCounter)
}
@IBAction func rollButton(_ sender: UIButton) {
let dices = [#imageLiteral(resourceName: "dice1image"), #imageLiteral(resourceName: "dice2image"), #imageLiteral(resourceName: "dice3image"), #imageLiteral(resourceName: "dice4image"), #imageLiteral(resourceName: "dice5image"),#imageLiteral(resourceName: "dice6image")]
leftDice.image = dices[Int.random(in: 0...5)]
rightDice.image = dices[Int.random(in: 0...5)]
if leftDice.image == dices[4]{
scoreCounter += 5
//print("test")
scoreCounterLabel.text = String(scoreCounter)
}
if rightDice.image == dices[4]{
scoreCounter += 5
//print("test")
scoreCounterLabel.text = String(scoreCounter)
}
if checkWin(score: scoreCounter) == true {
//if won
scoreCounter = 0
}
}
func checkWin(score: Int) -> Bool{
if score >= 100 {
return true
}
return false
}
}
<file_sep># TuyetDiceCasino
| 78f456d2fb3f280fc23681e91dddc3fd0403e77f | [
"Swift",
"Markdown"
] | 2 | Swift | TuyetanhVu-zz/TuyetDiceCasino | b92cdb4d93a36b7332866d89af8e587fb3403046 | 651f4e56e38642286a8b93f4bd3f0cedbb03f74f |
refs/heads/master | <repo_name>CubatLin/An-implementation-of-Kmeans-Algorithm-by-using-R<file_sep>/kmeans_MIACadm.R
##Kmeans algorithm Source Code by MIACadm
#--------------------------
#sample data:iris
#--------------------------
kmeans_SC = function(data_input,Num_of_groups)
{
data =data_input
N=Num_of_groups
centers_unif = data[sample(N),]+replicate(N,rnorm(N,mean = 0,0.003))
#euclidean
for (i in 1:nrow(data)) {
for(j in 1:N){
if(i==1 & j==1){
euc_int=(sqrt(sum((data[i,]-centers_unif[j,])^2)))
}
else{
euc_int = c(euc_int,sqrt(sum((data[i,]-centers_unif[j,])^2)))
}
}
}
euc_int
fir = which(euc_int[1:N]==min(euc_int[1:N]))
for (x in seq(1+N,length(euc_int)-N+1,N) ){
fir = c(fir,which(euc_int[x:(x+2)]==min(euc_int[x:(x+2)])))
}
data_newGF = data
data_newGF$GroupFlag = fir
centers=colMeans(data_newGF[data_newGF$GroupFlag==1,])
for(i in 2:N){
centers = rbind(centers,colMeans(data_newGF[data_newGF$GroupFlag==i,]))
centers[is.nan(centers)]=0}
centers = data.frame(centers)
print(centers)
centers=centers[,-5]
#1.euclidean 2.flag 3.mean
cnt=0
while(cnt<20)
{ #1.
for (i in 1:nrow(data)) {
for(j in 1:N){
if(i==1 & j==1){
euc_int=(sqrt(sum((data[i,]-centers[j,])^2)))
}
else{
euc_int = c(euc_int,sqrt(sum((data[i,]-centers[j,])^2)))
}
}
}
euc_int
#2.
fir = which(euc_int[1:N]==min(euc_int[1:N]))
for (x in seq(1+N,length(euc_int)-N+1,N) ){
fir = c(fir,which(euc_int[x:(x+2)]==min(euc_int[x:(x+2)])))
}
data_newGF = data
data_newGF$GroupFlag = fir
#3.
centers_new=colMeans(data_newGF[data_newGF$GroupFlag==1,])
par(bg='#FCFCFC',cex=1)
plot(data_newGF$Petal.Length,data_newGF$Petal.Width,col="#81D8D0",
pch=20, xlim = c(0,10), ylim =c(0,3),
xlab = "X:Petal Length",ylab="Y:Petal Width") #feel free to change axis name ^^
title("Kmeans Algorithm")
col.vector=c("#FFA5D3","#EEC591","#CDAA7D","#EEE685","#9A32CD")
for(i in 2:N){
points(data_newGF[data_newGF$GroupFlag==i,]$Petal.Length,
data_newGF[data_newGF$GroupFlag==i,]$Petal.Width,
col=col.vector[i-1] , pch=20)
centers_new = rbind(centers_new,colMeans(data_newGF[data_newGF$GroupFlag==i,]))
centers_new[is.nan(centers_new)]=0}
centers_new = data.frame(centers_new)
print(centers_new)
centers_new=centers_new[,-5]
centers=centers_new
cnt=cnt+1
}
centers.final <<- centers
data_newGF.final <<- data_newGF
GroupStat.final<<- data.frame(table(data_newGF.final$GroupFlag))
colnames(GroupStat.final)[1:2]=c('Group','Numbers')
print(GroupStat.final)
}
data <- iris[, -5]
kmeans_SC(data,3)
<file_sep>/README.md
# An-implementation-of-Kmeans-Algorithm-by-using-R-
[R Code](https://github.com/CubatLin/An-implementation-of-Kmeans-Algorithm-by-R-/blob/master/kmeans_MIACadm.R)

| e5fbc631a8b9f54d3b75e3d3371d667352193566 | [
"Markdown",
"R"
] | 2 | R | CubatLin/An-implementation-of-Kmeans-Algorithm-by-using-R | 9f9534a322a864e425ced9f09d61016f9705859b | 6544b7a949eea733e7b62866524768421ed2e724 |
refs/heads/master | <file_sep>let allDonors = []
function fetchAllDonors() {
fetch('http://localhost:8080/donor/all-donors')
.then(res => res.json())
.then(data => {
if (data.status) {
console.log(data)
allDonors = data.donors
displayAllDonors(data.donors)
} else {
document.getElementById('err-message').innerText = 'No donors till now'
}
})
.catch(err => console.log(err))
}
function displayAllDonors(donors) {
let tableBody = document.getElementById('donor-table-body')
tableBody.innerHTML = ''
donors.forEach(donor => {
tableBody.innerHTML += `
<tr>
<td>${donor.firstName} ${donor.lastName}</td>
<td>${donor.bloodGroup.toUpperCase()}</td>
<td>${donor.contact}</td>
<td>
<a class="btn btn-danger text-white"}>View Details</a>
</td>
</tr>
`
})
}
document.getElementById('bloodtype').addEventListener('change', function(e) {
if (event.target.value === 'select') {
if (allDonors.length > 0) {
displayAllDonors(allDonors)
} else {
document.getElementById('err-message').innerText = 'No donors till now'
}
return
}
const filteredDonors = allDonors.filter(function(donor, index) {
return (
donor.bloodGroup.trim().toLowerCase() ===
e.target.value.trim().toLowerCase()
)
})
if (filteredDonors.length > 0) {
displayAllDonors(filteredDonors)
document.getElementById('err-message').innerText = ''
} else {
document.getElementById('donor-table-body').innerHTML = ''
document.getElementById('err-message').innerText = 'No donors till now'
}
})
<file_sep>// Initialize Firebase
var config = {
apiKey: '<KEY>',
authDomain: 'blood-bucket.firebaseapp.com',
databaseURL: 'https://blood-bucket.firebaseio.com',
projectId: 'blood-bucket',
storageBucket: 'blood-bucket.appspot.com',
messagingSenderId: '629147239690'
}
firebase.initializeApp(config)
const db = firebase.firestore()
const apiEndPoint = `http://localhost:8080/donor/register-donor`
db.settings({
timestampsInSnapshots: true
})
const donor = {
name: 'neha',
age: 20,
type: 'donor',
weight: 60,
bloogGroup: 'a+'
}
// const patient = {
// name: 'abc',
// age: 20,
// type: 'patient',
// bloogGroup: 'o+'
// }
// function patientRegistration(patientObject) {
// // firebase code here
// db.collection('users')
// .doc('AVidr3nHFsgDWxudc24C')
// .collection('patients')
// .add(patientObject)
// .then(docRef => {
// console.log('DOC added with the reference of: ', docRef)
// })
// .catch(err => console.log(err))
// }
function donorRegistration(donorObject) {
// firebase code here
db.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('donors')
.add(donorObject)
.then(docRef => {
console.log('DOC added with the reference of: ', docRef)
})
.catch(err => console.log(err))
}
db.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('donors')
.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
const data = change.doc.data()
console.log('added fired', data)
fetch(apiEndPoint, {
method: 'POST',
body: JSON.stringify({
name: data.name,
age: data.age,
bloogGroup: data.bloogGroup,
type: data.type,
weight: data.weight
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
}
})
})
// patientRegistration(patient)
donorRegistration(donor)
<file_sep>const db = require('../dbConnection')
function deletePreviouseDocumentsOfPatients(req, res, next) {
db.dropCollection('patients', function(error, result) {
if (error) {
console.log('There is an error in droping the collection!!!')
} else {
console.log('Patients Collection removed Successfully!')
next()
}
})
}
module.exports = deletePreviouseDocumentsOfPatients
<file_sep>let allPatients = []
function fetchAllPatients() {
fetch('http://localhost:8080/patient/all-patients')
.then(res => res.json())
.then(data => {
if (data.status) {
allPatients = data.patients
displayAllpatients(data.patients)
} else {
document.getElementById('err-message').innerText =
'No patients till now'
}
})
.catch(err => console.log(err))
}
function displayAllpatients(patietns) {
let tableBody = document.getElementById('patient-table-body')
tableBody.innerHTML = ''
patietns.forEach(patient => {
tableBody.innerHTML += `
<tr>
<td>${patient.name}</td>
<td>${patient.bloodGroup}</td>
<td>${patient.contact}</td>
<td>
<a class="btn btn-danger text-white"}>View Details</a>
</td>
</tr>
`
})
}
document.getElementById('bloodtype').addEventListener('change', function(e) {
if (event.target.value === 'select') {
if (allPatients.length > 0) {
displayAllpatients(allPatients)
} else {
document.getElementById('err-message').innerText = 'No donors till now'
}
return
}
const filteredPatients = allPatients.filter(function(patient, index) {
return (
patient.bloodGroup.trim().toLowerCase() ===
e.target.value.trim().toLowerCase()
)
})
if (filteredPatients.length > 0) {
displayAllpatients(filteredPatients)
document.getElementById('err-message').innerText = ''
} else {
document.getElementById('patient-table-body').innerHTML = ''
document.getElementById('err-message').innerText = 'No patient till now'
}
})
<file_sep>const mongoose = require('mongoose')
const Schema = mongoose.Schema
const patientSchema = new Schema({
name: String,
email: String,
contact: String,
age: Number,
bloodGroup: String,
desease: String,
city: String,
gender: String,
address: String
})
module.exports = new mongoose.model('Patient', patientSchema)
<file_sep>const router = require('express').Router()
const controller = require('./patient-controllers')
const deletePreviouseDocumentsOfPatients = require('../middlewares/patient _Middleware')
router.post('/register-patient', controller.registerPatient)
router.get(
'/all-patients',
deletePreviouseDocumentsOfPatients,
controller.getAllPatients
)
router.delete('/delete-patient/:id/:fb_id', controller.deletePatient)
module.exports = router
<file_sep>console.log('running register patient')
// Initialize Firebase
var config = {
apiKey: '<KEY>',
authDomain: 'blood-bucket.firebaseapp.com',
databaseURL: 'https://blood-bucket.firebaseio.com',
projectId: 'blood-bucket',
storageBucket: 'blood-bucket.appspot.com',
messagingSenderId: '629147239690'
}
firebase.initializeApp(config)
const db = firebase.firestore()
db.settings({
timestampsInSnapshots: true
})
document
.getElementById('patientForm')
.addEventListener('submit', registerPatient)
function registerPatient(e) {
e.preventDefault()
// elements gathering
let name = document.getElementById('name').value
let email = document.getElementById('email').value
let contact = document.getElementById('cellnum').value
let age = document.getElementById('age').value
let bloodGroup = document.getElementById('bloodtype').value
let desease = document.getElementById('disease').value
let city = document.getElementById('city').value
let address = document.getElementById('address').value
// getting the radio buttons
let maleFlag = document.getElementById('inlineRadio1').checked
let femaleFlag = document.getElementById('inlineRadio2').checked
let gender = !maleFlag ? 'male' : 'female'
const patient = {
name,
email,
contact,
age,
bloodGroup,
desease,
city,
gender,
address
}
patientRegistration(patient)
.then(docRef => {})
.catch(err => console.log(err))
}
function patientRegistration(patient) {
// firebase code here
return db
.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('patients')
.add(patient)
}
db.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('patients')
.onSnapshot(function(snapshot) {
snapshot.docChanges().forEach(function(change) {
if (change.type === 'added') {
fetch(`http://localhost:8080/patient/register-patient`, {
method: 'POST',
body: JSON.stringify({
...change.doc.data()
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(patient => console.log(patient))
.catch(err => console.log(err))
}
})
// }
// })
})
<file_sep>const router = require('express').Router()
const controller = require('./donor-controllers')
const deletePreviouseDocumentsOfDonors = require('../middlewares/donor_Middleware')
router.post('/register-donor', controller.registerDonor)
router.get(
'/all-donors',
deletePreviouseDocumentsOfDonors,
controller.getAllDonors
)
router.delete('/delte-donor/:mongo_id/:fb_id', controller.deleteDonor)
module.exports = router
<file_sep>const mongoose = require('mongoose')
// connecting to local database
mongoose.connect(
'mongodb://localhost/testDatabase',
{ useNewUrlParser: true }
)
const connection = mongoose.connection
connection.on('connected', function() {
console.log('connected to database')
})
<file_sep>const mongoose = require('mongoose')
const Schema = mongoose.Schema
const donorSchema = new Schema({
firstName: String,
lastName: String,
email: String,
gender: String,
city: String,
address: String,
postalCode: String,
age: Number,
bloodGroup: String,
contact: String
})
module.exports = new mongoose.model('Donor', donorSchema)
<file_sep>// ===== Event Listener ===== //
document.getElementById('adminForm').addEventListener('submit', admin)
// ===== Function ===== //
// Admin
function admin(event) {
event.preventDefault()
let email = document.getElementById('email').value
let macAddress = document.getElementById('macAddress').value
let patientAdmin = '<EMAIL>'
let donorAdmin = '<EMAIL>'
let masterAdmin = '<EMAIL>'
let patientAdminMacAddress = 'soha12345'
let donorAdminMacAddress = 'neha12345'
let masterAdminMacAddress = 'rehan12345'
if (email === masterAdmin && macAddress === masterAdminMacAddress) {
window.location.href = '../adminViews/masterView.html'
localStorage.setItem('MasterAdmin', masterAdminMacAddress)
} else if (email === patientAdmin && macAddress === patientAdminMacAddress) {
window.location.href = '../adminViews/patientsViews.html'
localStorage.setItem('PatientAdmin', patientAdminMacAddress)
} else if (email === donorAdmin && macAddress === donorAdminMacAddress) {
window.location.href = '../adminViews/donorViews.html'
localStorage.setItem('DonorAdmin', donorAdminMacAddress)
} else {
swal('Invalid email or mac address')
}
}
<file_sep>// Initialize Firebase
var config = {
apiKey: '<KEY>',
authDomain: 'blood-bucket.firebaseapp.com',
databaseURL: 'https://blood-bucket.firebaseio.com',
projectId: 'blood-bucket',
storageBucket: 'blood-bucket.appspot.com',
messagingSenderId: '629147239690'
}
firebase.initializeApp(config)
// signup
// firebase
// .auth()
// .createUserWithEmailAndPassword('<EMAIL>', '<PASSWORD>')
// .then(res => console.log(res))
// .catch(err => console.log(err))
// login
// firebase
// .auth()
// .signInWithEmailAndPassword('<EMAIL>', '<PASSWORD>')
// .then(res => console.log(res))
// .catch(err => console.log(err))
// auth status check
// firebase.auth().onAuthStateChanged(user => {
// if (user) {
// console.log('user loggin')
// } else {
// console.log('user logout')
// }
// })
// signout code
// firebase.auth().signOut()
// firestore work with collections
// const db = firebase.firestore()
// db.settings({
// timestampsInSnapshots: true
// })
// const donor = {
// name: 'rehan',
// age: 19,
// type: 'donor',
// bloogGroup: 'o+'
// }
// const patient = {
// name: 'abc',
// age: 20,
// type: 'patient',
// bloogGroup: 'o+'
// }
// function patientRegistration(patientObject) {
// // firebase code here
// db.collection('users')
// .doc('AVidr3nHFsgDWxudc24C')
// .collection('patients')
// .add(patientObject)
// .then(docRef => {
// console.log('DOC added with the reference of: ', docRef)
// })
// .catch(err => console.log(err))
// }
// function donorRegistration(donorObject) {
// // firebase code here
// db.collection('users')
// .doc('AVidr3nHFsgDWxudc24C')
// .collection('donors')
// .add(donorObject)
// .then(docRef => {
// console.log('DOC added with the reference of: ', docRef)
// })
// .catch(err => console.log(err))
// }
// patientRegistration(patient)
// donorRegistration(donor)
<file_sep>const Patient = require('./patient-model.js')
const firestore = require('../fbConfig')
function registerPatient(req, res) {
const newPatient = new Patient(req.body)
newPatient
.save()
.then(patient => {
res.send({
status: true,
...patient
})
})
.catch(err => {
res.send({
status: false,
err
})
})
}
function getAllPatients(req, res) {
let patientPromises = []
// fetching donors from firebase
firestore
.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('patients')
.get()
.then(querySnapshot => {
// creating a local array
querySnapshot.forEach(doc => {
// setting all documents in a promised chain array!
let newPatient = new Patient(doc.data())
patientPromises.push(newPatient.save())
})
Promise.all(patientPromises)
.then(flag => {
// finding patients locally..!!
if (flag) {
Patient.find({})
.then(patients =>
patients.length > 0
? res.send({
status: true,
totalPatient: patients.length,
patients
})
: res.send({
status: false,
message: 'no patients'
})
)
.catch(err => res.send({ status: false, err }))
}
})
.catch(err => res.send({ status: false, err }))
})
}
function deletePatient(req, res) {
const id = req.params.mongo_id
const fb_id = req.params.fb_id
firestore
.collection('users')
.doc('AVidr3nHFsgDWxudc24C')
.collection('patients')
.doc(fb_id)
.delete()
.then(() => {
Patient.findByIdAndDelete(id, { new: true })
.then(deletedPatient =>
res.send({
stauts: true,
deletedPatient
})
)
.catch(err =>
res.send({
status: false,
err
})
)
})
.catch(err =>
res.send({
status: false,
err
})
)
}
module.exports = {
registerPatient,
getAllPatients,
deletePatient
}
<file_sep>// Initialize Firebase
var config = {
apiKey: '<KEY>',
authDomain: 'blood-bucket.firebaseapp.com',
databaseURL: 'https://blood-bucket.firebaseio.com',
projectId: 'blood-bucket',
storageBucket: 'blood-bucket.appspot.com',
messagingSenderId: '629147239690'
};
var firebase = firebase.initializeApp(config);
// ===== Event Listeners ===== //
document.getElementById('signupForm').addEventListener('submit', signup);
// ===== Functions ===== //
// Signup
let auth = firebase.auth();
function signup(event) {
event.preventDefault();
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
auth
.createUserWithEmailAndPassword(email, password)
.then(data => localStorage.setItem('User', JSON.stringify(data.user)))
.catch(error => console.log(error));
}
auth.onAuthStateChanged(user => {
if (user) {
window.location.href = '../dashboard/dashboard.html';
} else {
console.log('Login first');
}
});
<file_sep>function fetchAllPatients() {
fetch('http://localhost:8080/patient/all-patients')
.then(res => res.json())
.then(data => {
if (data.status) {
console.log(data)
displayAllpatients(data.patients)
} else {
document.getElementById('err-message').innerText =
'No patients till now'
}
})
.catch(err => console.log(err))
}
function fetchAllDonors() {
fetch('http://localhost:8080/donor/all-donors')
.then(res => res.json())
.then(data => {
if (data.status) {
displayAllDonors(data.donors)
} else {
document.getElementById('err-message').innerText = 'No donors till now'
}
})
.catch(err => console.log(err))
}
function fetchData() {
fetchAllDonors()
fetchAllPatients()
}
function displayAllpatients(patietns) {
let tableBody = document.getElementById('patient-table-body')
tableBody.innerHTML = ''
patietns.forEach(patient => {
tableBody.innerHTML += `
<tr>
<td>${patient.name}</td>
<td>${patient.bloodGroup}</td>
<td>${patient.contact}</td>
<td>
<a class="btn btn-danger text-white"}>View Details</a>
</td>
</tr>
`
})
}
function displayAllDonors(donors) {
let tableBody = document.getElementById('donor-table-body')
tableBody.innerHTML = ''
donors.forEach(donor => {
tableBody.innerHTML += `
<tr>
<td>${donor.firstName} ${donor.lastName}</td>
<td>${donor.bloodGroup.toUpperCase()}</td>
<td>${donor.contact}</td>
<td>
<a class="btn btn-danger text-white"}>View Details</a>
</td>
</tr>
`
})
}
document
.getElementById('patient-list-btn')
.addEventListener('click', function() {
document.getElementById('patient-table-body').style.display = 'table'
document.getElementById('donor-table-body').style.display = 'none'
})
document.getElementById('donor-list-btn').addEventListener('click', function() {
document.getElementById('donor-table-body').style.display = 'table'
document.getElementById('patient-table-body').style.display = 'none'
})
<file_sep># Blood-Bucket
A blood bank application developed on the principles of distributed databases.
| 1c0da20f30b2353eff3fe3c4684fc0ff0acf086d | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | soha-moosa/Blood-Bucket | b498d301ba87a707574190eb73f49f9a4485fad5 | f25e6da87f07df2c83432087aa034a69f98a7fed |
refs/heads/master | <file_sep>module FlickrHelper
def user_photos(user_id, photo_count = 12)
FlickRaw.api_key = ENV['FLICKR_API_KEY']
FlickRaw.shared_secret = ENV['FLICKR_SECRET']
flickr.people.getPublicPhotos(:user_id => ENV['FLICKR_ID'])
end
def render_feed(user_id, photo_count = 12, columns = 2)
#begin
photos = user_photos(user_id, photo_count).to_a.in_groups_of(2)
render partial: 'flickr/feed', locals: {photos: photos}
#rescue Exception
# render 'flickr/unavailable'
#end
end
def build_url(farm, server, id, secret)
return "https://farm#{farm}.staticflickr.com/#{server}/#{id}_#{secret}_s.jpg"
end
end<file_sep>class StaticPagesController < ApplicationController
def home
@user_id = params[:user_id] unless params[:user_id].blank?
end
end
| 341cc232b7e087ee6f47a99a70ec63911088b029 | [
"Ruby"
] | 2 | Ruby | severnsc/flickr-sidebar | 8ecd375fe4bd189dd0b1732ef59a8e6703082de4 | 200ab0d9bb4f7026c6a1d2518ce3369f91934508 |
refs/heads/master | <file_sep># Basic_Perceptron
single perceptron
<file_sep>from perceptron import Perceptron
import numpy as np
training_inputs = []
training_inputs.append(np.array([1, 1]))
training_inputs.append(np.array([1, 0]))
training_inputs.append(np.array([0, 1]))
training_inputs.append(np.array([0, 0]))
training_outputs = np.array([1, 1, 1, 0])
perceptron = Perceptron(2)
perceptron.train(training_inputs, training_outputs)
'''
test
'''
inputs = np.array([1, 1])
print("1 or 1 = ",perceptron.predict(inputs))
inputs = np.array([0, 1])
print("0 or 1 = ",perceptron.predict(inputs))
inputs = np.array([1, 0])
print("1 or 0 = ",perceptron.predict(inputs))
inputs = np.array([0, 0])
print("0 or 0 = ",perceptron.predict(inputs)) <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 12:25:22 2019
@author: pierre
"""
from perceptron import Perceptron
import numpy as np
training_inputs = []
training_inputs.append(np.array([1, 1]))
training_inputs.append(np.array([1, 0]))
training_inputs.append(np.array([0, 1]))
training_inputs.append(np.array([0, 0]))
training_outputs = np.array([1, 0, 0, 0])
perceptron = Perceptron(2)
perceptron.train(training_inputs, training_outputs)
'''
test
'''
inputs = np.array([1, 1])
print("1 and 1 = ",perceptron.predict(inputs))
inputs = np.array([0, 1])
print("0 and 1 = ",perceptron.predict(inputs))
inputs = np.array([1, 0])
print("1 and 0 = ",perceptron.predict(inputs))
inputs = np.array([0, 0])
print("0 and 0 = ",perceptron.predict(inputs)) <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 11:46:57 2019
@author: pierre
"""
import numpy as np
class Perceptron(object):
def __init__(self, num_of_inputs, threshold=20, learn_rate=0.01):
self.threshold = threshold
self.learn_rate = learn_rate
self.weights = np.zeros(num_of_inputs)
self.bias = 0.0
#activation function
def predict(self, inputs):
sum = np.dot(inputs, self.weights)+self.bias
#print(self.weights[1:])
#print(self.bias)
#print()
if sum>0:
activation = 1
else:
activation = 0
return activation
def train(self, training_inputs, training_outputs):
for _ in range(self.threshold):
for inputs, outputs in zip(training_inputs, training_outputs):
prediction = self.predict(inputs)
print("inputs = ",inputs)
print("prediction = ",prediction)
print("outputs = ",outputs)
print("error = ",outputs-prediction)
print("---------------")
self.weights += self.learn_rate*(outputs-prediction)*inputs
self.bias += self.learn_rate*(outputs-prediction)
| 4ae409dcf65dbe791fbbdb510b9ad24119cfdc46 | [
"Markdown",
"Python"
] | 4 | Markdown | pierre0210/Basic_Perceptron | 879f4702159e486270364c3ffd0cd2553e027db5 | 950b4e24b1b2f43046d3267814c3e62589e1faf4 |
refs/heads/master | <repo_name>caiocsgomes/generator-dotnetcore-boilerplate<file_sep>/generators/app/index.js
const Generator = require('yeoman-generator');
var yosay = require('yosay');
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
// this.npmInstall("bower");
}
async prompting() {
this.log(yosay(
'Welcome to the .NET Core generator!'
));
this.answers = await this.prompt([
{
type: "input",
name: "projectName",
message: "What is your project name?",
default: this.appname // Default to current folder name
},
{
type: 'list',
name: 'projectType',
message: 'What type of project?',
choices: [
'webapi',
'mvc',
'web',
'console'
],
prefix: ''
}
])
}
dotnet() {
this.log('Creating a solution file...');
this.spawnCommandSync('dotnet',
[
'new',
'sln',
'--name',
this.answers.projectName
],
{
cwd: this.destinationRoot()
}
);
this.log(`Creating ${this.answers.projectType} project...`);
this.spawnCommandSync('dotnet',
[
'new',
this.answers.projectType,
'--name',
this.answers.projectName
],
{
cwd: this.destinationRoot()
}
);
this.log(`Creating model project...`);
this.spawnCommandSync('dotnet',
[
'new',
'classlib',
'--name',
`${this.answers.projectName}.Model`
],
{
cwd: this.destinationRoot()
}
);
}
}; | a38b885e3fac2553626214115426cb7c26a06597 | [
"JavaScript"
] | 1 | JavaScript | caiocsgomes/generator-dotnetcore-boilerplate | 1ce553fdead56c0e1cd26c5fa46c9aed12134efa | fddf7fce6d235d4077dff341f52932371d83f9ce |
refs/heads/master | <repo_name>SurgeTransient/MudroomNode<file_sep>/MudroomMotionSensor.ino
/*
*******************************
*
* REVISION HISTORY
* Version 1.0
*
* DESCRIPTION
* Motion Sensor example using HC-SR501. Based on the following MySensors example
* http://www.mysensors.org/build/motion
*
*/
// Enable debug prints
#define MY_DEBUG
#define MY_NODE_ID 4
#define MY_RADIO_NRF24
#include <MySensors.h>
#define DIGIAL_INPUT_DOOR_SENSOR 2
#define DIGITAL_INPUT_MOTION_SENSOR 3
#define CHILD_ID_MOTION_SENSOR 1
#define CHILD_ID_DOOR_SENSOR 2
// Initialize motion message
MyMessage motionSensor(CHILD_ID_MOTION_SENSOR, V_TRIPPED);
MyMessage doorSensor(CHILD_ID_DOOR_SENSOR, V_TRIPPED);
void setup()
{
pinMode(DIGITAL_INPUT_MOTION_SENSOR, INPUT_PULLUP);
pinMode(DIGIAL_INPUT_DOOR_SENSOR, INPUT_PULLUP);
}
void presentation()
{
// Send the sketch version information to the gateway and Controller
sendSketchInfo("Mudroom Motion and Door Node", "1.0");
// Register all sensors to gw (they will be created as child devices)
present(CHILD_ID_MOTION_SENSOR, S_MOTION);
present(CHILD_ID_DOOR_SENSOR, S_DOOR);
}
void loop()
{
//Read both sensor's states
bool motionSensorState = digitalRead(DIGITAL_INPUT_MOTION_SENSOR) == LOW;
bool doorSensorState = digitalRead(DIGIAL_INPUT_DOOR_SENSOR) == LOW;
Serial.println("Motion Sensor State");
Serial.println(motionSensorState);
send(motionSensor.set(motionSensorState?"1":"0"));
Serial.println("Door Sensor State");
Serial.println(doorSensorState);
send(doorSensor.set(doorSensorState?"1":"0"));
// Sleep until interrupt comes in on door or motion sensor
sleep(digitalPinToInterrupt(DIGITAL_INPUT_MOTION_SENSOR), CHANGE, digitalPinToInterrupt(DIGIAL_INPUT_DOOR_SENSOR), CHANGE,0);
}
| 33e82b2b4d573496ff57f7dfd42b0a76979d86f0 | [
"C++"
] | 1 | C++ | SurgeTransient/MudroomNode | 91d806c02ff03fe618d90de68eb0f2b5142ee434 | 548709097412e8077cace5e6f5b6ac7fac95adc3 |
refs/heads/master | <repo_name>briantical/telesim<file_sep>/src/main/java/com/telesim/telesim/TelesimApplication.java
package com.telesim.telesim;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TelesimApplication {
public static void main(String[] args) {
SpringApplication.run(TelesimApplication.class, args);
}
}
<file_sep>/settings.gradle
rootProject.name = 'telesim'
<file_sep>/build.gradle
plugins {
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id "io.freefair.lombok" version "5.1.0"
id 'java'
}
group = 'com.telesim'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
targetCompatibility = '11'
repositories {
mavenCentral()
maven {
url "http://dl.bintray.com/africastalking/java"
}
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
implementation 'com.africastalking:core:3.4.2'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.statemachine:spring-statemachine-core:2.2.0.RELEASE'
implementation 'io.freefair.gradle:lombok-plugin:3.8.4'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'org.postgresql:postgresql'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
apply plugin: "io.freefair.lombok"
<file_sep>/src/main/java/com/telesim/telesim/utils/ReadVars.java
package com.telesim.telesim.utils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
public class ReadVars {
public String username;
public String apiKey;
public void setVariables(){
JSONParser parser = new JSONParser();
try {
Object object = parser.parse(new FileReader("./../Config.json"));
JSONObject jsonObject = (JSONObject) object;
this.username = (String)jsonObject.get("username");
this.apiKey = (String)jsonObject.get("apiKey");
}catch (Exception e){
}
}
public String getUsername(){
return this.username;
}
public String getApiKey(){
return this.apiKey;
}
}
<file_sep>/src/main/java/com/telesim/telesim/models/USSDRequest.java
package com.telesim.telesim.models;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class USSDRequest {
@Id
@GeneratedValue
private Long id;
private String text;
private String sessionId;
private String phoneNumber;
private String networkCode;
private String serviceCode;
@Enumerated(EnumType.STRING)
private USSDStates ussdstate;
}
<file_sep>/src/main/java/com/telesim/telesim/services/USSDRequestService.java
package com.telesim.telesim.services;
import com.telesim.telesim.models.USSDEvents;
import com.telesim.telesim.models.USSDRequest;
import com.telesim.telesim.models.USSDStates;
import org.springframework.statemachine.StateMachine;
public interface USSDRequestService {
USSDRequest newUSSDRequest(USSDRequest ussdRequest);
StateMachine<USSDStates, USSDEvents> authorize(String sessionId);
StateMachine<USSDStates, USSDEvents> cancel(String sessionId);
StateMachine<USSDStates, USSDEvents> complete(String sessionId);
StateMachine<USSDStates, USSDEvents> process(String sessionId);
}
<file_sep>/src/main/java/com/telesim/telesim/services/USSDStateChangeListener.java
package com.telesim.telesim.services;
import com.telesim.telesim.models.USSDEvents;
import com.telesim.telesim.models.USSDRequest;
import com.telesim.telesim.models.USSDStates;
import com.telesim.telesim.repository.USSDRequestRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.support.StateMachineInterceptorAdapter;
import org.springframework.statemachine.transition.Transition;
import org.springframework.stereotype.Component;
import java.util.Optional;
@RequiredArgsConstructor
@Component
public class USSDStateChangeListener extends StateMachineInterceptorAdapter<USSDStates, USSDEvents> {
private final USSDRequestRepository ussdRequestRepository;
@Override
public void preStateChange(State<USSDStates, USSDEvents> state, Message<USSDEvents> message, Transition<USSDStates, USSDEvents> transition, StateMachine<USSDStates, USSDEvents> stateMachine) {
Optional.ofNullable(message).ifPresent(msg -> {
Optional.ofNullable(String.class.cast(msg.getHeaders().getOrDefault(USSDRequestServiceImpl.SESSIONID_HEADER, "")))
.ifPresent(sessionId -> {
USSDRequest ussdRequest = ussdRequestRepository.findBySessionId(sessionId).get(0);
ussdRequest.setUssdstate(state.getId());
ussdRequestRepository.save(ussdRequest);
});
});
}
}
<file_sep>/src/main/java/com/telesim/telesim/configuration/guards/USSDIdGuard.java
package com.telesim.telesim.configuration.guards;
import com.telesim.telesim.models.USSDEvents;
import com.telesim.telesim.models.USSDStates;
import com.telesim.telesim.services.USSDRequestServiceImpl;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.guard.Guard;
public class USSDIdGuard implements Guard<USSDStates, USSDEvents> {
@Override
public boolean evaluate(StateContext<USSDStates, USSDEvents> context) {
return context.getMessageHeader(USSDRequestServiceImpl.SESSIONID_HEADER) != null;
}
}
| 20c1bec3f21296e5292e8b8b75d69a5019327258 | [
"Java",
"Gradle"
] | 8 | Java | briantical/telesim | 8f6a2ed1c36fe11c3372c197578152f9557994e8 | 7014c21755808421584c6ac88cb68721b980e36f |
refs/heads/master | <repo_name>akhilarjun/personal<file_sep>/ishak/assets/js/ishak.js
let zen = {};
zen.imgs = [];
let start = 0;
let pagination = 10;
let firstload = true;
const zenFor = {
get elem() {
return document.querySelector("zen-for");
},
};
zenFor.elem.setAttribute("list", "imgs");
const paintMosaic = () => {
const gridWrapper = document.querySelector(".gallery zen-for");
if (gridWrapper) {
console.info("Painting Mosaic for you!");
const rowHeight = parseInt(
window.getComputedStyle(gridWrapper).getPropertyValue("grid-auto-rows")
);
const gapHeight = parseInt(
window.getComputedStyle(gridWrapper).getPropertyValue("gap")
);
document.querySelectorAll(".imgholder").forEach((item) => {
const rowSpan = Math.ceil(
(item.querySelector("img").getBoundingClientRect().height + gapHeight) /
(rowHeight + gapHeight)
);
item.style.gridRowEnd = "span " + rowSpan;
});
document.querySelector(".loader").classList.add("hide");
setTimeout(() => {
document.querySelector(".banner").classList.add("start");
}, 1500);
}
};
const getImgs = () => {
!firstload && (start = start + pagination);
if (start < 70) {
document.querySelector(".loader").classList.remove("hide");
for (let i = start; i < start + pagination && i < 62; i++) {
zen.imgs.push({
url: `./assets/img/lowres/img${i}.webp`,
});
}
zenFor.elem.renderContent().then(() => {
firstload = !firstload;
setTimeout(() => {
paintMosaic();
}, 200);
});
}
};
// getImgs();
// document.querySelector("body").onscroll = (e) => {
// const gridWrapper = document.querySelector(".gallery zen-for");
// console.log(
// gridWrapper.scrollHeight,
// document.querySelector("body").scrollTop,
// gridWrapper.getBoundingClientRect().height
// );
// if (
// gridWrapper.scrollTop + gridWrapper.clientHeight >=
// gridWrapper.scrollHeight
// ) {
// console.log("reached end");
// }
// };
ScrollOut({
onShown: () => {
// console.log("came");
getImgs();
},
});
<file_sep>/scripts/compress-imgs.js
const compress_imgs = require("compress-images");
const imagemin = require("imagemin");
const { resolve } = require("path");
const imageminWebp = require("imagemin-webp");
const INPUT_PATH = resolve(process.cwd(), "ishak/assets/img/*.jpg").replace(
/\\/g,
"/"
);
const OUTPUT_PATH =
resolve(process.cwd(), "ishak/assets/img/lowres/").replace(/\\/g, "/") + "/";
console.log(INPUT_PATH);
console.log(OUTPUT_PATH);
module.exports.op = OUTPUT_PATH;
module.exports.ip = INPUT_PATH;
module.exports.compress = () => {
compress_imgs(
INPUT_PATH,
OUTPUT_PATH,
{
compress_force: false,
statistic: true,
autoupdate: false,
},
false,
{
jpg: {
engine: "webp",
command: ["-q", 10],
},
},
{ png: { engine: false, command: false } },
{ svg: { engine: false, command: false } },
{ gif: { engine: false, command: false } },
(err, completed, stat) => {
console.log("----------------------");
console.log(err);
console.log(completed);
console.log(stat);
console.log("----------------------");
}
);
};
module.exports.minify = () => {
return imagemin([INPUT_PATH], {
destination: OUTPUT_PATH,
plugins: [imageminWebp({ quality: 10 })],
});
};
<file_sep>/scripts/setup-ishak.js
const rimraf = require("rimraf");
const imageCompressor = require("./compress-imgs");
const { readdirSync, rename, renameSync } = require("fs");
const { resolve, join } = require("path");
const { lstatSync } = require("fs");
const imgPath = resolve(process.cwd(), "ishak/assets/img/");
const chalk = require("chalk");
const imgs = readdirSync(imgPath);
console.log(chalk.yellow("Renaming..."));
imgs.forEach((img, index) => {
const stat = lstatSync(join(imgPath, img));
if (!stat.isDirectory()) {
renameSync(imgPath + `/${img}`, imgPath + `/img${index}.jpg`);
}
});
console.log(chalk.green("Renaming Complete!"));
rimraf("ishak/assets/img/lowres/", async () => {
console.log(chalk.red("Low res folder cleared and deleted!"));
//imageCompressor.compress();
const changedFiles = await imageCompressor.minify();
console.log(chalk.greenBright("Images optimised"));
console.log(changedFiles);
});
| 64db5538ed65032a0a012135615e5037205bcd7c | [
"JavaScript"
] | 3 | JavaScript | akhilarjun/personal | eea0c4d3f361cd60e0d938ffe5bb80420dcfe755 | 14e21efe32c05f000cc3a6a3e0b981717ab2682a |
refs/heads/master | <file_sep>#!/bin/bash
source sicat.conf
sa-clean-jboss.sh;
DEPLOY_PATH=${JBOSS_HOME}/server/sgap/deploy/sgap-sa/SGAP.war
mkdir -p ${DEPLOY_PATH}
rm -rf ${DEPLOY_PATH}/*;
cd ${DEPLOY_PATH};
mv ${REPO_PATH}/legado/SGAP/target/*.war .;
jar xvf *.war; rm -f ${DEPLOY_PATH}/*.war;
<file_sep>#!/bin/bash
source sicat.conf
cd ${REPO_PATH}/componentes;
git stash; git pull; git stash pop;
cd ${REPO_PATH}/legado;
git reset pom.xml; git checkout pom.xml;
git stash; git pull; git stash pop;
<file_sep>#!/bin/bash
source cfe.conf;
cfe-clean.sh;
cfe-clean-jboss.sh;<file_sep>#!/bin/bash
source sicat.conf;
cd ${REPO_PATH}/componentes;
mvn -DskipTests eclipse:clean eclipse:eclipse;
cd ${REPO_PATH}/legado;
mvn -DskipTests eclipse:clean eclipse:eclipse;<file_sep>#!/bin/bash
source sicat.conf
cd ${REPO_PATH}/legado/SGAP;
mvn install -T 2C -DskipTests;<file_sep>#!/bin/bash
source sicat.conf;
cd ${REPO_PATH}/componentes;
mvn clean -T 2C -DskipTests eclipse:clean eclipse:eclipse;
<file_sep>#!/bin/bash
source sicat.conf;
rm -rf ${JBOSS_HOME}/server/sgap/data
rm -rf ${JBOSS_HOME}/server/sgap/log
rm -rf ${JBOSS_HOME}/server/sgap/tmp
rm -rf ${JBOSS_HOME}/server/sgap/work
rm -rf ${JBOSS_HOME}/server/sgap/deploy/sgap-sa/*.war
<file_sep>#!/bin/bash
source cfe.conf;
cd ${REPO_PATH}/cfe;
mvn clean -T 2C -DskipTests;
<file_sep>#!/bin/bash
source sicat.conf
cd ${REPO_PATH}/legado/SGAP;
mvn install -DskipTests;<file_sep>#!/bin/bash
source sicat.conf
cd ${REPO_PATH}/componentes;
mvn install -T 2C -DskipTests;
<file_sep>#!/bin/bash
source sicat.conf;
sa-install-componentes2.sh;
sa-install-legado2.sh;
<file_sep>#!/bin/bash
source sicat.conf
cd ${REPO_PATH}/legado;
#export JAVA_HOME=$JAVA_HOME
mvn install -DskipTests;
<file_sep>#!/bin/bash
source cfe.conf
cfe-clean-jboss.sh;
DEPLOY_PATH=${JBOSS_HOME}/standalone/deployments
mkdir -p ${DEPLOY_PATH}
rm -rf ${DEPLOY_PATH}/*;
cd ${DEPLOY_PATH};
mv ${REPO_PATH}/cfe/cfesg/target/*.war .;
jar xvf *.war; rm -f ${DEPLOY_PATH}/*.war;
<file_sep>#!/bin/bash
source sicat.conf;
sa-clean-componentes.sh;
sa-clean-legado.sh;
sa-clean-jboss.sh;
<file_sep>#!/bin/bash
source sicat.conf;
sa-install-componentes.sh;
sa-install-legado.sh;
<file_sep>#!/bin/bash
source cfe.conf;
cd ${JBOSS_HOME}/standalone;
rm -rf data;
rm -rf tmp;
rm -rf log;
rm -rf deployments/*;<file_sep>#!/bin/bash
source cfe.conf;
cd ${REPO_PATH}/cfe;
git checkout pom.xml;
git stash;
git pull;
git stash pop;<file_sep>#!/bin/bash
source cfe.conf;
cd ${REPO_PATH}/cfe;
mvn package -DskipTests;<file_sep>#!/bin/bash
source sicat.conf;
cd ${REPO_PATH}/legado;
mvn clean -T 2C -DskipTests eclipse:clean eclipse:eclipse; | f73cf84ffffb5a26a3da99dcd841d340afd2192c | [
"Shell"
] | 19 | Shell | dmonti/dotfiles | ce60c0fad449478aa477fba528fc94e136c54496 | f217031535b14908bf7f5f9750933a37ac017ae8 |
refs/heads/master | <file_sep>package com.myob.payslip.models;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TaxRatePropertiesTest {
@Autowired
private TaxRateProperties taxRateProperties;
@Test
public void getRates() throws Exception {
List<TaxRate> taxRateList = taxRateProperties.getRates();
Assert.assertEquals(taxRateList.size(), 5);
}
}
<file_sep>MYOB code test
======
This is a simple spring boot app to calculate employee monthly payslip. Currently it only support CSV input and output.
##Prerequirement
1. JAVA 8
2. Gradle 3.5
3. Maven
##Build
Windows:
`gradlew.bat build`
Linux/Mac:
`./gradlew build`
## Run
1. Simply run `./gradlew bootRun`
4. By default it will pickup csv here `src/main/resource/input.csv` and write output CSV into the folder where you run this app.
## Test
1. Simply run `./gradlew test`
2. To check test coverage, run `./gradlew test jacocoTestReport`
##Integration test
1. `./gradlew clean build -x integrationTest`
##Configuration
1. Tax rate and input CSV file is configurable here: `src/main/resource/application.yml
2. You can specify your input csv and out put csv by using `./gradlew bootRun -DinputCSVFile=/youroutputcsvfilepath -DoutputCSVFile=/youroutputcsvfilepath`
##Important information!
To make it simple, currently only support payslip for one calendar month, which mean, will have the same output regardless payment period. Sorry for being lazy here :)
<file_sep>rootProject.name = 'employee-monthly-payslip'
<file_sep>package com.myob.payslip.util;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.myob.payslip.models.Payslip;
public class CSVWriter {
private static final Logger LOGGER = LoggerFactory.getLogger(CSVReader.class);
public static void writeCsvFile(File file, List<Payslip> payslips) {
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.DEFAULT;
try {
fileWriter = new FileWriter(file);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
//Write a new student object list to the CSV file
for (Payslip payslip : payslips) {
List csvDataRecord = new ArrayList();
csvDataRecord.add(payslip.getEmployee().getName());
csvDataRecord.add(payslip.getEmployee().getPaymentPeriod());
csvDataRecord.add(payslip.getGrossIncome());
csvDataRecord.add(payslip.getIncomeTax());
csvDataRecord.add(payslip.getNetIncome());
csvDataRecord.add(payslip.getSuperannuation());
csvFilePrinter.printRecord(csvDataRecord);
}
LOGGER.info("CSV file generated here ", file.getAbsolutePath());
} catch (Exception e) {
throw new RuntimeException("Error in CsvFileWriter!" + e);
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (Exception e) {
LOGGER.error("Error while flushing/closing fileWriter/csvPrinter!" + e);
}
}
}
}
<file_sep>package com.myob.payslip.service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.myob.payslip.models.TaxRateProperties;
@Component
public class TaxCalculator {
@Autowired
private TaxRateProperties taxRateProperties;
public BigDecimal calculateGrossIncome(BigDecimal annualSalary) {
return annualSalary.divide(new BigDecimal(12), 2, BigDecimal.ROUND_HALF_UP)
.setScale(0, BigDecimal.ROUND_HALF_UP);
}
public BigDecimal calculateIncomeTax(BigDecimal annualSalary) {
List<BigDecimal> taxSteps = new ArrayList();
taxRateProperties.getRates().stream().forEach(taxRate -> {
if (taxRate.matchingRate(annualSalary.intValue())) {
BigDecimal taxableIncome = annualSalary
.subtract(new BigDecimal(taxRate.getTaxableIncomeStart()));
if (annualSalary.intValue() > taxRate.getTaxableIncomeEnd()
&& taxRate.getTaxableIncomeEnd() != -1) {
taxableIncome = new BigDecimal(
taxRate.getTaxableIncomeEnd() - taxRate.getTaxableIncomeStart());
}
taxSteps.add(taxableIncome.multiply(new BigDecimal(taxRate.getRate())));
}
});
BigDecimal totalIncome = taxSteps.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
return totalIncome.divide(new BigDecimal(12), 2, BigDecimal.ROUND_HALF_UP)
.setScale(0, BigDecimal.ROUND_HALF_UP);
}
public BigDecimal calculateNetIncome(BigDecimal annualSalary) {
return calculateGrossIncome(annualSalary).subtract(calculateIncomeTax(annualSalary))
.setScale(0, BigDecimal.ROUND_HALF_UP);
}
public BigDecimal calculateSuper(BigDecimal annualSalary, BigDecimal superRate) {
return calculateGrossIncome(annualSalary).multiply(superRate)
.setScale(0, BigDecimal.ROUND_HALF_UP);
}
}
<file_sep>package com.myob.payslip.builder;
import java.math.BigDecimal;
import com.myob.payslip.models.Payslip;
public class PayslipBuilder {
public static Payslip build() {
Payslip payslip = new Payslip();
payslip.setEmployee(EmployeeBuilder.build());
payslip.setGrossIncome(new BigDecimal(5004));
payslip.setIncomeTax(new BigDecimal(922));
payslip.setSuperannuation(new BigDecimal(111));
return payslip;
}
}
<file_sep>package com.myob.payslip.models;
import java.math.BigDecimal;
import java.time.LocalDate;
public class Employee {
private String firstName;
private String lastName;
private BigDecimal aunualSalary;
private BigDecimal superRate;
private LocalDate paymentStartDate;
private LocalDate paymentEndDate;
private String paymentPeriod;
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 BigDecimal getAunualSalary() {
return aunualSalary;
}
public void setAunualSalary(BigDecimal aunualSalary) {
this.aunualSalary = aunualSalary;
}
public BigDecimal getSuperRate() {
return superRate;
}
public void setSuperRate(BigDecimal superRate) {
this.superRate = superRate;
}
public LocalDate getPaymentEndDate() {
return paymentEndDate;
}
public void setPaymentEndDate(LocalDate paymentEndDate) {
this.paymentEndDate = paymentEndDate;
}
public LocalDate getPaymentStartDate() {
return paymentStartDate;
}
public void setPaymentStartDate(LocalDate paymentStartDate) {
this.paymentStartDate = paymentStartDate;
}
public String getName(){
return this.firstName + " "+this.lastName;
}
public String getPaymentPeriod() {
return paymentPeriod;
}
public void setPaymentPeriod(String paymentPeriod) {
this.paymentPeriod = paymentPeriod;
}
}
<file_sep>package com.myob.payslip.convertor;
import java.io.BufferedReader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.List;
import java.util.StringJoiner;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import com.myob.payslip.models.Employee;
public class CsvRecordToEmployeeConvertorTest {
private CsvRecordToEmployeeConvertor subject;
private CSVRecord csvRecord;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
subject = new CsvRecordToEmployeeConvertor();
}
@Test
public void testConvert() throws Exception {
String firstName = "David";
String lastName = "Rudd";
String anuualSalary = "60000";
String superRate = "9%";
String paymentPeriod = "01 March\t– 31 March";
StringJoiner joiner = new StringJoiner(",");
joiner.add(firstName).add(lastName).add(anuualSalary).add(superRate).add(paymentPeriod);
String csvLine = joiner.toString();
CSVFormat csvFormat = CSVFormat.DEFAULT;
CSVParser csvParser = new CSVParser(new BufferedReader(new StringReader(csvLine)), csvFormat);
List<CSVRecord> csvRecordList = csvParser.getRecords();
csvRecord = csvRecordList.get(0);
Employee employee = subject.convert(csvRecord);
Assert.assertEquals(employee.getFirstName(), firstName);
Assert.assertEquals(employee.getLastName(), lastName);
Assert.assertEquals(employee.getAunualSalary(), new BigDecimal(anuualSalary));
Assert.assertEquals(employee.getSuperRate(), new BigDecimal("0.09"));
Assert.assertEquals(employee.getPaymentStartDate().getDayOfMonth(), 1);
Assert.assertEquals(employee.getPaymentStartDate().getMonthValue(), 3);
Assert.assertEquals(employee.getPaymentEndDate().getDayOfMonth(), 31);
Assert.assertEquals(employee.getPaymentEndDate().getMonthValue(), 3);
}
@Test(expected = RuntimeException.class)
public void testConvertException() throws Exception {
String firstName = "David";
StringJoiner joiner = new StringJoiner(",");
joiner.add(firstName);
String csvLine = joiner.toString();
CSVFormat csvFormat = CSVFormat.DEFAULT;
CSVParser csvParser = new CSVParser(new BufferedReader(new StringReader(csvLine)), csvFormat);
List<CSVRecord> csvRecordList = csvParser.getRecords();
csvRecord = csvRecordList.get(0);
subject.convert(csvRecord);
}
}
<file_sep>package com.myob.payslip.service;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.myob.payslip.convertor.CsvRecordToEmployeeConvertor;
import com.myob.payslip.convertor.EmployeeToPayslipConvertor;
import com.myob.payslip.models.Employee;
import com.myob.payslip.models.Payslip;
import com.myob.payslip.util.CSVReader;
import com.myob.payslip.util.CSVWriter;
@Service
public class PayslipService {
@Value("${inputCSVFile}")
private String inputCSVFile;
@Value("${outputCSVFile}")
private String outputCSVFile;
@Autowired
private CsvRecordToEmployeeConvertor csvRecordToEmployeeConvertor;
@Autowired
private EmployeeToPayslipConvertor employeeToPayslipConvertor;
public void generatePayslips() {
List<Employee> employees = getEmployees();
List<Payslip> payslips = buildPayslips(employees);
writePayslipsCSV(payslips);
}
private List<Employee> getEmployees() {
List<Employee> employees = new ArrayList();
List<CSVRecord> csvRecords = CSVReader.readCsvRecord(getInputCSVFile());
if (!CollectionUtils.isEmpty(csvRecords)) {
employees = getEmployeessFromCsvRecords(csvRecords);
}
return employees;
}
private File getInputCSVFile() {
File csvFile;
URL fileURL = getClass().getResource(inputCSVFile);
if (fileURL == null) {
csvFile = new File(inputCSVFile);
} else {
csvFile = new File(fileURL.getFile());
}
return csvFile;
}
private File getOutCSVFile() {
File csvFile = new File(outputCSVFile);
return csvFile;
}
private void writePayslipsCSV(List<Payslip> payslips) {
CSVWriter.writeCsvFile(getOutCSVFile(), payslips);
}
private List<Payslip> buildPayslips(List<Employee> employees) {
return employees.stream().map(employee -> employeeToPayslipConvertor.convert(employee))
.collect(Collectors.toList());
}
private List<Employee> getEmployeessFromCsvRecords(List<CSVRecord> csvRecords) {
return csvRecords.stream()
.map(csvRecord -> csvRecordToEmployeeConvertor.convert(csvRecord))
.collect(Collectors.toList());
}
}
<file_sep>package com.myob.payslip.convertor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.myob.payslip.models.Employee;
@Component
public class CsvRecordToEmployeeConvertor implements Converter<CSVRecord, Employee> {
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy");
// private static final Logger LOGGER =
// LoggerFactory.getLogger(CsvRecordToEmployeeConvertor.class);
@Override
public Employee convert(CSVRecord csvRecord) {
Employee employee = new Employee();
try {
employee.setFirstName(csvRecord.get(0));
employee.setLastName(csvRecord.get(1));
employee.setAunualSalary(new BigDecimal(csvRecord.get(2)));
employee.setSuperRate(getSuperRateFromSuperRatePercentage(csvRecord.get(3)));
employee.setPaymentPeriod(csvRecord.get(4));
setEmployeePaymentStartDateAndPaymentEndDate(csvRecord.get(4), employee);
if (employee.getPaymentStartDate().getDayOfMonth() != 1) {
}
} catch (Exception e) {
throw new RuntimeException("can't parse CSV record " + csvRecord.toString() + " to employee.",
e);
}
return employee;
}
private BigDecimal getSuperRateFromSuperRatePercentage(String superRatePercentage) {
return new BigDecimal(superRatePercentage.trim().replace("%", ""))
.divide(BigDecimal.valueOf(100));
}
private void setEmployeePaymentStartDateAndPaymentEndDate(
String paymentStartDateAndPaymentEndDate, Employee employee) {
String[] startEndDateArr = paymentStartDateAndPaymentEndDate.split("–");
// append default year to date to parse date
String startDate = startEndDateArr[0].trim() + " " + LocalDate.now().getYear();
String endDate = startEndDateArr[1].trim() + " " + LocalDate.now().getYear();
employee.setPaymentStartDate(LocalDate.parse(startDate, formatter));
employee.setPaymentEndDate(LocalDate.parse(endDate, formatter));
}
}
<file_sep>package com.myob.payslip.builder;
import java.math.BigDecimal;
import com.myob.payslip.models.Employee;
public class EmployeeBuilder {
public static Employee build() {
String firstName = "David";
String lastName = "Rudd";
String anuualSalary = "60000";
String paymentPeriod = "01 March\t– 31 March";
Employee employee = new Employee();
employee.setLastName(lastName);
employee.setFirstName(firstName);
employee.setPaymentPeriod(paymentPeriod);
employee.setAunualSalary(new BigDecimal(anuualSalary));
return employee;
}
}
<file_sep>package com.myob.payslip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.myob.payslip.service.PayslipService;
@SpringBootApplication
public class PayslipApplication implements CommandLineRunner {
@Autowired
private PayslipService payslipService;
@Override
public void run(String... args) {
payslipService.generatePayslips();
}
public static void main(String[] args) {
SpringApplication.run(PayslipApplication.class, args);
}
}
<file_sep>package com.myob.payslip.models;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "taxrate")
public class TaxRateProperties {
private List<TaxRate> rates = new ArrayList<>();
public List<TaxRate> getRates() {
return rates;
}
public void setRates(List<TaxRate> rates) {
this.rates = rates;
}
}
<file_sep>package com.myob.payslip.service;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TaxCalculatorTest {
private BigDecimal annualSalary = new BigDecimal(120000);
@Autowired
private TaxCalculator taxCalculator;
@Before
public void setUp() throws Exception {
}
@Test
public void calculateGrossIncome() throws Exception {
BigDecimal grossIncome = taxCalculator.calculateGrossIncome(annualSalary);
Assert.assertEquals(grossIncome, new BigDecimal(10000));
}
@Test
public void calculateIncomeTax() throws Exception {
BigDecimal incomeTax = taxCalculator.calculateIncomeTax(annualSalary);
Assert.assertEquals(incomeTax, new BigDecimal(2696));
}
@Test
public void calculateNetIncome() throws Exception {
BigDecimal netIncome = taxCalculator.calculateNetIncome(annualSalary);
Assert.assertEquals(netIncome, new BigDecimal(7304));
}
@Test
public void calculateSuper() throws Exception {
BigDecimal superannuation = taxCalculator.calculateSuper(annualSalary, new BigDecimal(0.1));
Assert.assertEquals(superannuation, new BigDecimal(1000));
}
}
<file_sep>package com.myob.payslip.service;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.util.ReflectionTestUtils;
import com.myob.payslip.builder.EmployeeBuilder;
import com.myob.payslip.builder.PayslipBuilder;
import com.myob.payslip.convertor.CsvRecordToEmployeeConvertor;
import com.myob.payslip.convertor.EmployeeToPayslipConvertor;
public class PayslipServiceTest {
@InjectMocks
private PayslipService subject;
private String inputCSVFile = "/testInput.csv";
private String outputCSVFile = "out.csv";
@Mock
private CsvRecordToEmployeeConvertor csvRecordToEmployeeConvertor;
@Mock
private EmployeeToPayslipConvertor employeeToPayslipConvertor;
@Before
public void setUp() throws Exception {
subject = new PayslipService();
MockitoAnnotations.initMocks(this);
}
@Test
public void testGeneratePayslips() throws Exception {
ReflectionTestUtils.setField(subject, "inputCSVFile", inputCSVFile);
ReflectionTestUtils.setField(subject, "outputCSVFile", outputCSVFile);
Mockito.when(csvRecordToEmployeeConvertor.convert(Mockito.any())).thenReturn(EmployeeBuilder.build());
Mockito.when(employeeToPayslipConvertor.convert(Mockito.any())).thenReturn(PayslipBuilder.build());
subject.generatePayslips();
}
}
<file_sep>package com.myob.payslip.models;
public class TaxRate {
private int taxableIncomeStart;
private int taxableIncomeEnd;
private double rate;
public int getTaxableIncomeStart() {
return taxableIncomeStart;
}
public void setTaxableIncomeStart(int taxableIncomeStart) {
this.taxableIncomeStart = taxableIncomeStart;
}
public int getTaxableIncomeEnd() {
return taxableIncomeEnd;
}
public void setTaxableIncomeEnd(int taxableIncomeEnd) {
this.taxableIncomeEnd = taxableIncomeEnd;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public boolean matchingRate(int income) {
return income >= taxableIncomeStart;
}
}
| 109c0fa730c748ca4e6f9ba75a736bdea224822e | [
"Markdown",
"Java",
"Gradle"
] | 16 | Java | jaysu-github/employee-monthly-payslip | bbe447f0ca5c7e95d0fbc09299fc240945bd167b | 40d30cd730345120640691330dd0a49a36f26688 |
refs/heads/master | <repo_name>kumarmeet/LetUS12VChaperter03<file_sep>/LoopQ3/main.c
/*Write a program to find the value of one number raised to the power of another*/
/*01-05-2019*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, num2, i, pow=1;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
for(i=1 ; i <= num2 ; i++){
pow = pow * num1;
}
printf("%d is raised to the power of %d is %d",num1, num2, pow);
return 0;
}
<file_sep>/LoopQ4/main.c
/*Write a program to print all the ASCII values and their
equivalent characters using a while loop.*/
/*01-05-2019*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ascii; int i = 0;
while(i <= 255){
printf("%d = ASCII value is %c \n", i,i);
i++;
}
return 0;
}
<file_sep>/LoopQ5/main.c
/*Write a program to print out all Armstrong numbers between 1 and 500*/
/*01-05-2019*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,dn,d,temp;
printf("The series of Armstrong numbers from 1 to 500 : ");
for(i=1; i<=500; i++){
temp=0;
n=i;
do {
d=n%10;
temp=temp+(d*d*d);
n=n/10;
} while(n!=0);
if(i==temp){
printf("\t %d", i);
}
}
return 0;
}
<file_sep>/LoopQ8/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,ocnum=1,foct=0,temp;
printf("\nEnter an integer = ");
scanf("%d",&num);
while(num>=8) //loop for converting decimal to octal
{
temp=num%8;
num=num/8;
ocnum=(ocnum*10)+temp;
}
ocnum=(ocnum*10)+num; //number is in reverse
while(ocnum!=1) //loop for reversing the octal result
{
temp=ocnum%10;
ocnum=ocnum/10;
foct=(foct*10)+temp;
}
printf("\nThe octal equivalent of %d\n",foct);
return 0;
}
<file_sep>/LoopQ1/main.c
/*Write a program to calculate overtime pay of 10 employees*/
/*01-05-2019*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int overtime, overtimePay, employees = 10, i = 1, hours;
while(i <= employees){
printf("Enter %d employee hours: ", i);
scanf("%d",&hours);
if(hours > 40){
overtime = hours - 40;
overtimePay = overtimePay + (12 * overtime);
}else{
printf("Enter hour above 40 only ");
break;
}
i++;
}
printf("\nTotal overtime pay of %d employees is %d", i, overtimePay);
return 0;
}
<file_sep>/LoopQ9/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, max=-32768, min=32767, range;
char choice='y';
while(choice=='y'){
printf("\nenter any number ");
scanf("%d",&num);
if(num>max){
max=num;
}
if(num<min){
min=num;
}
printf("\nYou Want To Add Another Number(y/n) ");
fflush(stdin);
scanf("%c",&choice);
}
range=max-min;
printf("Largest number Is %d\n",max);
printf("Smallest number Is %d\n",min);
printf("Range Is %d\n",range);
return 0;
}
<file_sep>/LoopQ2/main.c
/*Write a program to calculate factorial value of a number*/
/*01-05-2019*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, fact = 1;
printf("Enter number for calculating factorial of it: ");
scanf("%d", &num);
//factorial of 5 is 120 = 1*2*3*4*5
for(i=1 ; i<=num ; i++){
fact = fact * i;
}
printf("%d", fact);
return 0;
}
<file_sep>/README.md
# LetUS12VChaperter03
Loop Exercises
| 33a8d8436d9cf63fea92df0b899cb1d651b90ace | [
"Markdown",
"C"
] | 8 | C | kumarmeet/LetUS12VChaperter03 | aae0252c3d62c08f62a1f7b7dd28cdd76ca6a1c8 | 0474fdc62678b6f558bdaf9d04046b2b031f1aa4 |
refs/heads/master | <repo_name>harryw1/data_structures<file_sep>/DynamicArray/DynamicArray.cpp
#include <iostream>
#include <string>
#include <stdlib.h>
#include "DynamicArray.h"
template<typename T>
DynamicArray<T>::DynamicArray()
{
m_NumItems = 0;
m_Size = DEFAULT_SIZE;
m_Array = new T[m_Size];
}
template<typename T>
void DynamicArray<T>::append(T a_Item)
{
// Resize the array if necessary
resize();
insert(a_Item, m_NumItems);
}
template<typename T>
void DynamicArray<T>::prepend(T a_Item)
{
// Resize the array if necessary
resize();
insert(a_Item, 0);
}
template<typename T>
void DynamicArray<T>::insert(T a_Item, int a_Index)
{
if (a_Index > m_NumItems || a_Index < 0)
{
std::cout << "Invalid call to DynamicArray<T>::insert(...), index out of bounds" << std::endl;
return;
}
resize();
for (int i = (m_NumItems - 1); i >= a_Index; i--)
{
m_Array[i + 1] = m_Array[i];
}
m_Array[a_Index] = a_Item;
m_NumItems++;
}
template<typename T>
void DynamicArray<T>::remove(int a_Index)
{
if (a_Index > (m_NumItems - 1) || a_Index < 0)
{
std::cout << "Invalid call to DynamicArray<T>::remove(...), index out of bounds" << std::endl;
return;
}
resize();
for (int i = a_Index; i < (m_NumItems - 1); i++)
{
m_Array[i] = m_Array[i + 1];
}
m_NumItems--;
}
template<typename T>
void DynamicArray<T>::remove_all()
{
delete[] m_Array;
m_NumItems = 0;
m_Size = DEFAULT_SIZE;
m_Array = new T[m_Size];
}
template<typename T>
void DynamicArray<T>::print_array()
{
if (m_NumItems == 0)
{
std::cout << "Empty array :(" << std::endl;
return;
}
for (int i = 0; i < m_NumItems; i++)
{
std::cout << "Item [" << i << "]: " << m_Array[i] << std::endl;
}
}
template<typename T>
void DynamicArray<T>::rotate(int a_Rotation)
{
// 0 would mean no rotation
if (a_Rotation == 0)
{
return;
}
// Shifting to the left is the same as shifting to the right n - r times
if (a_Rotation < 0)
{
a_Rotation = m_NumItems + a_Rotation - 1;
}
a_Rotation = a_Rotation % m_NumItems;
T *newArray = new T[m_Size];
int numLoops = 0;
// std::cout << "m_Size = " << m_Size << " m_NumItems = " << m_NumItems << " a_Rotation = " << a_Rotation << std::endl;
for (int i = 0; i < (m_NumItems - a_Rotation); i++)
{
//std::cout << "[i + a_Rotation] = " << (i + a_Rotation) << " i = " << i << std::endl;
newArray[i + a_Rotation] = m_Array[i];
numLoops = i + 1;
}
int j = 0;
for (int i = numLoops; j < (m_NumItems - numLoops); i++, j++)
{
//std::cout << i << " " << j << std::endl;
newArray[j] = m_Array[i];
}
delete[] m_Array;
m_Array = newArray;
}
template<typename T>
void DynamicArray<T>::reverse()
{
T *newArray = new T[m_Size];
for (int i = 0; i < m_NumItems; i++)
{
newArray[i] = m_Array[(m_NumItems - 1) - i];
}
delete[] m_Array;
m_Array = newArray;
}
template<typename T>
void DynamicArray<T>::random_shuffle()
{
T* arrayCopy = new T[m_Size];
int arrayCopyNumItems = m_NumItems;
for(int i = 0; i < m_NumItems; i++)
{
arrayCopy[i] = m_Array[i];
}
int randomIndex;
bool breakCondition;
for(int i = 0; i < m_NumItems; i++)
{
//std::cout << "array copy num items: " << arrayCopyNumItems << std::endl;
randomIndex = (rand() % arrayCopyNumItems);
//std::cout << "random index: " << randomIndex << std::endl;
m_Array[i] = arrayCopy[randomIndex];
//deletes the random index we just pulled from the copy array
for (int i = randomIndex; i < (arrayCopyNumItems - 1); i++)
{
arrayCopy[i] = arrayCopy[i + 1];
}
arrayCopyNumItems--;
}
delete[] arrayCopy;
}
template<typename T>
void DynamicArray<T>::resize()
{
if ((m_NumItems / m_Size) > 64)
{
grow_array();
}
if ((m_Size > DEFAULT_SIZE) && (m_NumItems / m_Size < 50))
{
shrink_array();
}
// Else do nothing
}
template<typename T>
void DynamicArray<T>::grow_array()
{
unsigned int newSize;
newSize = ((m_Size * 100) / 64);
m_Size = newSize;
T* newArray = new T[m_Size];
copy_array(newArray);
std::cout << "new size: " << newSize << std::endl;
std::cout << "m_size: " << m_Size << std::endl;
}
template<typename T>
void DynamicArray<T>::shrink_array()
{
unsigned int newSize;
newSize = ((m_Size * 100) / 64);
m_Size = newSize;
T* newArray = new T[m_Size];
copy_array(newArray);
std::cout << "new size: " << newSize << std::endl;
std::cout << "m_size: " << m_Size << std::endl;
}
template<typename T>
void DynamicArray<T>::copy_array(T*newArray)
{
for(int i = 0; i < m_NumItems; i++)
{
newArray[i] = m_Array[i];
}
delete[] m_Array;
m_Array = newArray;
}<file_sep>/DynamicArray/DynamicArray.h
#ifndef __DynamicArray__
#define __DynamicArray__
template <typename T>
class DynamicArray
{
public:
DynamicArray();
// append an items to the array
void append(T a_Item);
// prepend an item to the array
void prepend(T a_Item);
// insert a_Item at a_Index
void insert(T a_Item, int a_Index);
// remove an item from a_index
void remove(int a_Index);
// removes all elements from the array
void remove_all();
// Shifts all elements of the array a_Rotation positions
void rotate(int a_Rotation);
//reverses the order of the elements in the list
void reverse();
// randomly shuffles the elements of the array
void random_shuffle();
// prints all elemetns of the array
void print_array();
private:
// The default size of an empty array
static const unsigned int DEFAULT_SIZE = 1000000;
// Holds the item count
unsigned int m_NumItems;
// Holds the current size of the array
unsigned int m_Size;
// The actual array that holds the items
T* m_Array;
// tests whether or not we need to resize
void resize();
// grow and shrink array are essentially the same: could change into just one function later
void grow_array();
void shrink_array();
// takes contents from a and puts them into b,
// moves a pointer to b
// frees up b
void copy_array(T*newArray);
};
#endif<file_sep>/project34Files/stlListTiming/timingMain.cpp
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
#include <string>
#include <list>
#include <vector>
int main()
{
srand(time(0));
//instantiates list (doubly-linked)
std::list<int> myList;
//iterator from list called it
std::list<int>::iterator it;
//TIMING FUNCTION STUFF
std::clock_t start;
while(true)
{
int menuSelection;
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
std::cout << "STL List (Doubly-Linked)" << std::endl;
std::cout << "------------------------" << std::endl;
//push_back
std::cout << std::setw(8) << "1. " << std::setw(2) << "Append" << std::endl;
//push_front
std::cout << std::setw(8) << "2. " << std::setw(2) << "Prepend" << std::endl;
//insert
std::cout << std::setw(8) << "3. " << std::setw(2) << "Insert" << std::endl;
//erase
std::cout << std::setw(8) << "4. " << std::setw(2) << "Remove Element" << std::endl;
//clear
std::cout << std::setw(8) << "5. " << std::setw(2) << "Remove All" << std::endl;
//????
std::cout << std::setw(8) << "6. " << std::setw(2) << "Rotate" << std::endl;
//reverse
std::cout << std::setw(8) << "7. " << std::setw(2) << "Reverse" << std::endl;
//???
std::cout << std::setw(8) << "8. " << std::setw(2) << "Shuffle" << std::endl;
//begin: iterator is called it... it++ moves the iterator to the next element
std::cout << std::setw(8) << "9. " << std::setw(2) << "Display" << std::endl;
//exit
std::cout << std::setw(8) << "10. " << std::setw(2) << "Exit" << std::endl;
std::cout << std::endl;
std::cout << "Please make a selection: ";
std::cin >> menuSelection;
if(menuSelection < 1 || menuSelection > 10)
{
std::cout << std::endl;
std::cout << "Please make a valid selection." << std::endl;
std::cout << std::endl;
}
else
{
if(menuSelection == 1)
{
int userInput;
std::cout << "Please enter the item to be appended: ";
std::cin >> userInput;
//TIMING
start = std::clock();
for(int i = 0; i < 1000; i++)
{
myList.push_back(userInput);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
}
if(menuSelection == 2)
{
int userInput;
std::cout << "Please enter the item to be prepended: ";
std::cin >> userInput;
start = std::clock();
for(int i = 0; i < 1000000; i++)
{
myList.push_front(userInput);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
}
if(menuSelection == 3)
{
int userInput;
int indexInsert;
it = myList.begin();
std::cout << "Please enter the item to be inserted: ";
std::cin >> userInput;
std::cout << std::endl;
std::cout << "Please enter the index to insert at (ie. 0 to insert at head): ";
std::cin >> indexInsert;
for(int i = 0; i < indexInsert; i++)
{
++it;
}
start = std::clock();
for(int i = 0; i < 1000000; i++)
{
myList.insert(it, userInput);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
}
if(menuSelection == 4)
{
int userInput;
it = myList.begin();
std::cout << "Please enter the item to be removed (ie. 0 to remove the head): ";
std::cin >> userInput;
if(userInput > myList.size())
{
std::cout << std::endl;
std::cout << "Out of bounds exception in std::list::remove(i)..." << std::endl;
std::cout << std::endl;
break;
}
for(int i = 0; i < userInput; i++)
{
++it;
}
start = std::clock();
for(int i = 0; i < 99; i++)
{
myList.erase(it);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
}
if(menuSelection == 5)
{
std::cout << "Removing all..." << std::endl;
for(int i = 0; i < 100; i++)
{
myList.clear();
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
std::cout << "All items removed from list." << std::endl;
}
if(menuSelection == 6)
{
int userInput;
std::cout << "Please enter the number of roations to be made: ";
std::cin >> userInput;
// creates a vector with name ...
std::vector<int> vectorCopy;
// reserves necessary space for the vector based on list size
vectorCopy.reserve(myList.size());
// copies elements from list to vector
std::copy(myList.begin(), myList.end(), std::back_inserter(vectorCopy));
// rotates the vector based on i
std::rotate(vectorCopy.begin(), vectorCopy.begin() + userInput, vectorCopy.end());
// clears list
myList.clear();
// assigns new values
it = myList.begin();
start = std::clock();
for(int i = 0; i < vectorCopy.size(); i++)
{
myList.push_back(vectorCopy[i]);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
std::cout << "List rotated." << std::endl;
}
if(menuSelection == 7)
{
std::cout << "Reversing..." << std::endl;
start = std::clock();
myList.reverse();
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
std::cout << "List reversed." << std::endl;
}
if(menuSelection == 8)
{
std::cout << "Shuffling..." << std::endl;
// creates a vector with name ...
std::vector<int> vectorCopy;
// reserves neceessary space for the vector based on list size
vectorCopy.reserve(myList.size());
// copies elemets from list to vector
std::copy(myList.begin(), myList.end(), std::back_inserter(vectorCopy));
// shuffles the vector
std::random_shuffle(vectorCopy.begin(), vectorCopy.end());
// clears list
myList.clear();
// assigns new values
it = myList.begin();
start = std::clock();
for(int i = 0; i < vectorCopy.size(); i++)
{
myList.push_back(vectorCopy[i]);
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
std::cout << "List shuffled." << std::endl;
}
if(menuSelection == 9)
{
int i;
it = myList.begin();
std::cout << "Current list:" << std::endl;
start = std::clock();
for(it, i = 0; it!= myList.end(); it++, i++)
{
std::cout << "Index [" << i << "]" << ": " << *it << std::endl;
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
std::cout << std::endl;
}
if(menuSelection == 10)
{
std::cout << "Exiting" << std::endl;
break;
}
}
}
return 0;
}<file_sep>/LinkedList/Node.h
#ifndef NODE_H_
#define NODE_H_
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
class Node
{
/* no other member variables should be used */
private:
T data;
Node<T>* next;
Node<T>* prev;
public:
/* Constructor needs a body */
Node(T data, Node::Node<T>* next = NULL, Node::Node<T>* prev = NULL)
{
this -> data = data;
this -> next = next;
this -> prev = prev;
}
/* getters/setters for this->data */
T get_data()
{
return this -> data;
}
void set_data(T data)
{
this -> data = data;
}
/* getters/setters for this->next */
Node<T>* get_next()
{
return this -> next;
}
void set_next(Node<T>* next)
{
this -> next = next;
}
/* getters/setters for this->prev */
Node<T>* get_prev()
{
return this -> prev;
}
void set_prev(Node<T>* prev)
{
this -> prev = prev;
}
/* display the pointer addresses */
void display_links()
{
cout << "Previous: " << prev << endl;
cout << "Next: " << next << endl;
}
/* display all node information */
void print_node()
{
cout << "Data: " << data << endl;
}
};
#endif
<file_sep>/DynamicArray/dArrayMain.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
#include "DynamicArray.cpp"
int main()
{
srand(time(0));
DynamicArray<int> myArray;
unsigned int menuSelection;
while(true)
{
std::cout << "~~~~~~~~~~~~~" << std::endl;
std::cout << "DYNAMIC ARRAY" << std::endl;
std::cout << "-------------" << std::endl;
std::cout << std::setw(8) << "1. " << std::setw(2) << "Append" << std::endl;
std::cout << std::setw(8) << "2. " << std::setw(2) << "Prepend" << std::endl;
std::cout << std::setw(8) << "3. " << std::setw(2) << "Insert" << std::endl;
std::cout << std::setw(8) << "4. " << std::setw(2) << "Remove" << std::endl;
std::cout << std::setw(8) << "5. " << std::setw(2) << "Remove all" << std::endl;
std::cout << std::setw(8) << "6. " << std::setw(2) << "Rotate" << std::endl;
std::cout << std::setw(8) << "7. " << std::setw(2) << "Reverse" << std::endl;
std::cout << std::setw(8) << "8. " << std::setw(2) << "Random Shuffle" << std::endl;
std::cout << std::setw(8) << "9. " << std::setw(2) << "Print Array" << std::endl;
std::cout << std::setw(8) << "10. " << std::setw(2) << "Exit" << std::endl;
std::cout << std::endl;
std::cout << "Please make a selection: ";
std::cin >> menuSelection;
if(menuSelection < 1 || menuSelection > 10)
{
std::cout << std::endl;
std::cout << "Please make a valid selection." << std::endl;
std::cout << std::endl;
}
else
{
if(menuSelection == 1)
{
int userInput;
std::cout << "Please enter the item to be appended: ";
std::cin >> userInput;
myArray.append(userInput);
}
if(menuSelection == 2)
{
int userInput;
std::cout << "Please enter the item to be prepended: ";
std::cin >> userInput;
myArray.prepend(userInput);
}
if(menuSelection == 3)
{
int userInput;
int indexInsert;
std::cout << "Please enter the item to be inserted: ";
std::cin >> userInput;
std::cout << std::endl;
std::cout << "Please enter the index to insert at (ie. 0 to insert at head): ";
std::cin >> indexInsert;
myArray.insert(userInput, indexInsert);
}
if(menuSelection == 4)
{
int userInput;
std::cout << "Please enter the item to be removed (ie. 0 to remove the head): ";
std::cin >> userInput;
myArray.remove(userInput);
}
if(menuSelection == 5)
{
std::cout << "Removing all..." << std::endl;
myArray.remove_all();
std::cout << "All items removed from array." << std::endl;
}
if(menuSelection == 6)
{
int userInput;
std::cout << "Please enter the number of roations to be made: ";
std::cin >> userInput;
myArray.rotate(userInput);
}
if(menuSelection == 7)
{
std::cout << "Reversing..." << std::endl;
myArray.reverse();
std::cout << "Array reversed." << std::endl;
}
if(menuSelection == 8)
{
std::cout << "Shuffling..." << std::endl;
myArray.random_shuffle();
std::cout << "Array shuffled." << std::endl;
}
if(menuSelection == 9)
{
std::cout << "Current array:" << std::endl;
std::cout << std::endl;
myArray.print_array();
}
if(menuSelection == 10)
{
std::cout << "Exiting" << std::endl;
break;
}
}
}
/*std::cout << std::endl;
std::string x;
std::cout << "Press enter to continue...";
std::getline(std::cin, x);
std::cout << std::endl;*/
return 0;
}<file_sep>/project34Files/linkedListTiming/main.cpp
#include <iostream>
#include <ctime>
#include "LinkedList.h"
using namespace std;
int main()
{
srand(time(0));
LinkedList<int> * list = new LinkedList<int>(NULL, NULL, 0, 0);
std::clock_t start;
start = std::clock()
list -> append(0);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_i(0);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> append(1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_i(1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> prepend(42);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_i(0);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> add_at_i(84, 1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_i(1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> remove_at_i(1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_all();
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> display_range(0,0);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> change_type(1);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> append(100);
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list - remove_at_i((list->get_size()));
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
start = std::clock()
list -> info();
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
//list -> random_shuffle();
cout << endl;
for(int i = 0; i < (list -> get_size()); i++)
{
list -> display_i(i);
cout << endl;
}
}
<file_sep>/project34Files/dynamicArrayTiming/dynamicTiming.cpp
#include "DynamicArray.cpp"
#include <iostream>
#include <ctime>
int main()
{
DynamicArray<int> arrayTest;
std::clock_t start;
for(int i = 0; i < 1000000; i++)
{
arrayTest.append(10);
}
//arrayTest.append(10);
////////////////////
start = std::clock();
for(int i = 0; i < 1; i++)
{
arrayTest.print_array();
}
std::cout << "Stopwatch: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms." << std::endl;
////////////////////
}<file_sep>/hweiss_project_1.cpp
#include <iostream>
using namespace std;
void grow_array(int array[], int &array_count);
void shrink_array(int array[], int &array_count, int user_number_remove);
double report_size(int array[], int &array_count);
void exit_program();
int main()
{
MyClass a;
}
void grow_array(int array[], int &array_count)
{
if(report_size > 65 && array.size() > 3)
{
int new_array_size = 0;
new_array_size = (array_count * 100 / 62);
int temp_array* = new int[new_array_size];
for(int i = 0; i < array_count; i++)
{
temp_array[i] = array[i];
}
delete [] array;
array = temp_array;
temp_array = NULL;
}
}
void shrink_array(int array[], int &array_count, int user_number_remove)
{
if(report_size < 60 && array.size() > 3)
{
int new_array_size = 0;
new_array_size = (array_count * 100 / 62);
int temp_array* = new int[new_array_size];
int temp_array_count = 0;
for(int i = 0; i < array_count && array[i] != user_number_remove; i++)
{
temp_array[i] = array[i];
temp_array_count++;
}
for(int i = temp_array_count + 1; i < array_count; i++)
{
temp_array[i] = array[i];
}
delete [] array;
array = temp_array;
temp_array = NULL;
}
}
double report_size(int array[], int &array_count)
{
size_t tmp_array_size = 0;
for(int i = 0; i < array.size(); i++)
{
tmp_array_size++;
}
size_t tmp_array_count = array_count;
double percent_full;
percent_full = (100 * tmp_array_count / tmp_array_size);
return percent_full;
}
void exit_program()
{
cout << endl;
cout << "Program ended." << endl;
cout << endl;
}
<file_sep>/nonTemplateLinked/LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"
using namespace std;
//template <typename T>
class LinkedList
{
/* No other member variables should be added */
private:
Node head;
Node tail;
size_t type;
size_t size;
bool is_circularly;
public:
/* Default Constructor - I gave you this for Free */
LinkedList() : head(NULL), tail(NULL), type(0), size(0), is_circularly(false){}
/* ... but not this one */
LinkedList(Node head, Node tail, size_t type, bool is_circularly)
{
this -> head = head;
this -> tail = tail;
this -> type = type;
this -> is_circularly = is_circularly;
}
/* getter for size */
size_t get_size()
{
return this -> size;
}
/* add to the end of the list */
void append(int data)
{
Node node(data);
Node tmp;
while(tmp -> next != NULL)
{
tmp = tmp -> next;
}
node -> next = tmp;
tmp -> next = NULL;
if(is_circularly)
{
tmp -> prev = tail;
}
tail = tmp;
/*Node<int> node = new Node(data);
Node tmp = head;
while(tmp -> next != nullptr){
tmp = tmp -> next;
}
tmp = node;
tmp -> next = nullptr;
if(is_circularly)
{
tmp -> prev = tail;
}
tail = tmp;*/
}
/* add to the front of the list */
void prepend(int data);
/* add so the new node is the ith node */
void add_at_i(int data, size_t i);
/* remove the ith node from the list */
void remove_at_i(size_t i);
/* update the type of the array along with all the links
and members of the list */
void change_type(size_t type);
/* remove all the elements in the list */
void delete_list();
/* rotate the nodes in the list r spots.
if r < 0 rotate left
if r > 0 rotate right
*/
void rotate(int r);
/* reverse the order of the list */
void reverse();
/* put the list in a random order */
void random_shuffle();
/* display the node iformation of the ith node */
void display_i(size_t i);
/* Print the data from all the nodes - again a freebie */
void display_all()
{
std::cout << "List: ";
if (this->head == NULL)
{
std::cout << "EMPTY LIST\n";
return;
}
Node<int>* c = this->head;
while (c != NULL)
{
std::cout << c->get_data() << " ";
c = c->get_next();
}
std::cout << std::endl;
}
/* print node information for all nodes in the given range
if one of the range values are not given use the following
if no start: start at node 0
I started this one for you
*/
void display_range(size_t i = 0, size_t j = 0)
{
if (i > j)
{
std::cout << "Error: j cannot be larger than i\n";
return;
}
std::cout << "List: ";
}
/* display the head/tail addresses - Free */
void display_links()
{
std::cout << "Links:"
<< "\n\thead = " << this->head
<< "\n\ttail = " << this->tail
<< std::endl;
}
/* display all list information - another! Im so nice. */
void info()
{
std::string t = (this->type) ? "Doubly" : "Singly";
t += (is_circularly) ? "-circularly " : " ";
std::cout << "Type: " << t << "linked-list\n";
std::cout << "Size: " << this->size << std::endl;
this->display_links();
}
};
#endif
<file_sep>/LinkedList/LinkedList.h
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "Node.h"
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
//this thing leaks memory like one ones business ;D
template <typename T>
class LinkedList
{
/* No other member variables should be added */
private:
Node<T>* head;
Node<T>* tail;
size_t type;
size_t size;
bool is_circularly;
public:
/* Default Constructor - I gave you this for Free */
LinkedList() : head(NULL), tail(NULL), type(0), size(0), is_circularly(false){}
/* ... but not this one */
LinkedList(Node<T>* head, Node<T>* tail, size_t type, bool is_circularly)
{
this -> head = head;
this -> tail = tail;
this -> type = type;
this -> size = 0;
this -> is_circularly = is_circularly;
}
/* getter for size */
size_t get_size()
{
return this -> size;
}
/* add to the end of the list */
void append(T data)
{
//construct new node to be appended
Node<T>* toAppend = new Node<T>(data);
//case for when the list is empty
if(!size)
{
head = toAppend;
tail = toAppend;
}
//otherwise
else
{
//sets the next pointer to NULL
toAppend->set_next(NULL);
//sets the current tail's next to the new node
tail -> set_next(toAppend);
//cases for when the list is doubly, circularly, and doubly circularly
if(type)
{
//sets appended prev pointer to what is the current tail
toAppend -> set_prev(tail);
}
if(is_circularly)
{
//sets the appended next pointer to the head if we have a circularly
toAppend -> set_next(head);
}
if(is_circularly && type)
{
//does the same as is_circularly but also sets the head prev pointer to the appnded element
toAppend -> set_next(head);
head -> set_prev(toAppend);
}
//makes the appended thing the new tail
tail = toAppend;
}
size++;
return;
}
/* add to the front of the list */
void prepend(T data)
{
//creates new node
Node<T>* toPrepend = new Node<T>(data);
//for when the list is empty
if(!size)
{
head = toPrepend;
tail = toPrepend;
}
else
{
//new node points to where the head is pointing
toPrepend -> set_next(head);
if(type)
{
tail -> set_next(NULL);
toPrepend -> set_prev(NULL);
}
if(is_circularly)
{
//points tail to new node at the beginning of list
toPrepend -> set_prev(tail);
}
if(is_circularly && type)
{
//points tail to new node and points new node prev to tail
tail -> set_next(toPrepend);
toPrepend -> set_prev(tail);
}
head = toPrepend;
}
size++;
return;
}
/* add so the new node is the ith node */
void add_at_i(T data, size_t i)
{
//create a counter to loop from the beginning of the list to the end
//if the user enters 0, we call the prepend function
//if the user enters a number equal to the size of the list, call append
Node<T>* appendI = new Node<T>(data);
Node<T>* current = new Node<T>(data);
Node<T>* previousN = new Node<T>(data);
int temp = 0;
//empty list
if(!size)
{
append(data);
head = appendI;
tail = appendI;
}
//if user enters 0
if(!i)
{
prepend(data);
head = appendI;
}
//if user enters size
if(i == size)
{
append(data);
tail = appendI;
}
else
{
//iterates through the list, updating node pointers until we reach the position where we want to add
current = head;
while(temp < i)
{
previousN = current;
current = (current -> get_next());
temp++;
}
previousN -> set_next(appendI);
appendI -> set_next(current);
if(type)
{
appendI -> set_prev(previousN);
}
if(is_circularly && type && (i == 0))
{
appendI -> set_prev(tail);
appendI -> set_next(head);
head = appendI;
}
if(is_circularly && type && (i == size))
{
appendI -> set_prev(previousN);
appendI -> set_next(head);
tail = appendI;
}
}
size++;
return;
}
/* remove the ith node from the list */
void remove_at_i(size_t i)
{
//temp nodes for iterating through the list
Node<T>* temp = new Node<T>(0);
Node<T>* nextIterate = new Node<T>(0);
int counter = 0;
if(!size)
{
cout << "The list is already empty." << endl;
return;
}
if(i < 0 || i > size)
{
cout << "Out of bounds." << endl;
return;
}
//when deleteing the first thing in the list
if(i == 0)
{
//holds the first node
temp = head;
//head points to second thing in list
head = (head -> get_next());
//sets the previous to NULL when in a doubly linked list
if(type)
{
head -> set_prev(NULL);
}
//if its a circle, second thing now needs to also point to the tail
if(is_circularly)
{
head -> set_prev(tail);
}
}
//deleting the last thing in the list
if(i == size)
{
//cout << "inside i = size" << endl;
if(is_circularly)
{
temp = head;
nextIterate = head;
while(counter < (i-1))
{
temp = nextIterate;
nextIterate = (nextIterate -> get_next());
counter++;
}
tail = temp;
tail -> set_next(head);
nextIterate -> set_next(NULL);
}
if(type)
{
temp = head;
nextIterate = head;
while(counter < (i-2))
{
temp = nextIterate;
nextIterate = (nextIterate -> get_next());
counter++;
}
tail = nextIterate;
tail -> set_prev(temp);
nextIterate -> set_next(NULL);
}
else
{
temp = head;
nextIterate = head;
while(counter < (i-1))
{
temp = nextIterate;
nextIterate = (nextIterate -> get_next());
counter++;
}
tail = temp;
tail -> set_next(NULL);
}
}
else
{
if(type)
{
while(counter < (i-1))
{
temp = nextIterate;
nextIterate = (nextIterate -> get_next());
counter++;
}
nextIterate = (nextIterate -> get_next());
temp -> set_next(nextIterate);
nextIterate -> set_prev(temp);
}
else
{
//additional node to so we can null the pointer of thing to remove
//and not lose the thing after it
Node<T>* third = new Node<T>(0);
temp = head;
nextIterate = head;
while(counter < i)
{
temp = nextIterate;
nextIterate = (nextIterate -> get_next());
counter++;
}
third = (nextIterate -> get_next());
temp -> set_next(third);
nextIterate -> set_next(NULL);
}
}
size--;
return;
}
/* update the type of the array along with all the links
and members of the list */
void change_type(size_t type)
{
//should iterate through the list, and depending on the current type
//should add or remove prev pointers to all of the nodes
//if we make the list circularly, give the head node a prev pointer to the tail
//and the tail node a next pointer to the head
Node<T>* previousPointer = new Node<T>(0);
Node<T>* currentPointer = new Node<T>(0);
Node<T>* nextPointer = new Node<T>(0);
previousPointer = head;
currentPointer = head;
nextPointer = head;
//making sure the pointers are all at head
//cout << previousPointer << " " << currentPointer << " " << nextPointer << endl;
if(type)
{
this -> type = 1;
//cout << "inside type" << endl;
currentPointer -> set_prev(NULL);
//cout << "first pointer set" << endl;
//first iteration does not move the previous pointer
currentPointer = (nextPointer -> get_next());
nextPointer = (nextPointer -> get_next());
//cout << "moves current and next" << endl;
currentPointer -> set_prev(previousPointer);
//cout << "current points to prev" << endl;
while(nextPointer != NULL)
{
//inside while loop
previousPointer = currentPointer;
//cout << "previous = current" << endl;
currentPointer = nextPointer;
//cout << "current = next" << endl;
currentPointer -> set_prev(previousPointer);
//cout << currentPointer -> get_prev() << " this is current get prev" << endl;
nextPointer = (nextPointer -> get_next());
//cout << "next is get next" << endl;
}
//cout << "Left while loop" << endl;
currentPointer -> set_prev(previousPointer);
//cout << "current points to prev" << endl;
previousPointer = currentPointer;
//cout << "previous is now current" << endl;
currentPointer = tail;
//cout << "current equals tail" << endl;
currentPointer -> set_prev(previousPointer);
}
if(type && is_circularly)
{
this -> type = 1;
//cout << "type and circle" << endl;
currentPointer -> set_prev(NULL);
//first iteration does not move the previous pointer
currentPointer = (nextPointer -> get_next());
nextPointer = (nextPointer -> get_next());
currentPointer -> set_prev(previousPointer);
while(nextPointer != head)
{
previousPointer = currentPointer;
currentPointer = nextPointer;
nextPointer = (nextPointer -> get_next());
currentPointer -> set_prev(previousPointer);
}
currentPointer -> set_prev(previousPointer);
nextPointer -> set_prev(currentPointer);
nextPointer -> set_next(head);
}
if(!type)
{
this -> type = 0;
//cout << "not type" << endl;
//first iteration does not move the previous pointer
currentPointer = (nextPointer -> get_next());
nextPointer = (nextPointer -> get_next());
while(nextPointer != NULL)
{
previousPointer = currentPointer;
currentPointer = nextPointer;
nextPointer = (nextPointer -> get_next());
previousPointer -> set_prev(NULL);
currentPointer -> set_prev(NULL);
}
nextPointer -> set_prev(NULL);
currentPointer -> set_prev(NULL);
}
if(!type && !is_circularly)
{
this -> type = 0;
//cout << "not type and not circle" << endl;
currentPointer -> set_prev(NULL);
//first iteration does not move the previous pointer
currentPointer = (nextPointer -> get_next());
nextPointer = (nextPointer -> get_next());
currentPointer -> set_prev(NULL);
while(nextPointer != NULL)
{
previousPointer = currentPointer;
currentPointer = nextPointer;
nextPointer = (nextPointer -> get_next());
currentPointer -> set_prev(NULL);
}
nextPointer -> set_prev(NULL);
}
}
/* remove all the elements in the list */
void delete_list()
{
//iterate through the list, using the delete function on each node
//pointer that exists so far
Node<T>* deleteAll = new Node<T>(0);
deleteAll = head;
while(deleteAll != NULL)
{
head -> set_next(deleteAll->get_next());
deleteAll -> set_next(NULL);
delete deleteAll;
deleteAll = (head -> get_next());
}
head = NULL;
tail = NULL;
}
/* rotate the nodes in the list r spots.
if r < 0 rotate left
if r > 0 rotate right
*/
void rotate(int r);
/* reverse the order of the list */
void reverse();
/* put the list in a random order */
void random_shuffle()
{
//temp nodes so i dont lose pointers
Node<T>* startingNode = new Node<T>(NULL);
Node<T>* temp = new Node<T>(NULL);
int counter = 0;
int randomNode = 0;
startingNode = head;
//j_temp = head;
randomNode = (rand() % (this -> size));
while(counter < randomNode)
{
startingNode = (startingNode -> get_next());
counter++;
}
//cout << (startingNode -> get_data()) << endl;
}
/* display the node iformation of the ith node */
void display_i(size_t i)
{
cout << "[" << i << "]" << " Node Info: " << endl;
Node<T>* displayThis = new Node<T>(NULL);
int counter = 0;
if(i == 0)
{
//cout << "Times round: " << counter << endl;
cout << "Data: " << (head -> get_data()) << endl;
head -> display_links();
return;
//counter++;
}
if(i == (this -> size))
{
//cout << "Times round: " << counter << endl;
cout << "Data: " << (tail -> get_data()) << endl;
tail -> display_links();
return;
//counter++;
}
else
{
displayThis = head;
for(int q = 0; q < i; q++)
{
displayThis = (displayThis -> get_next());
}
//cout << "Times round: " << counter << endl;
cout << "Data: " << (displayThis -> get_data()) << endl;
displayThis -> display_links();
return;
//counter++;
}
}
/* Print the data from all the nodes - again a freebie */
void display_all()
{
std::cout << "List: ";
if (this->head == NULL)
{
std::cout << "EMPTY LIST\n";
return;
}
Node<T>* c = this->head;
if(!is_circularly)
{
while (c != NULL)
{
std::cout << c->get_data() << " ";
c = c->get_next();
}
std::cout << std::endl;
}
int sizeCount = 0;
if(is_circularly)
{
while (sizeCount < size)
{
std::cout << c->get_data() << " ";
c = c->get_next();
sizeCount++;
}
std::cout << std::endl;
}
}
/* print node information for all nodes in the given range
if one of the range values are not given use the following
if no start: start at node 0
I started this one for you
*/
void display_range(size_t i = 0, size_t j = 0)
{
if (i > j)
{
std::cout << "Error: i cannot be larger than j\n";
return;
}
std::cout << "List: ";
while(i <= j)
{
if (this->head == NULL)
{
std::cout << "EMPTY LIST\n";
return;
}
Node<T>* c = this->head;
while (c != NULL && i <= j)
{
std::cout << c->get_data() << " ";
c = c->get_next();
i++;
}
std::cout << std::endl;
}
}
/* display the head/tail addresses - Free */
void display_links()
{
std::cout << "Links:"
<< "\n\thead = " << this->head
<< "\n\ttail = " << this->tail
<< std::endl;
}
/* display all list information - another! Im so nice. */
void info()
{
std::string t = (this->type) ? "Doubly" : "Singly";
t += (is_circularly) ? "-circularly " : " ";
std::cout << "Type: " << t << "linked-list\n";
std::cout << "Size: " << this->size << std::endl;
this->display_links();
}
};
#endif
<file_sep>/nonTemplateLinked/Node.h
#ifndef NODE_H
#define NODE_H
#include <iostream>
#include <cstdlib>
using namespace std;
//template <typename T>
class Node
{
/* no other member variables should be used */
private:
int data;
Node next;
Node prev;
public:
/* Constructor needs a body */
Node(int data, Node::Node next = NULL, Node::Node prev = NULL)
{
this -> data = data;
this -> next = next;
this -> prev = prev;
}
/* getters/setters for this->data */
int get_data()
{
return this -> data;
}
int set_data(int data)
{
this -> data = data;
}
/* getters/setters for this->next */
int get_next()
{
return this -> next;
}
int set_next(int &next)
{
this -> next = next;
}
/* getters/setters for this->prev */
int get_prev()
{
return this -> prev;
}
int set_prev(int &prev)
{
this -> prev = prev;
}
/* display the pointer addresses */
void display_links()
{
cout << "Previous: " << prev << endl;
cout << "Next: " << next << endl;
}
/* display all node information */
void print_node()
{
cout << "Data: " << data << endl;
}
};
#endif
| e85df0f66d36962a8d621ae074721a1003fbffe2 | [
"C++"
] | 11 | C++ | harryw1/data_structures | 25bb15239fc9bf1e1743b0a78e41634e7162de91 | 3de68079efc2842b7f275b8817fafae5744f3f86 |
refs/heads/main | <repo_name>MateoEggel/Entrega-Final-JS<file_sep>/index.js
$(document).ready(function(){
var hamburguesasSeleccionada=0
var aderezosSeleccionada=[]
var cantHamburguesa=[]
var cantComplementos=[]
var cantBebidas=[]
var cantAderezos=[]
const pantalla_0 = document.getElementById ("pantalla_0")
const pantalla_1 = document.getElementById ("pantalla_1")
const pantalla_2 = document.getElementById ("pantalla_2")
const pantalla_3 = document.getElementById ("pantalla_3")
const pantalla_4 = document.getElementById ("pantalla_4")
const pantalla_5 = document.getElementById ("pantalla_5")
const pantalla_6 = document.getElementById ("pantalla_6")
pantalla_0.style.dispaly='block'
$("#btnResumen").attr("style", "display:none");
pantalla_1.style.display='none'
pantalla_2.style.display='none'
pantalla_3.style.display='none'
pantalla_4.style.display='none'
pantalla_5.style.display='none'
pantalla_6.style.display='none'
async function readData(url,data = {}) {
// Default options are marked with *
const response = await fetch(url);
return response.json();
}
let productos=readData('dataBase/dataBase.JSON',"")
.then(data => {
hamburguesas=''
resumen=''
for(let i=0;i<data.hamburguesas.length;i++) {
cantHamburguesa[i+1]=0
hamburguesas += ' <div class="col-6 col-md-3 shadow" > <div class="hamburguesa" id='+ data.hamburguesas[i].id+'> <br> <h3 class="item-title"> '+ data.hamburguesas[i].nombre+' $'+ data.hamburguesas[i].precio+' <img class="img" src='+data.hamburguesas[i].image+' alt=""> </div> '
hamburguesas += ' CANTIDAD: <div class="btn-group btn-group-toggle" data-toggle="buttons"> </label> <label class="btn btn-secondary"> <input id='+ data.hamburguesas[i].id+' type="radio" class="restarHamburguesa" name="options" id="option3" autocomplete="off"> - </label> <label class="btn btn-secondary"> <h5 class="contadorHamburguesa" id='+ data.hamburguesas[i].id+' >'+0+' </h5> </label> <label class="btn btn-secondary"> <input id='+ data.hamburguesas[i].id+' type="radio" class="sumarHamburguesa" name="options" id="option3" autocomplete="off"> + </label> </div> </div> '
resumen += '<div class="row resumenHamburguesa" id="'+data.hamburguesas[i].id+'" style="display:none"> <div class="col-3" > <img class="img-resumen" src='+data.hamburguesas[i].image+' alt=""> </div> <div class="col-4"> <h3 class="item-title"> '+ data.hamburguesas[i].nombre+'<h3> </div> <div class="col-2"><h3 id="'+data.hamburguesas[i].id+'" class="cantHamburguesa"> X 0 </h3></div> <div class="col-2"><h3 id="'+data.hamburguesas[i].id+'" class="precioHamburguesa"> 0 </h3></div> <div class="col-2"> </div></div>'
}
document.getElementById ("pantalla_1_items").innerHTML=hamburguesas
document.getElementById ("pantalla_5_hamburguesa").innerHTML=resumen
complementos=''
for(let i=0;i<data.complementos.length;i++) {
cantComplementos[i+1]=0
complementos += ' <div class="col-6 col-md-3 shadow" > <div class="complementos" id='+ data.complementos[i].id+'> <br> <h3 class="item-title"> '+ data.complementos[i].nombre+' $'+ data.complementos[i].precio+' <img class="img" src='+data.complementos[i].image+' alt=""> </div> '
complementos += ' CANTIDAD: <div class="btn-group btn-group-toggle" data-toggle="buttons"> </label> <label class="btn btn-secondary"> <input id='+ data.complementos[i].id+' type="radio" class="restarComplementos" name="options" id="option3" autocomplete="off"> - </label> <label class="btn btn-secondary"> <h5 class="contadorComplementos" id='+ data.complementos[i].id+' >'+0+' </h5> </label> <label class="btn btn-secondary"> <input id='+ data.complementos[i].id+' type="radio" class="sumarComplementos" name="options" id="option3" autocomplete="off"> + </label> </div> </div> '
resumen += '<div class="row resumenComplementos" id="'+data.complementos[i].id+'" style="display:none"> <div class="col-3" > <img class="img-resumen" src='+data.complementos[i].image+' alt=""> </div> <div class="col-4"> <h3 class="item-title"> '+ data.complementos[i].nombre+'<h3> </div> <div class="col-2"><h3 id="'+data.complementos[i].id+'" class="cantComplementos"> X 0 </h3></div> <div class="col-2"><h3 id="'+data.complementos[i].id+'" class="precioComplementos"> 0 </h3></div> <div class="col-2"> </div></div>'
}
document.getElementById ("pantalla_2_items").innerHTML=complementos
document.getElementById ("pantalla_5_hamburguesa").innerHTML=resumen
bebidas=''
for(let i=0;i<data.bebidas.length;i++) {
cantBebidas[i+1]=0
bebidas += ' <div class="col-6 col-md-3 shadow" > <div class="bebidas" id='+ data.bebidas[i].id+'> <br> <h3 class="item-title"> '+ data.bebidas[i].nombre+' $'+ data.bebidas[i].precio+' <img class="img" src='+data.bebidas[i].image+' alt=""> </div> '
bebidas += ' CANTIDAD: <div class="btn-group btn-group-toggle" data-toggle="buttons"> </label> <label class="btn btn-secondary"> <input id='+ data.bebidas[i].id+' type="radio" class="restarBebidas" name="options" id="option3" autocomplete="off"> - </label> <label class="btn btn-secondary"> <h5 class="contadorBebidas" id='+ data.bebidas[i].id+' >'+0+' </h5> </label> <label class="btn btn-secondary"> <input id='+ data.bebidas[i].id+' type="radio" class="sumarBebidas" name="options" id="option3" autocomplete="off"> + </label> </div> </div> '
resumen += '<div class="row resumenBebidas" id="'+data.bebidas[i].id+'" style="display:none"> <div class="col-3" > <img class="img-resumen" src='+data.bebidas[i].image+' alt=""> </div> <div class="col-4"> <h3 class="item-title"> '+ data.bebidas[i].nombre+'<h3> </div> <div class="col-2"><h3 id="'+data.bebidas[i].id+'" class="cantBebidas"> X 0 </h3></div> <div class="col-2"><h3 id="'+data.bebidas[i].id+'" class="precioBebidas"> 0 </h3></div> <div class="col-2"> </div></div>'
}
document.getElementById ("pantalla_3_items").innerHTML=bebidas
document.getElementById ("pantalla_5_hamburguesa").innerHTML=resumen
aderezos=''
for(let i=0;i<data.aderezos.length;i++) {
cantAderezos[i+1]=0
aderezos += ' <div class="col-6 col-md-3 shadow" > <div class="aderezos" id='+ data.aderezos[i].id+'> <br> <h3 class="item-title"> '+ data.aderezos[i].nombre+' $'+ data.aderezos[i].precio+' <img class="img" src='+data.aderezos[i].image+' alt=""> </div> '
aderezos += ' CANTIDAD: <div class="btn-group btn-group-toggle" data-toggle="buttons"> </label> <label class="btn btn-secondary"> <input id='+ data.aderezos[i].id+' type="radio" class="restarAderezos" name="options" id="option3" autocomplete="off"> - </label> <label class="btn btn-secondary"> <h5 class="contadorAderezos" id='+ data.aderezos[i].id+' >'+0+' </h5> </label> <label class="btn btn-secondary"> <input id='+ data.aderezos[i].id+' type="radio" class="sumarAderezos" name="options" id="option3" autocomplete="off"> + </label> </div> </div> '
resumen += '<div class="row resumenAderezos" id="'+data.aderezos[i].id+'" style="display:none"> <div class="col-3" > <img class="img-resumen" src='+data.aderezos[i].image+' alt=""> </div> <div class="col-4"> <h3 class="item-title"> '+ data.aderezos[i].nombre+'<h3> </div> <div class="col-2"><h3 id="'+data.aderezos[i].id+'" class="cantAderezos"> X 0 </h3></div> <div class="col-2"><h3 id="'+data.aderezos[i].id+'" class="precioAderezos"> 0 </h3></div> <div class="col-2"> </div></div>'
}
document.getElementById ("pantalla_4_items").innerHTML=aderezos
document.getElementById ("pantalla_5_hamburguesa").innerHTML=resumen
// //recibe evento al realizar click dentro del elemento que contiene la clase img
// $(".hamburguesa").click(function(){
// console.log("click")
// //comprobamos si existe una imagen seleccionada
// if ( $( ".hamburguesa" ).hasClass( "seleccionado" ) ) {
// /*en el caso que exista ya una imagen seleccionada la eliminamos para que únicamente solo se tenga una imagen seleccionada*/
// $(".hamburguesa").removeClass("seleccionado");
// }
// //añadimos la clase de la imagen seleccionada
// $(this).addClass("seleccionado");
// hamburguesasSeleccionada=$(this).attr('id')
// console.log(hamburguesasSeleccionada)
// });
// HAMBURGUESAS--------
function precioTotal(){
var precioTotal=0
for(let i=0;i<data.hamburguesas.length;i++) {
precioTotal=precioTotal+(data.hamburguesas[i].precio*cantHamburguesa[i+1])
}
for(let i=0;i<data.complementos.length;i++) {
precioTotal=precioTotal+(data.complementos[i].precio*cantComplementos[i+1])
}
for(let i=0;i<data.bebidas.length;i++) {
precioTotal=precioTotal+(data.bebidas[i].precio*cantBebidas[i+1])
}
for(let i=0;i<data.aderezos.length;i++) {
precioTotal=precioTotal+(data.aderezos[i].precio*cantAderezos[i+1])
}
var resultado='<h2> Precio Total:'+precioTotal+'<h2>'
document.getElementById ("pantalla_5_resultado").innerHTML=resultado
}
$(".sumarHamburguesa").click(function(){
cantHamburguesa[$(this).attr('id')]++
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorHamburguesa "+cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorHamburguesa").text(cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantHamburguesa").text(cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioHamburguesa").text(cantHamburguesa[$(this).attr('id')]*data.hamburguesas[$(this).attr('id')-1].precio)
if (cantHamburguesa[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenHamburguesa").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenHamburguesa").attr("style", "display:in-line")
}
})
$(".restarHamburguesa").click(function(){
if (cantHamburguesa[$(this).attr('id')]>0) {
cantHamburguesa[$(this).attr('id')]--
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorHamburguesa "+cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorHamburguesa").text(cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantHamburguesa").text(cantHamburguesa[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioHamburguesa").text(cantHamburguesa[$(this).attr('id')]*data.hamburguesas[$(this).attr('id')-1].precio)
if (cantHamburguesa[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenHamburguesa").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenHamburguesa").attr("style", "display:in-line")
}
}
})
// Complementos---------
$(".sumarComplementos").click(function(){
cantComplementos[$(this).attr('id')]++
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorComplementos "+cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorComplementos").text(cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantComplementos").text(cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioComplementos").text(cantComplementos[$(this).attr('id')]*data.complementos[$(this).attr('id')-1].precio)
if (cantComplementos[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenComplementos").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenComplementos").attr("style", "display:in-line")
}
})
$(".restarComplementos").click(function(){
if (cantComplementos[$(this).attr('id')]>0) {
cantComplementos[$(this).attr('id')]--
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorComplementos "+cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorComplementos").text(cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantComplementos").text(cantComplementos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioComplementos").text(cantComplementos[$(this).attr('id')]*data.complementos[$(this).attr('id')-1].precio)
if (cantComplementos[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenComplementos").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenComplementos").attr("style", "display:in-line")
}
}
})
//BEBIDAS-----------------------------------------
$(".sumarBebidas").click(function(){
cantBebidas[$(this).attr('id')]++
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorBebidas "+cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorBebidas").text(cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantBebidas").text(cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioBebidas").text(cantBebidas[$(this).attr('id')]*data.bebidas[$(this).attr('id')-1].precio)
if (cantBebidas[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenBebidas").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenBebidas").attr("style", "display:in-line")
}
})
$(".restarBebidas").click(function(){
if (cantBebidas[$(this).attr('id')]>0) {
cantBebidas[$(this).attr('id')]--
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorBebidas "+cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorBebidas").text(cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantBebidas").text(cantBebidas[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioBebidas").text(cantBebidas[$(this).attr('id')]*data.bebidas[$(this).attr('id')-1].precio)
if (cantBebidas[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenBebidas").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenBebidas").attr("style", "display:in-line")
}
}
})
// Aderezos-------------------
$(".sumarAderezos").click(function(){
cantAderezos[$(this).attr('id')]++
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorAderezos "+cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorAderezos").text(cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantAderezos").text(cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioAderezos").text(cantAderezos[$(this).attr('id')]*data.aderezos[$(this).attr('id')-1].precio)
if (cantAderezos[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenAderezos").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenAderezos").attr("style", "display:in-line")
}
})
$(".restarAderezos").click(function(){
if (cantAderezos[$(this).attr('id')]>0) {
cantAderezos[$(this).attr('id')]--
precioTotal()
console.log( "#"+[$(this).attr('id')]+".contadorAderezos "+cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".contadorAderezos").text(cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".cantAderezos").text(cantAderezos[$(this).attr('id')])
$("#"+[$(this).attr('id')]+".precioAderezos").text(cantAderezos[$(this).attr('id')]*data.aderezos[$(this).attr('id')-1].precio)
if (cantAderezos[$(this).attr('id')]==0){
console.log("cero")
$("#"+[$(this).attr('id')]+".resumenAderezos").attr("style", "display:none")
}
else{
console.log("cant>0")
$("#"+[$(this).attr('id')]+".resumenAderezos").attr("style", "display:in-line")
}
}
})
});
// --------------------------------------------
$("#btnIngresar").click(function(){
console.log("click boton")
$("#pantalla_0").attr("style", "display:none");
$("#pantalla_1").attr("style", "display:block");
$("#btnResumen").attr("style", "display:block");
})
$("#btnHamburguesa").click(function(){
console.log("click boton")
$("#pantalla_1").attr("style", "display:none");
$("#pantalla_2").attr("style", "display:block");
$("#btnResumen").attr("style", "display:block");
})
$("#btnComplementos").click(function(){
console.log("click boton")
$("#pantalla_2").attr("style", "display:none");
$("#pantalla_3").attr("style", "display:block");
$("#btnResumen").attr("style", "display:block");
})
$("#btnBebidas").click(function(){
console.log("click boton")
$("#pantalla_3").attr("style", "display:none");
$("#pantalla_4").attr("style", "display:block");
$("#btnResumen").attr("style", "display:block");
})
$("#btnAderezos").click(function(){
console.log("click boton")
$("#pantalla_4").attr("style", "display:none");
$("#pantalla_5").attr("style", "display:block");
$("#btnResumen").attr("style", "display:block");
})
$("#btnConfirmar").click(function(){
console.log("click boton")
$("#pantalla_5").attr("style", "display:none");
$("#pantalla_6").attr("style", "display:block");
$("#btnResumen").attr("style", "display:none");
})
$("#btnInicio").click(function(){
console.log("click boton")
$("#pantalla_6").attr("style", "display:none");
$("#pantalla_0").attr("style", "display:block");
})
$("#btnResumen").click(function(){
console.log("click boton")
$("#pantalla_0").attr("style", "display:none");
$("#pantalla_1").attr("style", "display:none");
$("#pantalla_2").attr("style", "display:none");
$("#pantalla_3").attr("style", "display:none");
$("#pantalla_4").attr("style", "display:none");
$("#pantalla_5").attr("style", "display:block");
$("#pantalla_6").attr("style", "display:none");
})
});
<file_sep>/AjaxDBase.js
async function readData(url,data = {}) {
// Default options are marked with *
const response = await fetch(url);
return response.json();
}
let productos=readData('dataBase/dataBase.JSON',"")
.then(data => {
console.log(data.hamburguesas);
data.hamburguesas
hamburguesas=''
for(let i=0;i<data.hamburguesas.length;i++) {
hamburguesas += '<div id="hamburguesa1" class="col-6 col-md-4 col-xl-3"> <div class="item shadow mb-4"> <h3 class="item-title"> $ '+ data.hamburguesas[i].nombre+' <img src='+data.hamburguesas[i].image+' alt=""> <div class="item-details"> <h4 class="item-price">'+ data.hamburguesas[i].precio+'</h4> </div> </div> </div>'
document.getElementById ("pantalla_1_items").innerHTML=hamburguesas
}
});
| 4af1c2f84b24c1b941abf34c85bbdd7eb93820cd | [
"JavaScript"
] | 2 | JavaScript | MateoEggel/Entrega-Final-JS | 21a0455fab31cc333abcf0a0a10fbb1b46eba630 | 59d6f8d6dea5a7e71a8b387e3580631c46b1728f |
refs/heads/master | <file_sep>package org.apache.sheff.util;
/**
* @Author sff
* @Description 获取组件的名称
* @Date 2021/6/16
**/
public class ComponentUtil {
public static String getComponentName(String fullClassName) {
String[] split = fullClassName.split("\\.");
return split[split.length-1];
}
public static String getComponentName(Object object) {
String fullClassName = object.getClass().getName();
return getComponentName(fullClassName);
}
public static void main(String[] args) {
String componentName = getComponentName("org.apache.catalina.startup.Bootstrap");
System.out.println(componentName);
}
private ComponentUtil() {
}
}
<file_sep>package sff.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author SFF
* @version 1.0.0
* @description
* @date 2021/5/7 - 22:30
*/
public class SffServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("test servlet");
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write("hello".getBytes());
}
}
<file_sep>package javax.test;
import org.eclipse.jdt.internal.compiler.classfmt.MethodInfoWithAnnotations;
/**
* @author SFF
* @version 1.0.0
* @description
* @date 2021/4/5 - 16:26
*/
public class TestJava {
public static void main(String[] args) {
}
}
<file_sep>base.path=D:\\Resource\\iTomcat\\lib | 3e3cdf2ae199e142909c7835ab86324a7ff1eda3 | [
"Java",
"INI"
] | 4 | Java | shengfangfang/iTomcat | 998fcb3b2b60c3a145216cae86ba9d35a13dc69e | dee5ec953d906ab4f66787af692b009bb31e83ce |
refs/heads/master | <file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
$threadName=$_SESSION['working_thread'];
$qref=$_SESSION['qref'];
require_once 'configuration.php';
mysqli_query($connectify,"UPDATE about_threads SET `last_qref`='$qref' WHERE `thread_name` = '$threadName' ");
header("location:index.php");
session_destroy();
?>
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
/**
* THis page just authenticates a valid existing user
*/
session_start();
require_once 'configuration.php';
$uname=$_POST['uname'];
$pwd=$_POST['pwd']; // TODO: Revisit here to implement hashing of pwd. // Also update the DB accordingly. (salting required??)
// Sending real passwords via POST operation is a txetbook security threat
//$mail=$_POST['userMail'];
//$num=mysql_result(mysql_query("SELECT COUNT(*) AS count FROM login_details WHERE `uname`='$uname' AND `pwd`='$pwd' "),0,"count");
$query=mysqli_query($connectify,"SELECT COUNT(*) AS countExists FROM login_details WHERE `uname`='$uname' AND `pwd`='$pwd' "); // TODO: (do salting here with the hashed pwd). AlsoRemember to hash+salt while registering newUser
$userValid=mysqli_fetch_array($query);
if(! $userValid['countExists']){
echo "** Are you kidding me?\n\n← These are Incorrect Login Credentials !";
return;
}
else{
$_SESSION['me']=$uname;// setting the SESSION ME variable
echo $userValid['countExists'].". Welcome ".$uname." :) ";
//header("location:index.php");
//return;
}
//echo " Total Valid user of ".$uname."/".$pwd." is: ".$userValid['countExists'];
?>
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
require_once 'configuration.php';
if(isset($_SESSION['working_thread'])){
$threadname = $_SESSION['working_thread'];
$oldqref = $_SESSION['qref'];
mysqli_query($connectify, "UPDATE about_threads SET `last_qref`= '$oldqref' WHERE `thread_name`='$threadname' ");
$_SESSION['qref']=1;
}
$currentThread = $_POST['postedThread']; /// ChangeTrack to a different Thread
$_SESSION['working_thread']=$currentThread;
if($result=mysqli_query($connectify,"SELECT last_qref FROM about_threads WHERE `thread_name`='$currentThread' ")) {
$row=mysqli_fetch_array($result);
$_SESSION['qref']=$row['last_qref'];
}
else echo "No qref data is found :(";
// echo "The thread ' $currentThread ' has been successfully loaded :)";
// header("location:index.php");
?>
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
// TODO: Think of a better way to do this. Better, if you can avoid this entirely
$admins = array( "IamADMIN","","superuser","root" );
?>
<file_sep>
______________________________________
INFORMATION ON HOW TO RUN?
--------------------------------------
The main is written here TestMainFlow (/SimpleMarkerPriceHandler/src/com/fx/marketprice/main/TestMainFlow.java)
Please execute the main from there.
______________________________________
DEPENDANCY
--------------------------------------
1. Concurrent API
______________________________________
HOW To Add New Mock DMA PRICE csv?
--------------------------------------
add new csv's in this path /SimpleMarkerPriceHandler/mockPrices/
______________________________________
HOW TO CHANGE THE COMMISION ALGO ?
--------------------------------------
Feel free to change the commission algo in AlgoForMarginCalcuation
(i.e. com.fx.marketprice.margin.AlgoForMarginCalcuation)
______________________________________
SAMPLE OUTPUT
--------------------------------------
.
.
.
The original Price received from DMA :
{Id:1110, CcyPair:EUR/JPY, Bid:119.61, Ask:119.91, TimeStamp:2020-09-21T12:01:02.110}
The original Price received from DMA :
{Id:1111, CcyPair:GBP/USD, Bid:1.25, Ask:1.256, TimeStamp:2020-09-21T12:01:02.112}
*******************************************
CURRENT SNAPSHOT (post margin)
*******************************************
{Id:1000001106, CcyPair:EUR/USD, Bid:1.09989, Ask:1.2001199999999999, TimeStamp:2020-09-21T12:01:01.001}
{Id:1000001111, CcyPair:GBP/USD, Bid:1.249875, Ask:1.2561256, TimeStamp:2020-09-21T12:01:02.112}
{Id:1000001110, CcyPair:EUR/JPY, Bid:119.598039, Ask:119.92199099999999, TimeStamp:2020-09-21T12:01:02.110}
______________________________________
FULL CONSOLE OUTPUT
--------------------------------------
Please see this file ./nohupOutput.txt
Thank you..
<file_sep># A percolation test gives a model to find a consistent crack in soil/metal/object.
It can also be tweaked to suggest, in how many more steps a suitable crack can be made with least cost.
#How to run
1. compile all java files in current directory. Note: they are not part of any packages.
2. do not compile (references directory)
3. execute the following in console>>
$ java PercolationVisualizer "percolation_test/input20.txt"
4. check the visual process for correctness
TODO: Yet to fix the backwash issue (when virtualHead and VirtualTail are linked, bleeding happens from the bottom of matrix).
//Guess I need to fix isFull() & open() both, when I have time.
#Dependency:
The module is dependent on the algs4.jar which can be found at http://algs4.cs.princeton.edu/code/algs4.jar
#Disclaimer
Assignment mentored by Professor <NAME>, Princeton University
The test suit was provided, (refer percolation_test/credits )
<file_sep># repo1
This repository contains some of the works that I've done.
Coming next:
A Chess App.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <chrono>
#include <iostream>
/* ----------------------------------------------------------
* WordCount
*
* SYNOPSIS: reads a file and outputs a list of the words in
* the file, and the number of times they occured.
* Optionally can list only the most common (top 'n') words.
* Words are delimited by whitespace; non-alphanumeric chars
* are ignored.
*
* This 'wordcount' takes either one or two arguments:
*
* $ wordcount.out < testdata.txt [<n>]
*
* ... where 'testdata.txt' is the file to read and count words
* from, and 'n' (optional) is the number of words to output.
*
* Compile with: g++ -o wordcount.out wordcount.cpp */
#define MAXWORDSIZE 128
#define MAXMAPSIZE 10000
constexpr bool isDebugMode = true;
/* We'll use an array of wordcount structs to store our
* running data. The array will be terminated by an 'empty'
* record, ie word[0] = 0; count = 0; */
struct wordcount {
char word[MAXWORDSIZE];
int count;
struct wordcount * next; // for seperate chaining on hash collision
};
wordcount * hashTable[MAXMAPSIZE] = {0};
int uniqueWords = 0;
unsigned int hashFunc(const char* word){
unsigned int hashVal = 0;
for (int i=0; i < strlen(word); ++i){
hashVal += i * i + word[i] * word[i]; // i^2 + c^2 // alternatively can use skip hash
}
return hashVal % MAXMAPSIZE; // the bucket id
}
/* ----------------------------------------------------------
* addWord adds the word 'word' to our 'words' array; either
* increments the count if it already exists, or reallocs the
* array to create enough space to append the new word.
* Assumes strlen(word) < MAXWORDSIZE */
// struct wordcount *addWord( struct wordcount *words, const char *word )
void addWord(const char *word )
{
auto hf = hashFunc(word);
if ( 0 == hashTable[hf] ) // unique word found
{
if (isDebugMode) std::cout << "DEBUG :: Unique word found" << std::endl;
uniqueWords++;
hashTable[hf] = new struct wordcount;
strcpy(hashTable[hf]->word, word);
hashTable[hf]->count = 1;
hashTable[hf]->next = NULL;
}
else // hash collision may or may not happened
{
auto ptr = hashTable[hf];
auto lastPtr = ptr;
while( ptr != NULL){
if (strcmp(ptr->word, word) == 0) // collision free location found
{
if (isDebugMode) std::cout << "DEBUG :: collision free location found" <<std::endl;
ptr->count++;
return;
}
if (isDebugMode) std::cout << "DEBUG :: OOPS! Collision happened ! " <<std::endl;
lastPtr = ptr;
ptr = ptr->next;
}
if (isDebugMode) std::cout << "DEBUG :: insert newly collided item at the end of the list" << std::endl;
uniqueWords++;
lastPtr->next = new struct wordcount; // (struct wordcount*) realloc(words, sizeof(*words)*(hf+2));
strcpy(lastPtr->next->word, word);
lastPtr->next->count = 1;
lastPtr->next->next = NULL;
}
}
struct wordcount * converter()
{
struct wordcount * result = new wordcount[uniqueWords+1];
for (int i=0, j=0; i < MAXMAPSIZE; ++i)
{
wordcount* ptr = hashTable[i] ;
while ( ptr != 0 )
{
result[j++] = *ptr;
ptr = ptr->next;
}
}
result[uniqueWords].count = 0;
return result;
}
/* ----------------------------------------------------------
* parseFile opens and reads the file named in 'filename'
* Words are extracted, delimited by whitespace; non-alphanum
* chars ignored. */
struct wordcount *parseFile()
{
struct wordcount *words = 0;
char curword[MAXWORDSIZE], *p;
int ch;
/* Create an empty wordcount list */
words = (struct wordcount*) malloc(sizeof(*words));
words->count = 0; words->word[0] = 0;
p = curword;
while ((ch = fgetc(stdin)) != EOF) {
if (isspace(ch) || ch == '\t' || ch == '\n' || ch == '\r') {
/* we've reached the end of a word (or not started one yet) */
if (p != curword) {
*p = 0;
// words = addWord( words, curword );
addWord( curword );
p = curword;
}
} else if (isalnum(ch)) {
/* it's a valid character. We truncate words that are too long */
if (p-curword < MAXWORDSIZE-1) *p++ = (char)ch;
}
/* we ignore all other characters */
}
if (p != curword) addWord(curword);
return converter();
}
int comparator( const void* left, const void * right)
{
return (((struct wordcount*) left)->count) < (((struct wordcount*) right)->count) ;
}
/* ----------------------------------------------------------
* Sorts the 'words' array in place, in reverse order (ie,
* highest count at the beginning) */
void sortWordsList( struct wordcount *words )
{
/* Use an insertion sort. qsort(3) would probably be quicker? */
qsort( words, uniqueWords, sizeof(struct wordcount), comparator);
}
/* ----------------------------------------------------------
* 'main': entry point
* Verifies and parses arguments
* Reads file and creates wordcount array
* Sorts array
* Prints results
* Cleans up
*/
int main( int argc, char *argv[] )
{
int n = 0, i;
struct wordcount *words = 0;
fscanf( stdin, "%u", &n );
if(n < 0) {
n = INT_MAX;
}
// auto start = std::chrono::high_resolution_clock::now();
/* Get the words list from the file */
words = parseFile(); // After profiling, I have found this consumes most of the time
// auto end = std::chrono::high_resolution_clock::now();
// auto mSecsSoFar = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
// std::cout << "ParseFile took: " << mSecsSoFar.count() << std::endl;
//start = std::chrono::high_resolution_clock::now();
/* sort the list of words */
sortWordsList(words);
//end = std::chrono::high_resolution_clock::now();
//auto mSecsSoFar2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
// std::cout << "sortWordsList took: " << mSecsSoFar2.count() << std::endl;
//start = std::chrono::high_resolution_clock::now();
/* print the top 'n' */
for (i = 0; i < n; i++) {
/* check if we've hit the end of the list */
if (words[i].count == 0) break;
printf("%d %s\n", words[i].count, words[i].word);
}
// end = std::chrono::high_resolution_clock::now();
// auto mSecsSoFar3 = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
// std::cout << "Printing " << n << " words took: " << mSecsSoFar3.count() << std::endl;
/* clean up */
free(words);
return 0;
}
<file_sep>package com.global.orderbook;
/** Part A.
* The solution
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author snehasys
*
*/
public class OrderBook {
private ConcurrentMap<Long, Order> orders; // key is orderId
private Map<Double, List<Long>> bidOrders; // Key is price, Value is list of orderIds which has same bid price, (NOTE: front orderId is the oldest order in the list)
private Map<Double, List<Long>> offerOrders; // " " "
public OrderBook() {
// The highest bid and lowest offer are considered "best", with all other orders stacked in price levels behind.
this.orders = new ConcurrentHashMap<>();
this.bidOrders = new TreeMap<>(Collections.reverseOrder()); // doubt: should this be concurrent too?
this.offerOrders = new TreeMap<>();
}
// (order additions are expected to occur extremely frequently)
public void addOrder(Order o) {
orders.put(o.getId(), o);
Map<Double, List<Long>> bidAskOrders = getBidAskMap(o.getSide());
if (bidAskOrders.containsKey(o.getPrice())) // same price quoted earlier
bidAskOrders.get(o.getPrice()).add(o.getId());
else
bidAskOrders.put(o.getPrice(), new ArrayList<>(Arrays.asList(o.getId())) );
}
// (order deletions are expected to occur at approximately 60% of the rate of order additions)
public boolean removeOrder(final long orderId)
{
Long id = Long.valueOf(orderId);
if (orders.containsKey(id)) {
orders.remove(id);
return true;
}
return false;
}
//(size modifications do not effect time priority)
public boolean modifyOrderSize(final long orderId, final long newSize)
{
Long id = Long.valueOf(orderId);
if (orders.containsKey(id)) {
orders.get(id).setSize(newSize);
return true;
}
return true;
}
private Map<Double, List<Long>> getBidAskMap(final char side){
return (side == 'B') ? bidOrders : offerOrders;
}
// • Given a side and a level (an integer value >0), return the price for that level (where level 1 represents the best price for a given side).
public double getBestPriceForLevel(final char side, final int level) {
Optional<Double> price = getBidAskMap(side).keySet().stream().skip(level - 1).findFirst();
if (price.isPresent())
return price.get();
return -1;
}
// • Given a side and a level return the total size available for that level
public long getTotalSizeForLevel(final char side, final int level) {
Optional<List<Long>> o = getBidAskMap(side).values().stream().skip(level - 1).findFirst();
if (!o.isPresent()) return 0;
long[] totalSize = { 0 };
o.get().stream().forEach(orderId -> {totalSize[0] += orders.get(orderId).getSize();});
return totalSize[0];
}
// • Given a side return all the orders from that side of the book, in level- and time-order
// NOTE: Assuming the time-order: the oldest order in same prices should be prioritized..
public List<Order> getAllOrdersSoFar(final char side) {
List<Order> output = new ArrayList<Order>();
getBidAskMap(side).values().forEach(groupedOrderIds -> {
groupedOrderIds.forEach(orderId -> {
if (orders.containsKey(orderId))
output.add(this.orders.get(orderId));
});
});
return output;
}
/** UNIT TESTS **
* TODO >> we should write a separate jUnit class for this, and add more regression
*/
public static void main(String[] args) {
// NOTE: need to enable this VM Args "-enableassertions", while compiling this file. Or all the test asserts will be ignored
OrderBook ob = new OrderBook();
ob.addOrder(new Order(767, 99.99, 'O', 80));
ob.addOrder(new Order(768, 93.94, 'B', 56));
ob.addOrder(new Order(769, 13.99, 'B', 84));
ob.addOrder(new Order(770, 77.5, 'O', 30));
ob.addOrder(new Order(771, 545.9, 'B', 78));
ob.addOrder(new Order(4767, 99.99, 'O', 81));
ob.addOrder(new Order(4768, 193.94, 'B', 65));
ob.addOrder(new Order(4769, 13.99, 'B', 40));
ob.addOrder(new Order(4770, 77.5, 'O', 30));
ob.addOrder(new Order(4771, 545.9, 'B', 78));
ob.addOrder(new Order(5767, 99.99, 'O', 80300060));
ob.addOrder(new Order(5768, 93.94, 'B', 9987000));
// System.out.println(ob.getBestPriceForLevel('B', 2));
assert (ob.getBestPriceForLevel('B', 2) == 193.9400);
// System.out.println(ob.getBestPriceForLevel('B', 1));
assert (ob.getBestPriceForLevel('B', 1) == 545.90000);
// System.out.println(ob.getBestPriceForLevel('O', 1));
assert (ob.getBestPriceForLevel('O', 1) == 77.5);
// System.out.println(ob.getTotalSizeForLevel('O', 2));
assert (ob.getTotalSizeForLevel('O', 2) == 80300221);
assert (ob.removeOrder(770) == true);
// System.out.println(ob.getAllOrdersSoFar('B').toString());
assert(ob.getAllOrdersSoFar('B').toString()
.equals( "[(771|545.9|B|78), (4771|545.9|B|78), (4768|193.94|B|65), (768|93.94|B|56), (5768|93.94|B|9987000), (769|13.99|B|84), (4769|13.99|B|40)]"));
// System.out.println(ob.getAllOrdersSoFar('O').toString());
assert(ob.getAllOrdersSoFar('O').toString()
.equals("[(4770|77.5|O|30), (767|99.99|O|80), (4767|99.99|O|81), (5767|99.99|O|80300060)]"));
assert (ob.removeOrder(770) == false);
assert (ob.removeOrder(5767) == true);
assert (ob.removeOrder(771) == true);
assert (ob.removeOrder(1) == false);
assert (ob.removeOrder(4767) == true);
assert (ob.removeOrder(5768) == true);
assert (ob.removeOrder(769) == true);
ob.show();
}
public void show() {
System.out.println("All->\t" + this.orders);
System.out.println("Bids->\t" + this.bidOrders);
System.out.println("Offer->\t" + this.offerOrders);
}
} // end of class
// ==================================== ==================================== ====================================
/* Part B
Q:
Please suggest (but do not implement) modifications or additions to the Order and/or OrderBook classes
to make them better suited to support real-life, latency-sensitive trading
*
* A:
The given solution has many limitations like:
1. It is relying on in memory hashMap for storing orders.
Given a very busy system with millions of incoming orders per minute, it may go out of memory pretty soon.
2. We can have multiple instance of the service running across various datacenters to accept orders. We need better mechanisms to handle that distributed model.
3. Some kind of persistence mechanism should be there in the code. Like any time-series based db like KDB, or sqlServer, or MongoDB
4. Only the top-30 bid/ask price is enough for caching each side. Rest can be moved to a relatively slower memory, because too low bids and too high asks are not useful to anyone (because the spread will be huge)..
5. There may be many data-race related untested edge case bugs left in the code.
6. What happens to very old orders? There should be some phase out mechanism provided, that will clear up say 5hr old stale orders.
7. Auditing the orders is missing, this may be a regulatory requirement to some regions, and not having that info may attract huge fine from the regulators (e.g. Dodd-Frank).
* */
<file_sep>from Enumerators import BOARD_SIZE
from Enumerators import CellDiagonalMovements
def isValidCell(cell: tuple):
if(cell[0] in range(0,BOARD_SIZE) and
cell[1] in range(0,BOARD_SIZE) ) :
return True
return False
def getAdjacentDiagonalCell(isKnight : bool,
strategy : CellDiagonalMovements,
currentCell : tuple,
count : int):
if(strategy == CellDiagonalMovements.PP):
if(not isKnight):
return (currentCell[0] + count, currentCell[1] + count)
else:
return ((currentCell[0] + 2*count, currentCell[1] + count),
(currentCell[0] + count, currentCell[1] + 2*count))
if(strategy == CellDiagonalMovements.MM):
if(not isKnight):
return (currentCell[0] - count, currentCell[1] - count)
else:
return ((currentCell[0] - 2*count, currentCell[1] - count),
(currentCell[0] - count, currentCell[1] - 2*count))
if(strategy == CellDiagonalMovements.PM):
if(not isKnight):
return (currentCell[0] + count, currentCell[1] - count)
else:
return ((currentCell[0] + 2*count, currentCell[1] - count),
(currentCell[0] + count, currentCell[1] - 2*count))
if(strategy == CellDiagonalMovements.MP):
if(not isKnight):
return (currentCell[0] - count, currentCell[1] + count)
else:
return ((currentCell[0] - 2*count, currentCell[1] + count),
(currentCell[0] - count, currentCell[1] + 2*count))
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
//if(!isset($_POST['whatever_blah'])) echo "<script>window.location = '../index0.php'</script>"; //if manually called, i.e not via POST method then kick the attempt
$id=$_POST['id'];
$editedQuestion=$_POST['editedQuestion'];
require '../configuration.php';
$safe_editedQuestion=mysqli_real_escape_string($connectify,$editedQuestion);
if(!mysqli_query($connectify,"UPDATE question SET `qcontext`='$safe_editedQuestion' WHERE `ref` = $id "))
echo "\n\n".$comment." /-> ".$id."\nSorry,\n That edit was totally Unsuccessful :( ";
?>
<file_sep>/**
*
*/
package com.fx.marketprice.margin;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.StampedLock;
import com.fx.marketprice.feed.Price;
/**
* @author snehasish
*
*/
public class MarginCalculator {
private static HashMap<String, Price> ccypairPrices = new HashMap<>();
// private static StampedLock lock = new StampedLock();
/**
*
*/
public MarginCalculator() {
}
/**
* @param args
*/
public static void recalculateMargin(final Price price) {
final var oldPrice = ccypairPrices.get(price.ccyPair);
// long stamp = lock.writeLock();
try {
if (oldPrice == null
|| (oldPrice != null && oldPrice.ts.isBefore(price.ts))) { // this operation is not atomic, todo..
System.out.println("\n The original Price received from DMA : \n" + price.toJson());
ccypairPrices.put(price.ccyPair,
AlgoForMarginCalcuation.calculate(price));
}
} finally {
// lock.unlockWrite(stamp);
}
}
public static final Price getMarginedPrice (final String ccyPair){
// var stamp = lock.readLock();
try {
return ccypairPrices.get(ccyPair);
} finally {
// lock.unlock(stamp);
}
}
}
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
$usr=$_POST['newUname'];
$usrMail=$_POST['newMail'];
$usrPwd=$_POST['newPwd'];
$retypedPwd=$_POST['retypePwd'];
//echo "I am at this page, thankyou \n".$usr."/".$usrMail."/".$usrPwd;
//////// password fields mismatch check ///////////////
if($usrPwd!=$retypedPwd){
echo "Given passwords do not match with each other.\n\n ** Please enter again carefully **";
return;
}
//THE TASKS:: retype the password, existing user or not? check string-length password; all in this php side
require_once "configuration.php";
/////////// User Name Availability Check ///////////
$temp=mysqli_query($connectify,"SELECT COUNT(*) AS exist FROM login_details WHERE `uname`='$usr' ");
$userImpossible=mysqli_fetch_array($temp);
if($userImpossible['exist'])
{
echo $userImpossible['exist'].") The User-name: '".$usr."' is already taken\n\n\t** Please try another **";
return;
}
/////////////// password length Check /////////////
$pwdLen=mb_strlen($usrPwd);
if ($pwdLen<6||$pwdLen>20){
echo "Sorry, the chosen ".$pwdLen." length password is unacceptable.\n\n Select between 6-20 characters.. ";
return;
}
////////////// since ALL GOOD(so far), so SEND THE USER-given-DATA TO MYSQL and TRY TO CREATE HIS ACCOUNT :P /////////
if(mysqli_query($connectify,"INSERT INTO login_details VALUES ('$usr', '$usrPwd' , '$usrMail' )"))
{
echo "You just created your account successfully with the following credentials :\n\n User : '".$usr
."'\n Email : '".$usrMail
."'\n\n *** Memorize your password and/or keep it safe ***";
$_SESSION['me']=$usr;// setting the SESSION ME variable
echo "\nsession.ME==".$_SESSION['me']."\n\n **Kindly REFRESH this PAGE**";
return;
}
echo "Exception catched, \n Fatal error";
?>
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
$id = $_POST['id'];
$editedAnswer = $_POST['edited_answer'];
//echo "\n\n".$comment."/".$id;
require_once "configuration.php";
$safelyEditedAnswer=mysqli_real_escape_string($connectify,$editedAnswer);
//echo $id;
//$x = mysql_result(mysql_query($connectify,"SELECT * FROM $tablename WHERE `sequence` = $id "),0,"context");
if( ! mysqli_query($connectify,"UPDATE responses SET `context`='$safelyEditedAnswer' WHERE `sequence` = $id "))
echo "\n\n".$editedAnswer." /-> ".$id."\nSorry,\nEdit Unsuccessful :( ";
//.. else echo "This edit was a total success";
?>
<file_sep><link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.min.js"> </script> <!//src=source>
<script src="jquery-ui.js"> </script>
<style>
.QspaceStyle {color:dark; border: 2px solid white; background-color: #BBBBFF; font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
.answerStyle {border-top: 1px solid grey; background-color: #eee; padding: 0.8em; padding-left: 0.1em; font-size: 100%;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:13px;}
.commentStyle {background-color: #ffff9f;border}
.timestampStyle {background-color: #ffffbf;}
</style>
<?php
session_start();
if(!isset($_SESSION['working_thread'])) echo "<script>window.location = 'qMan/index.php'</script>"; //if manually called, i.e not via POST method then kick that attempt
$currentThread=$_SESSION['working_thread'];
require_once 'configuration.php';
//print_r($_POST);
//echo $_POST['fetch_qref'];
//$qref= $_POST['fetch_qref'];
$qref_=$_SESSION['qref'];
$threadId=$_SESSION['working_thread_id'];
$reply= $_POST['thought'];
$messy=mysqli_real_escape_string($connectify,$reply);
//if($messy=="") $messy="< - - Skipped - - >";
if( $messy!=$_SESSION['prevEntry'] && $messy != "" ) //// Get into this block if skipped via #skipper button or NotEqual to previous entry/// AND restrict NULLs
{
// echo ''.$qref_.': </u><br/>';
$qref_=$qref_+1;
$ques=mysqli_query($connectify,"SELECT qcontext FROM question WHERE `ref`=$qref_");
$qref_adjusted=$qref_-1; //<------------------ fixit \/ fixed ;D
if(mysqli_query($connectify,"INSERT INTO responses VALUES ('','$threadId', '$messy',' **Leave your comments here**', now(), '$qref_adjusted')"))
{
// $currentTime=date(' Y-m-d H:i:s');
$currentTime=myDateTime();
$_SESSION['qref']="$qref_";
$ques_1 = mysqli_fetch_array($ques);
// while($ques_1 = mysqli_fetch_array($ques)){ //apparently useless, since just one time execution of the following "echo" command is required.. bleh bleh! :P
echo '<div class="answerStyle" title="You are not supposed to edit thoughts while on active thread, BUT, if you are so desperate, you may refresh this page"><i>'
.' <b>'.$reply
.'</b></div><div class="commentStyle" title="You are not supposed to put comments while on active thread, and if you are so determined, you may refresh this page" > ** </div>'
.'<div align="right" class="timestampStyle"><small></i>'.$currentTime.'</small><i></div>'
.'<div id="Qspace" class="QspaceStyle" title="Answer My Question, if it is worth of your time :)"><b><small>    ►'
.$ques_1['qcontext'].'</small><b></div>';
mysqli_query($connectify,"UPDATE about_threads SET `last_qref`='$qref_' WHERE `thread_id` = '$threadId' "); // saving private Ryan :P
// }
$_SESSION['prevEntry']=$messy; ///Saving for next reference, so that no two consecutive entries be the same, thus preventing multiple key hits.. :)
}
}
////////////////////////////////////// the Date_module ////////////////////////////////
function myDateTime(){ //time.php :)
//echo "The Time ";
$d=25;
//while($d>0){
$today= date('Y-m-d');
$hour= date ('H')+5; //print $hour.":::";
$min= date('i')+30;
$sec=date('s');
if ($min>59){
$min-=60; //min=min-60
$hour+=1;
}
if ($hour>24) {
$hour-=24;
}
if ($hour>12)
{ $hour-=12;
if($hour==12) return $today." ".$hour.":".$min.":".$sec." am"."\n"; //case when hour==24
else
return $today." ".$hour.":".$min.":".$sec." pm"."\n";
}
else {
if($hour==12) return $today." ".$hour.":".$min.":".$sec." pm"."\n";//case when hour==12
else
return $today." ".$hour.":".$min.":".$sec." am"."\n";
}
}
///////////////////////////
?>
<body onLoad="document.f1.thought.focus();">
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
require_once 'configuration.php';
if(isset($_SESSION['working_thread'])){ //// if there is an existing thread you are working on, then first save that thread's ongoing Qreference number
$threadName = $_SESSION['working_thread'];
$oldqref = $_SESSION['qref'];
mysqli_query($connectify,"UPDATE about_threads SET `last_qref`= '$oldqref' WHERE `thread_name`='$threadName' ");
}
// $newThread =
$newThread = $_POST['threadRequest'];
$pattern0=$threadName."→".$newThread; // making 't_$threadName_blah' kinda string for appending infront of asked newThreadnames/subThreadNames e.g. 'blah'
if(
mysqli_query($connectify, "INSERT INTO `about_threads` VALUES ('', '$pattern0', '1')")
) {
$_SESSION['working_thread']=$pattern0; // <------------ SET the currentThread as this new thread..
$_SESSION['qref']=1;
echo "New Thread: ' $pattern0 ' created successfully. :D\n Hope you enjoy your new session...";
return;
}
else echo "Sorry, I'm getting errors,\n--------------------------\n\n** Maybe \" $pattern0 \" already exists **\nOR\n**You are probably using whitespaces/special characters/empty Fields ** ";
<file_sep>from Enumerators import PlayerType
from Enumerators import BOARD_SIZE
from Piece import Piece
#############################################################
class ControllerEngine:
lastPlayed : PlayerType
chessBoardSize: int
pieces : Piece = [] #: list(Piece) # 4* BOARD_SIZE
def __init__(self): # constructor
self.chessBoardSize = BOARD_SIZE
self.lastPlayed = PlayerType.Black # so that white can start the game
#############################################################
#############################################################
#############################################################
#############################################################
class Player:
activePieces : Piece = []
playerType : PlayerType
#############################################################<file_sep>/**
*
*/
package com.fx.marketprice.feed;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import com.fx.marketprice.sub.FeedSubscriber;
/**
* @author snehasish
*
*/
public final class MockFxPriceFeed {
private static final String csvPath = "./mockPrices"; // TODO read it from a static config/xml file
private String topic;
/** ctor */
public MockFxPriceFeed(final String topicName) {
topic = topicName;
try (Stream<Path> paths = Files.list(Paths.get(csvPath))){
paths.filter(Files::isRegularFile)
.forEach(this::action);
} catch (IOException e) {
e.printStackTrace();
}
}
private void action(final Path path) {
try (Stream<String> lines = Files.lines(path)){
lines.forEach(msg -> {
new FeedSubscriber().onMessageUpdateCallback(topic, msg); // I'm sure there's better way to do this, but just for simplicity
});
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* naive Unittest
*/
public static void main(String[] args) {
new MockFxPriceFeed("Marketprice/Feed");
}
}
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
?>
<!doctype HTML>
<meta charset="UTF-8" />
<head>
<title>
Full Conversation
</title>
<div align="right">
<a href="*/.." title="My Checklist" align="right"><img src="images/home1.png" style="height:30px; width:25px;" /></a><i>
<a href='#↓' title="Go to Bottom of page" onClick="document.f1.thought.focus();">
<img src="images/down.jpg" style="height:20px; width:15px;" /></a>
</div>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.min.js"> </script> <!//src=source>
<script src="jquery-ui.js"> </script>
<style>
.hidden {display: none;}
</style>
</head>
<body>
<?php
$qref_=$_SESSION['qref'];
$currentThread=$_SESSION['working_thread'];
require_once 'configuration.php';
///<--- module getThreadID ---> ////////
$threadIdArray = mysqli_query($connectify,"SELECT thread_id FROM about_threads WHERE thread_name = '$currentThread' "); //GET the THREAD ID
$threadIdRow = mysqli_fetch_array($threadIdArray);
$threadId=$threadIdRow[0];
$_SESSION['working_thread_id']=$threadId; ////// <===== setting up a new session variable to put the Working-Thread-ID directly.. :P
require 'qMan/allAdmins.php';
if ( in_array($_SESSION['me'] , $admins, true )) ////////////////////////////////////////////////////////////////////////////////////////////////////////
{ ///////// ONLY ADMINS have the PRiVILeGE to EXECUTE THIS BLOCK Since it's has a DELETE BUTTON, which might be a destructive tool for REGULAR USERS ////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$result = mysqli_query($connectify,"SELECT * FROM responses,about_threads,question WHERE ref=qref AND thread_ref=thread_id AND thread_ref='$threadId' ORDER BY t_stamp");
$questionNumber = 1;
while($value = mysqli_fetch_array($result)){
//foreach ($data as $key => $value) {
//echo $value['sequence'].' :: '.$value['context'].'<a class="delete">◄</a>'.'<br/>';
echo '<div id="Qspace1" class="QspaceStyle"><b><small>  '.$questionNumber.' ►'
.$value['qcontext'].'</b> </small></div>' //<--The question field
.'<div class="answerStyle"> <i><style>a:link {color:#4E388D;}a:hover {color:#088FDD;}</style>'
.'<a href="#" class="del" title="Delete This Entry" rel="'.$value['sequence'].'">█</a>  ' //<----- The delete link
//.'<a name="#" class="edit" title="Edit Entry" rel="'.$value['sequence'].'">E▄</a>' //<----- The BOGUS edit link :P
.'<b><div3 id="'.$value['sequence'].'" title="click to Modify, click away to save" >'.$value['context'] // <------------- the REAL user response (EDITABLE)
.'</div3></div></b></i><small><div class="commentStyle"><div1 id="'.$value['sequence'].'" title="Click to Comment, Click away to save" >'
.$value['comment'].' .</b></div1></div>' //<--corresponding futureUserResponse aka comment field
.'<div id="yellowfield" align="right" class="timestampStyle">'.$value['t_stamp'].'</small><i></div>'; //<--The timestamp field
//.'<br/>';//.'<hr>';
$questionNumber++;
}
$lastquestion = mysqli_query($connectify,"SELECT qcontext FROM question WHERE `ref`=$qref_");
while($value2 = mysqli_fetch_array($lastquestion)){
echo '<b><div id="Qspace" class="QspaceStyle"><small>    ►'
.$value2['qcontext'].'</b> </small></div><a name="↓"> </a> </div>'; // <!--<<<------the bottom Anchor---- -->
}
}
else /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ /////// FOR NON-ADMIN USERS /////////////////////////////// LESS POWER MAKES YOU LESS RESPONSIbLE ;) :) ;) //////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$result = mysqli_query($connectify,"SELECT * FROM responses,about_threads,question WHERE ref=qref AND thread_ref=thread_id AND thread_ref='$threadId' ORDER BY t_stamp");
$questionNumber = 1;
while($value = mysqli_fetch_array($result)){
//foreach ($data as $key => $value) {
//echo $value['sequence'].' :: '.$value['context'].'<a class="delete">◄</a>'.'<br/>';
echo '<div id="Qspace1" class="QspaceStyle"><b><small>  '.$questionNumber.' ►'
.$value['qcontext'].'</b> </small></div>' //<--The question field
.'<div class="answerStyle"> <i><style>a:link {color:#4E388D;}a:hover {color:#088FDD;}</style>'
.'  ' //<----- The disabled delete link
.'<b><div3 id="'.$value['sequence'].'" title="click to Modify, click away to save" >'.$value['context'] // <------------- the REAL user response (EDITABLE)...
.'</div3></div></b></i><small><div class="commentStyle"><div1 id="'.$value['sequence'].'" title="Click to Comment, Click away to save" >'
.$value['comment'].' .</b></div1></div>' //<--corresponding futureUserResponse aka comment field
.'<div id="yellowfield" align="right" class="timestampStyle">'.$value['t_stamp'].'</small><i></div>'; //<--The timestamp field
//.'<br/>';//.'<hr>';
$questionNumber++;
}
$lastquestion=mysqli_query($connectify,"SELECT qcontext FROM question WHERE `ref`=$qref_");
while($value2 = mysqli_fetch_array($lastquestion)){
echo '<b><div id="Qspace" class="QspaceStyle"><small>    ►'
.$value2['qcontext'].'</b> </small><a name="↓"> </a> </div>'; // <!--<<<------the bottom Anchor---- -->
}
}
//echo '<pre>';
//print_r($data);
?>
<script>
<!--// Begin scripting
function divClicked() { ////////////////////////////////////////////--->>> helps put a comment
var divHtml = $(this).html(); //capture the div1's content
$('html, body').animate({ scrollTop: $(this).offset().top-50}, 1000);
var sequence = $(this).attr('id');
var editableText = $("<textarea rows='1' cols='40' title='Click away to save' onFocus='this.select()' id='"+sequence+"' />");
editableText.val(divHtml);
$(this).replaceWith(editableText); //replaceWith is a very handy command, monsieur .. :D
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
function editableTextBlurred() { ////////////////////////////////////////////--->>> helps put a comment
var id3=$(this).attr('id');
var html = $(this).val();
$.post("ajaxCommentPost.php",{'id' : id3,'comment' : html}, function(data){
if(data) alert(data);
//document.write(id);
//alert(item);
});
var viewableText = $("<div1 id='"+id3+"' >");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(divClicked);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function divClicked3() { ////////////////////////////////////////////--->>> helps edit an Answer, a.k.a. Response
var divHtml = $(this).html(); //capture the div3's content
$('html, body').animate({ scrollTop: $(this).offset().top-250}, 1400);
var sequence = $(this).attr('id');
var editableText = $("<textarea rows='1' cols='60' title='Click away to save' id='"+sequence+"' />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred3);
}
function editableTextBlurred3() { ////////////////////////////////////////////--->>> helps edit an Answer, a.k.a. Response
var id3=$(this).attr('id');
var html = $(this).val();
$.post("ajaxEditAnswer.php",{'id' : id3,'edited_answer' : html}, function(data){
if(data) alert(data);
//document.write(id);
//alert(item);
});
var viewableText = $("<div3 id='"+id3+"' >");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(divClicked3);
}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$(document).ready(function()
{
$("div1").click(divClicked); /////////////////////////////////////////--->>> helps put a comment
$("div3").click(divClicked3); /////////////////////////////////////////--->>> helps edit an Answer, a.k.a. Response
// $('html, body').animate({ scrollTop: $("#gotop").offset().top }, 3000);
$('.del').click(function(){
var item = $(this).parent();
var id = $(this).attr('rel');
$.post("ajaxDelete.php",{'id' : id}, function(data){
// alert(data);
//document.write(id);
//alert(item);
$(item).hide();
$('html, body').animate({
scrollTop: $(".del").offset().top
}, 1000);
});
});
$(function(){
//"--------------------------------------------------"///// THE INFO PAGE
$("#dialog-about").dialog({autoOpen : false,
draggable: true, height : 540, width : 490, modal : true, position : ['top',35] ,
// puff, bounce, drop, highlight, blind, size, fold, explode,pulsate,shake,
show : "fold", hide : "drop",
buttons:
{
"Get it? Now go back to what you were doing..": function(){
$(this).dialog("close");
}
}
});
/*
$('.edit').click(function(){
var item = $(this).parent();
id1 = $(this).attr('rel');
$( "#dialog-about" ).dialog( "open" );
});
*/
//==================================================
$( "#about" ).button().click(function() {
$( "#dialog-about" ).dialog( "open" );
});
});
});
// End Scripting -->
</script>
<div id="dialog-about" title="Well, I am your Checklist.. " class='hidden'>
<small>
<p>
Often one faces a situation /challenge in design, where it is difficult to <u> identify their problems</u> with the existing products, except those which are apparent and obvious. This failure converts the creative task of problem solving into the routine exercise of solving mechanically framed design problems. Even if the important problem is identified and solved, it is not <b> unusual</b> to find that when the design is almost finalized, one gets ideas about the other problems, which could have been solved <b>together</b>, without adding to <u>design time and cost</u>.
</p>
<p>This checklist of yours, is an <b>aid</b> to explore the problem from many sides. The list is general in nature and has been worked out on the basis of experience of developing products in wide range of fields, from the consumer appliances to industrial products.
</p> <p>
In fact <u><b>in no case all the questions will be relevant.</b></u> Look for your possible goals in designing and pick up the questions from the collection. Edit them to suit the type of problems you are handling. Questions asked and replied with an open mind can give you <b>CLUE</b>'s to the <u>valid and rational change</u> that you were <b>looking for</b>.
</p> <p>
The checklist is by no means, the end of your problem explorations, but only a <b>beginning</b>. To get an effective solution, you must explore the effective way, of looking at the problem, and spot the problem that has eluded notice so far. This transforms the routine task of collecting data into a <b>creative search</b> for a different way of <u>looking at the problem situation</u>. Effective solutions will emerge only if the <b>problems are framed correctly</b>.
</p>
</small>
</div>
</body>
</HTML>
<file_sep># Info
A limit order book stores customer orders on a price time priority basis.
The highest bid and lowest offer are considered "best" with all other orders stacked in price levels behind. The best order is considered to be at level 1.
* A simple way to provide efficient and bare minimum limit order book capabilities.
<file_sep>import enum
BOARD_SIZE = 8
PlayerType = enum.Enum('PlayerType', 'Black White', start = 3 , module=__name__)
class PieceType(enum.Enum):
Rook = enum.auto()
Knight = enum.auto()
Bishop = enum.auto()
Queen = enum.auto()
King = enum.auto()
Pawn = enum.auto()
MovementBehavior = enum.Enum('MovementBehavior', 'AcrossMove DiagonalMove KnightMove QueenMove KingMove PawnMove' , start = 1, module=__name__)
'''
* There are 4 diagonal scenarios from any particular location.
* namely: ++, --, +-, -+
'''
CellDiagonalMovements = enum.Enum('CellDiagonalMovements', 'PP MM PM MP', start = 1 , module=__name__)
##############################################################
def UT1():
print(list(PlayerType))
print(list(PieceType))
print(list(MovementBehavior))
##############################################################
if __name__ == '__main__':
UT1()<file_sep>import os, sys
import pygame
from pygame.locals import * # MOUSEBUTTONDOWN
from pygame import font as pygame_font
from Enumerators import BOARD_SIZE
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
BROWN = (100, 73, 60)
GREY = ( 50, 50, 50)
LGREY = (150, 150, 150)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
screenResolution = width, height = 1280, 1024 #320, 240
speed = [5, 5]
screen = pygame.display.set_mode( screenResolution, 0, 32) # TODO: make it 32, for high quality images
pygame.display.set_caption('Offline Chess -created by snehasys')
pygame_font.init()
f = pygame_font.Font(None, 20)
s = f.render("foo", True, [0, 0, 0], [255, 255, 255])
#############################
class Rectangle:
def __init__(self, pos, color, size):
self.pos = pos
self.color = color
self.size = size
def draw(self):
pygame.draw.rect(screen, self.color, Rect(self.pos, self.size))
#############################
def drawChessBoard():
box = (height-40)/BOARD_SIZE
border = 3
offset_r = offset_c = 20
row = column = BOARD_SIZE
printWhite = False
screen.fill(GREY) #// App background
rectangles:Rectangle = []
while row:
column = BOARD_SIZE
offset_c = 20
while column:
if(printWhite): _color = WHITE
else: _color = BROWN
_pos = (int(offset_r), int(offset_c)) #(randint(0,height), randint(0,width))
_size = (box - border, box - border)#(639-randint(random_pos[0], 639), 479-randint(random_pos[1],479))
rectangles.append(Rectangle(_pos, _color, _size))
printWhite = not printWhite # Toggle
offset_c += box #760/BOARD_SIZE -10
column -= 1
printWhite = not printWhite
offset_r += box #1000/BOARD_SIZE
row -= 1
pygame.draw.rect(screen, BLACK, Rect(15, 15, box*BOARD_SIZE+border, box*BOARD_SIZE+border), 10) #// Chessboard border
# pygame.draw.rect(screen, WHITE, Rect(box*BOARD_SIZE+border+40, 5, (box*BOARD_SIZE)/4, (box*BOARD_SIZE)/2), 1) #// Scoreboard border
screen.lock()
for rectangle in rectangles:
rectangle.draw()
screen.unlock()
#############################
def bounceMe(chessPiece_img, howManyTimes:int):
chessPiece_rect = chessPiece_img.get_rect()
running = True
clock = pygame.time.Clock()
while running: #howManyTimes:
# This limits the while loop to a max of 10 times per second.
clock.tick(60) #a.k.a 60fps
pygame.mouse.set_visible(True)
for event in pygame.event.get():
try:
#print (event)
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
elif event.type == KEYDOWN and event.scancode == 1:
running = False #pygame.display.quit() # TODO show a exit warning on gamescreen
elif event.type == KEYDOWN:
print (event)
elif event.type == MOUSEBUTTONDOWN:
print (event)#.button, event.pos)
chessPiece_rect.left = event.pos[0]
chessPiece_rect.bottom = event.pos[1]
screen.blit(chessPiece_img, (event.pos))
pygame.display.flip()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
#screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
except:
pass #ignore the exception
# chessPiece_rect = chessPiece_rect.move(speed)
# if chessPiece_rect.left < 0 or chessPiece_rect.right > width:
# speed[0] = -speed[0]
# if chessPiece_rect.top < 0 or chessPiece_rect.bottom > height:
# speed[1] = -speed[1]
# screen.fill(BLACK)
drawChessBoard()
screen.blit(chessPiece_img, chessPiece_rect)
f = pygame_font.Font(None, 50)
s = f.render("\n" +' '*int(width/10) +"Score:", False, [200, 200, 200], None)
font_surface = s.get_rect()#.move(speed)
screen.blit(s, font_surface)
pygame.display.flip()
pygame.display.quit()
knight = pygame.image.load( os.path.join("Chess_Project","images", 'w_k.png')) #r'C:\\00_GitHub\\repo1\\Chess_Project\\images\\w_k.png'
smallKnight = pygame.transform.scale(knight, (75,120))
if __name__ == "__main__":
#bounceMe(ball, 1000)
bounceMe(smallKnight, 1000)
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
$hostName='localhost';
$user='snehasys';
$password='<PASSWORD>';
$DBname='dcl';
// Create connection
$connectify=mysqli_connect( $hostName , $user , $password , $DBname );
// Check connection
if (mysqli_connect_errno($connectify))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
$con = mysql_connect("localhost","snehasys","snehas","dcl");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("USE test",$con);
/*
$config =array();
$config['host'] = 'localhost';
$config['user'] = 'root';
$config['pass'] = '';
$config['table'] = 'test';
$config =array();
$config['host'] = 'localhost';
$config['user'] = 'snehasys';
$config['pass'] = '<PASSWORD>';
$config['table'] = 'test';
include 'mysqli.class.php';
$DB = new DB($config);
*/
?>
<file_sep>
<!doctype>
<html>
<meta charset="UTF-8" />
<center>
<head>
<title>All Threads</title>
<div align='right'> <small><i><b>
<a href='logMeOut.php' title='Log Me Out' class='logoutStyle' style='border: 3px solid white;background-color: #088fff;color: white'>←Logout▬</a> </b></i></div>
<a href='*/..' title='Go top Checklist Page'><img src='images/Checklist_assistant_home.jpg'/></a><br/><br/><br/>
<div id='bunchOfThreads' >
<button id='fork'>Create new rooted Thread</button>
<b><br/><br/> Or <br/>Browse any </b>
<link rel="stylesheet" href="jquery-ui.css" />
<?php ////______________________________________________//////////////////////////
//// THIS is the THREAD selection/creation PAGE.. //////////////////////////
////______________________________________________//////////////////////////
session_start();
print_r($_SESSION);
if(!isset($_SESSION['me'])) echo "<script>window.location = 'frontpage.php'</script>"; //if Invalid user, kick him/her to login page
$currentUserName=$_SESSION['me'];
$pattern0=$currentUserName."_";
$pattern=$pattern0."%"; // cooking up the wildcase search pattern for populating thread files
//echo $pattern0;
require 'qMan/allAdmins.php';
if ( in_array($_SESSION['me'] , $admins, true )) $pattern="%" ; ///////////// GIVES ADMINs THE PRIVILEGE to SNOOP into ALL USER's CHECKLISTS
include 'configuration.php';
$result=mysqli_query($connectify,"SELECT `thread_name` FROM about_threads WHERE `thread_name` LIKE '$pattern' ORDER BY `thread_name`");
////THE TABLE >>>>>>>>
echo "<table border='1' id='table1' rel='".$_SESSION['me']."' class='curvedEdges'> <tr><th> $currentUserName 's Threads </th></tr><tr><td>";
//$columnName="Tables_in_".$DBname." (".$pattern.")"; echo "\n".$columnName; //all this trouble for naming as "Tables_in_test (res%)" :P
$prevrow="EMPTY";
while($row = mysqli_fetch_row($result)){
$isSubset=strpos($row[0], $prevrow );
echo "<ul>";
if($isSubset=== false) echo "<hr/></ul><li>";
else echo "<li>";
echo "<a href='#' class='threads' rel='".$row[0]."' > ".$row[0]."</a>";
//
if($isSubset=== false) {
echo " <input type='button' id='".$row[0]."' class='subThreadButtons' value='Create Sub Thread'/>";
$prevrow=$row[0];
}
else {echo "</li></ul>";}
}
echo "</td></tr></table>";
echo "</div>";
/*
mysqli_query($connectify,"DROP TABLE ".$tablename.'_bak');
mysqli_query($connectify,"RENAME TABLE $tablename TO ".$tablename.'_bak');
mysqli_query($connectify, "CREATE TABLE $tablename ( sequence INT(5) NOT NULL AUTO_INCREMENT
, context VARCHAR(300) , comment VARCHAR(300)
, t_stamp DATETIME , qref INT(4)
, primary key(sequence), foreign key(qref) references question(ref) )");
echo $tablename.' table created/recreated successfully, hope you do know what you are doing...';
*/
//$DB->Query(" CREATE TABLE response1 ( sequence INT(5) NOT NULL AUTO_INCREMENT , context VARCHAR(50), primary key(sequence) );");
?>
<!-- CSS goes in the document HEAD -->
<style type="text/css">
table.curvedEdges { border:10px solid DodgerBlue;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px; }
table.curvedEdges th { border-bottom:1px dotted black; border-color: #666666; background-color: #bbbbff; padding:10px; }
table.curvedEdges td { color: green;border-bottom:1px dotted white; background-color: #ffffdf; padding:2px; }
.logoutStyle {color:dark; border: 4px solid white; background-color: #BBBBFF; font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
</style>
<script src="jquery-1.9.1.min.js"> </script> <!//src=source>
<script src="jquery-ui.js"> </script> <!the ui >
<script>
$(document).ready(function() {
$('#bunchOfThreads').draggable();
$('.subThreadButtons').click(function(){
var newThread2=$(this).attr('id');
$.post('threadSelect.php',{'postedThread' : newThread2 }, function(data){
if(data) alert(data);
// window.location.replace('*/..');
});
$( "#newThread" ).dialog( "open" );
getElementById('preThreadName').value= "newThread2";
});
$('.threads').click(function(){
// threadSelect(){
var thread=$(this).attr('rel');
$.post('threadSelect.php',{'postedThread' : thread }, function(data){
document.write("<h1>Loaded Successfully</h1>");
if(data) alert(data);
window.location.replace('*/..').delay(6000);
});
});
$("#newThread").submit(function(){
$.post('newThreadCreate.php',$('#newThread').serialize() ,function(data){
alert(data);
window.location.replace("*/..");
});
return false;
});
$(function(){
//"--------------------------------------------------"///// THE INFO PAGE
$("#newThread").dialog({autoOpen : false,
draggable: true, height : 190, width : 410, modal : true, position : ['top',250] ,
show : "size", hide : "size"}); // puff, bounce, drop, highlight, blind, size, fold, explode,pulsate,shake,
//==================================================
$( "#fork" ).button().click(function() {
var newThread2=$('#table1').attr('rel');
$.post('threadSelect.php',{'postedThread' : newThread2 }, function(data){
if(data) alert(data);
// window.location.replace('*/..');
});
$( "#newThread" ).dialog( "open" );
});
});
});
</script>
<body>
<div id="NewThread" title='Create thread' >
<form id='newThread' name='f1'>
<input type='text' size='25' maxlength='20' id='preThreadName' placeholder='New Thread Name' name='threadRequest' pattern="[A-Za-z0-9_$]+" title='no special characters(but _ $) or spaces are allowed as ThreadNames'/> <!// the valid thread pattern >
<input type='submit' value='GO' title='Create'/>
<input type='reset' value='<' title='Flush the Box' />
<img src='images/Checklist_assistant.jpg'/><br/>
<! Soon in here the radio buttons are coming :D >
</form>
</div>
<br/></br>
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
</body>
</html>
<file_sep>/**
*
*/
package com.fx.marketprice.sub;
/**
* @author snehasish
*
*/
public class MarginSubscriber implements ISubscriber {
private final String myTopic = "Marketprice/Margin";
/**
*
*/
public MarginSubscriber() {}
/* (non-Javadoc)
* @see com.fx.marketprice.ISubscriber#onMessageUpdate(java.lang.String)
*/
@Override
public void onMessageUpdateCallback(final String topic, final String marginUpdate) {
if (!topic.equalsIgnoreCase(myTopic))
return;
// got a new marginUpdate
// System.out.println("\n Received new marginUpdate, replacing old one for same ccyPair -> \n" + marginUpdate); // just displaying the received message in standard console for now
}
}
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
/** Summary:
* This page is constructing the question matrix
* TODO: more work required on the Acyclic Graph mapping of the questions,
* and the datastructure behind it. Increase the question depths.
* Try to introduce weightage of each path.
*
*/
session_start();
if(!isset($_SESSION['me'])) echo "<script>window.location = '../frontpage.php'</script>"; //if not valid user kick him to login page
print_r($_SESSION);
require 'allAdmins.php'; ///////// ONLY ADMINS ARE ALLOWED IN THIS PAGE /////////////
if (! in_array($_SESSION['me'] , $admins, true )) {
echo "<h2 style='color: RED;' > <br/><br/>** This is Unauthorized, Access DENIED **<h2>";
return;
}
require '../configuration.php';
echo "<table border='1' class='curvedEdges'>
<th>blockID</th><th title='In descending Order, seperated by slashes / .'>Next Block Priority</th>";
$tableRows2Darray=mysqli_query($connectify,"SELECT * FROM `qmatrix`");
while ($tableRows = mysqli_fetch_array($tableRows2Darray ) )
{
echo "<tr><td rel='readOnly' style='color: #555'>". $tableRows['qblockid']."</td><b><td rel='". $tableRows['qblockid'] ."'title='In descending Order, seperated by slashes / .' style='background-color: green;'>".$tableRows['nextblockpriority']."</td></b></tr>";
}
echo "</table>";
?>
<style type="text/css">
table.curvedEdges { border:10px solid Brown;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px; }
table.curvedEdges th { color: white;border-bottom:1px dotted black; border-color: #666666; background-color: #800; padding:10px; }
table.curvedEdges td { color: white;border-bottom:1px dotted white; background-color: #ffffdf; padding:2px; }
.logoutStyle {color:dark; border: 4px solid white; background-color: #BBBBFF; font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
</style>
<script src="../jquery-1.9.1.min.js"> </script> <!//src=source>
<script>
function tdClicked() { ////////////////////////////////////////////--->>> helps edit an Answer, a.k.a. Response
if ($(this).attr('rel') == 'readOnly') return;
var divHtml = $(this).html(); //capture the div3's content
var QblockID = $(this).attr('rel');
var editableText = $("<input type='text' size='16' title='** BE Very CAREFUL, Do NOT PUT anything but valid BlockIDs and slashes** Put data,In descending Order, seperated only by slashes / . Then Click away to save' rel='"+QblockID+"' />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textbox
editableText.blur(editableTextBlurred);
}
function editableTextBlurred() { ////////////////////////////////////////////--->>> helps edit an Answer, a.k.a. Response
var html = $(this).val();
var id4 =$(this).attr('rel');
$.post("ajaxEditQmatrix.php",{'block_id' : id4 ,'new_priorities' : html}, function(data){
if(data) alert(data);
//document.write(id);
//alert(item);
});
var viewableText = $("<td style='background-color: #f22;' >");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(tdClicked);
}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$(document).ready(function(){
$("td").click(tdClicked); /////////////////////////////////////////--->>> helps editing a Block priority
$('#newBlockCreate').submit(function(){
$.post('ajaxQblockCreate.php',$('#newBlockCreate').serialize(), function(data){
if(data) alert(data);
});
return false;
});
});
</script>
<div id='newBlockCreate'>
<form name='f1'>
<input type='submit' value='create'/>
</form>
</div>
<file_sep>
package com.fx.marketprice.sub;
import java.lang.String;
/**
* @author snehasish
*
*/
public interface ISubscriber {
void onMessageUpdateCallback (final String topic, final String msg);
}
<file_sep>package com.fx.marketprice.feed;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// a very basic naive POJO // avoiding getter/setters just to keep the solution small.
public class Price {
public Integer id;
public String ccyPair;
public Double bid;
public Double ask;
public LocalDateTime ts;
public Price(final String s) {
String [] data = s.split(",");
if (data.length != 5)
System.out.println("illegal csv line: " + s); // TODO: enrich & improve this validation logic, use async loggers
else {
id = Integer.parseInt(data[0]);
ccyPair = data[1]; // TODO may add a ccypair validator
bid = Double.parseDouble(data[2]);
ask = Double.parseDouble(data[3]);
ts = LocalDateTime.parse(data[4], DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss:SSS"));
}
}
public String toJson() { // Better if we are using well tested libs like jackson/Gson etc
var sb = new StringBuilder(" {");
sb.append("Id:"); sb.append(id);
sb.append(",\tCcyPair:"); sb.append(ccyPair);
sb.append(",\tBid:"); sb.append(bid);
sb.append(",\tAsk:"); sb.append(ask);
sb.append(",\tTimeStamp:"); sb.append(ts);
sb.append("} ");
return sb.toString();
}
}
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
print_r($_SESSION);
if(!isset($_SESSION['me'])) echo "<script>window.location = '../frontpage.php'</script>"; //if not valid user kick him to login page
require 'allAdmins.php'; ///////// ONLY ADMINS ARE ALLOWED IN THIS PAGE /////////////
if (! in_array($_SESSION['me'] , $admins, true )) {
echo "<h2 style='color: RED;' > <br/><br/>** This is Unauthorized, Access DENIED **<h2>";
return;
}
?>
<!doctype>
<HTML>
<meta charset='utf-8'/>
<title>Interact With Questions</title>
<head>
<body>
<h1 style="color: #AABBCC; "><center>Backbone Questions</center><hr/></h1>
<script src="../jquery-1.9.1.min.js"> </script> <!//src=source>
</head>
<style>
.QspaceStyle {color:DarkBlue; border: 3px solid white;background-color: #BBCCDD; padding: 5px; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
</style>
<script>
function divClicked() { ////////////////////////////////////////////--->>> helps edit a question
var divHtml = $(this).html(); //capture the div2's content
$('html, body').animate({ scrollTop: $(this).offset().top-250}, 1000);
var sequence = $(this).attr('id');
var editableText = $("<input type='text' size='63' maxlength='200' title='Click away to save' id='"+sequence+"' />");
editableText.val(divHtml);
$(this).replaceWith(editableText); //replaceWith is a very handy command, monsieur .. :D
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
function editableTextBlurred() { ////////////////////////////////////////////--->>> helps edit a question
var id2=$(this).attr('id');
var html = $(this).val();
$.post("ajaxQedit.php",{'id' : id2,'editedQuestion' : html}, function(data){
if(data) alert(data);
//document.write(id2);
});
var viewableText = $("<div2 id='"+id2+"' >");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(divClicked);
}
function check(stuff) {
var selectedBlockFromDropdown=stuff.options[stuff.selectedIndex].value;
document.getElementById('block_id').value=selectedBlockFromDropdown;
}
$(document).ready(function() {
$("div2").click(divClicked); /////////////////////////////////////////--->>> helps edit a question
$("#form1").submit(function() {
$.post('ajaxQpost.php',$('#form1').serialize(), function(data){
($('#appended').append("<div title='Refresh this page to edit this question' class='QspaceStyle'><b>"+data+"</div>"));
$('html, body').animate({
scrollTop: $("#appended").offset().top
}, 3500);
document.getElementById('nQF').select();
// alert(data);
});
return false;
});
});
</script>
<?php
require '../configuration.php';
$result = mysqli_query($connectify,'SELECT * FROM question order by qblock,ref');
while($line = mysqli_fetch_array($result)){ ///// <--------------- shows all the questions....
echo '<div id="Qspace" class="QspaceStyle">'.$line['ref'].'→ <div2 id="'.$line['ref'].'" >'.$line['qcontext'].'</div2></div>';
}
// $i=$i+1;
//----------------------------------------------------------------------
echo "<div id='appended' style='color: RED'> </div>";
$query = mysqli_query($connectify,"SELECT DISTINCT qblockid FROM qmatrix "); // Run your query
echo '<i></small><b><div style="color:RED;">Select your block within all existing blocks :-->> </i></small>
<select id="list" name="dropdown" value="b_id" onChange="check(this);" >
<option value="">Select</option>'; // Opens the drop down box
// Loop through the query results, outputing the options one by one
while ($row = mysqli_fetch_array($query)) { /// populating the dropdown...
echo "<option value='".$row[0]."' >".$row[0]."</option>";
}
echo '</select>';// Close your drop down box
?>
<form id="form1" name='f1'>
<label>Block ID</label>
<input type='text' size="1" id='block_id' name='block_name' title='Numeric Question block ID' placeholder=' # #' readonly>
<!value='<?php $max = mysqli_query($connectify,"SELECT max(ref) as maxid FROM question "); $max1=mysqli_fetch_array($max); echo $max1['maxid'];?>'/>
<input type='text' id='nQF' name='newQuestionField' size="50" placeholder='new_question' title="Insert a New Question with a relevant blockID "/>
<br/><br/>
<input type='submit' value=' Put '/>
<input type='reset' value='Clear' id='clearfield'/>
</form>
</div>
</body>
<file_sep>from Enumerators import PlayerType
import Movements
import unittest
#############################################################
# BASE CLASS for any chess piece
class Piece:
isDecommissioned : bool
currentLocation : tuple # x,y
color : PlayerType
movementBehavior: Movements.MovementBehavior
def __init__(self, location : tuple, pieceColor : PlayerType):
self.isDecommissioned = False
self.currentLocation = location
self.color = pieceColor
# self.movementBehavior = Movements.AcrossMove()
def getAllMoves(self): # virtual method
pass
# inheriting from ChessPiece Base class
class Rook(Piece):
def __init__(self, location : tuple, pieceColor : PlayerType):
self.isDecommissioned = False
self.currentLocation = location
self.color = pieceColor
self.movementBehavior = Movements.AcrossMove()
def getAllMoves(self):
if(self.isDecommissioned): return []
return self.movementBehavior.getAllMoves(self.currentLocation[0],
self.currentLocation[1])
# inheriting from ChessPiece Base class
class Bishop(Piece):
def __init__(self, location : tuple, pieceColor : PlayerType):
self.isDecommissioned = False
self.currentLocation = location
self.color = pieceColor
self.movementBehavior = Movements.DiagonalMove()
def getAllMoves(self):
if(self.isDecommissioned): return []
return self.movementBehavior.getAllMoves(self.currentLocation[0],
self.currentLocation[1])
# inheriting from ChessPiece Base class
class Knight(Piece):
def __init__(self, location : tuple, pieceColor : PlayerType):
self.isDecommissioned = False
self.currentLocation = location
self.color = pieceColor
self.movementBehavior = Movements.KnightlyMove()
def getAllMoves(self):
if(self.isDecommissioned): return []
return self.movementBehavior.getAllMoves(self.currentLocation[0],
self.currentLocation[1])
# if __name__ == '__main__':
# unittest.main()
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
if(!isset($_SESSION['me'])) echo "<script>window.location = 'frontpage.php'</script>"; //if not valid user kick him to login page
if(!isset($_POST['newQuestionField'])) echo "<script>window.location = '../index0.php'</script>"; //if manually called, i.e not via POST method then kick the attempt
if($_POST['block_name'] == "" || $_POST['newQuestionField'] == "" ) { echo "<div style='color: red;' >You know what, this kind of incomplete entries are unacceptable, <br/> I really need a meaningful *Block ID* along with a *Question* :( </div>"; return; } // activates when blockID less NewQuestions are detected..
require_once '../configuration.php';
//print_r($_POST);
$blockID = $_POST['block_name'];
$newQuestion = $_POST['newQuestionField'];
$safeNQ=mysqli_real_escape_string($connectify,$newQuestion);
if(mysqli_query($connectify, "INSERT INTO question VALUES('','$blockID','$safeNQ')"))
echo $newQuestion;
<file_sep>
<?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
if(!isset($_SESSION['me'])) echo "<script>window.location = 'frontpage.php'</script>"; //if not valid user kick him to login page
if(!isset($_SESSION['qref'])) $_SESSION['qref']=1; //start questioning from the beginning
if(!isset($_SESSION['working_thread']) || $_SESSION['me']==$_SESSION['working_thread'] ) echo "<script>window.location = 'index0.php'</script>"; // if working on no thread jump to threadlist
$currentThread=$_SESSION['working_thread'];
$currentUserName=$_SESSION['me'];
// echo $currentUserName;
$_SESSION['prevEntry']="NONE";
?>
<style>
.hidden {display: none;}
.linkStyle {color:grey; border: 2px solid grey; background-color: #fff;font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
.QspaceStyle {color:dark; border: 2px solid white; background-color: #BBBBFF; font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
.answerStyle {border-top: 1px solid grey; background-color: #eee; padding: 0.8em; padding-left: 0.1em; font-size: 100%;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:13px;}
.commentStyle {background-color: #ffff9f;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:13px;}
.timestampStyle {background-color: #ffffbf;}
.skipperClass {color: #fff; background-color: brown;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
</style>
<!doctype>
<html>
<head>
<meta charset="UTF-8" />
<title> <?php echo "Thread:: $currentThread"; ?> </title>
<! |||||||||_______________________>
<a name='↑'></a> <!ASCII24 Anchor >
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="jquery-ui.css" />
<div class="top-container" style="border-bottom-width: 1px;">
<body onLoad="document.f1.thought.focus();">
<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center">
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="3" width="100%">
<tr style="background-color: #FAFFF0"><!#088fff">
<td align="left" width=100%>
<!pre means preformatted>
<i><small><strong>
<small>
<a href='index0.php' class="linkStyle" title="Create/Browse your Threads" > My Threads </a>
<a href='#↓' name='bott' class="linkStyle" title="i.e. Bottom of page" onClick="document.f1.thought.focus();">Goto End of this Thread</a>
<B> |</B>
<a href='ajaxload.php' class="linkStyle" title="i.e. full Thread" >See Full Conversation </a>
<?php require 'qMan/allAdmins.php'; if ( in_array($_SESSION['me'] , $admins, true )) echo "| <a href='qMan/' title='I want to Edit QuestionBank' class='linkStyle' style='border: 4px solid brown;background-color: #008800; color: white'>Wow! SuperUser Detected</a> | ";?>
<a href='images/..' title="refresh now"><img src='images/refresh-animated.gif' /></a>
<B> |</B>
<button id="about" title="about-Checklist">What am I?</button>
<td align="right"> <i><b>
<small>
<a href='logMeOut.php' name='logout' title="I'm done, Log Me Out" class='QspaceStyle' style='border: 3px solid white;background-color: #088fff;color: white'>←Logout▬</a>
</b></i></small></td>
</strong></small></i>
</font>
</td>
<!--td align="right"> </td> <br/-->
</tr>
</table>
<h1 style="color:#fff; background-color: #088fff;border: 4px solid black;"> <!#088fff>
<img src="images/tick.jpg" style="height:30px; width:25px;" /> <?php echo "$currentUserName 's Checklist ( $currentThread )";?></h1>
</td>
</tr>
</table>
</div>
<! |||||||||_______________________>
<script src="jquery-1.9.1.min.js"> </script> <!//src=source>
<script src="jquery-ui.js"> </script> <!>
<script>
var skipcount = 0;
var skiptext = "<div2 class='skipperClass'><blink><b> : SKIPPED by user </b></blink></div2>";
var urlpaste = "<img src= ' pasteURL ' />";
//<h1> Sorry, Javascript/J-query Support Required, See your browser privileges :( <h1>
//<!-- Begin J-Query body
$(document).ready(function() {
// document.documentElement.style.overflow = 'hidden'; // disables the vertical scrollbar, doesn't work for IE*
$("#messages").load('ajaxload.php');
$("#loading").delay(1200).hide(0);
$("#talking").submit( function(){
$.post('ajaxPost.php',$('#talking').serialize(), function(data){
//alert(data);
($('#messages').append('<div>'+data+'</div>'));
$('html, body').animate({
scrollTop: $(".posting").offset().top
}, 2500);
document.getElementById('clearfield').click();
document.f1.thought.focus();
});
//$("#id").scrollTop($("#id").scrollTop() + 100);
//$('html, body').animate({scrollBottom: $("#page").offset().top}, 2000);
return false;
});
}); // End Scripting -->
</script>
</head>
<!center>
<!______dISPLAY Hist__________>
<div id="messages"> </div>
<!______Posting__________>
<div class="posting" id='posting_id'> <!style="height:10%; position:relative; bottom:0px;">
<form id="talking" name='f1'> <! onsubmit="window.scrollBy(0, 200); return true" >
<label> <!Mess> </label>
<!textarea rows="1" cols="50" placeholder="Thought" title="Free your mind and tell" name='thought' > </textarea>
<!--animate :P-->
<div id="loading">    <img src="images/ajax-loader1.gif" style="height:13px; width:170px;"/> fetching</div> <!-- loading anime-->
<!///////////// TEXTBOX //////////////>
<input type='text' size="50" title="Free your mind and tell" maxlength="500" id='thought_id' name="thought" placeholder="Current Thought" onkeyup="if (event.keyCode == 13) document.f1.put.click();"></textarea>
<!pattern="[^.!?\s][^.!?]*(?:[.!?](?![']?\s|$)[^.!?]*)*[.!?]?[']?(?=\s|$)"> <!pattern="[A-Za-z]"/>
<!///////////// PUT/SKIP/CLEAR buttons ////////////>
<input type="submit" name='put' title="Click me when you are done" value="Put" style="position:relative;"/>
<!--///// this botton doesn't work /////// -->
<input type="button" id="skipper" value="Skip" onClick="skipcount++;document.f1.thought.value= skipcount+':'+skiptext; document.f1.put.click();" title="Click me, if this question isn't applicable." />
<input type="reset" id="clearfield" value="clear" onClick="document.f1.thought.focus();" title="Flush that Box" />
<input type="button" class="QspaceStyle" value="put a picture!" style="border: 2px solid green;background-color: white;" title="How to?: Replace the **paste_Image_URL_here ** with your image URL"
onMouseDown=" getElementById('thought_id').value += urlpaste; document.f1.thought.focus(); " />
<a href='#↑' id="gotop" title="Go to Top of page" ><!onClick= "$("html, body").animate({ scrollTop: $(document).height() }, "slow");"> <img src="images/top.jpg" style="height:30px; width:30px;" /> </a>
<a name='↓'> </a> </div> <!--<<<------the bottom Anchor---- -->
</form>
</div>
<div id="footer" class="footer" > <p>   <! the adjustment bureau >
</div>
<!/center>
</body>
</html>
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
require_once 'configuration.php';
$result = mysqli_query($connectify,"SELECT * FROM question");
while ($value = mysqli_fetch_array($result))
{
echo $value['qref'].' :: '. $value['qcontext'].'<br/>';
}
?>
<file_sep>from Enumerators import BOARD_SIZE
from Enumerators import CellDiagonalMovements
import unittest
import Utils
#################################################################
class MovementBehavior:
isJumpingAllowed: bool
def __init__(self):
isJumpingAllowed = True
def getAllMoves(self, x : int, y : int): #virtual
pass
#################################################################
class AcrossMove(MovementBehavior):
def __init__(self):
self.isJumpingAllowed = False
#super().isJumpingAllowed = False
def getAllMoves(self, x : int, y : int):
possibleMoveLocations : tuple = []
count = 0
while (count < BOARD_SIZE):
if(count != x) : possibleMoveLocations.append((count,y))
count += 1
d = 0
while (d < BOARD_SIZE):
if(d != y) : possibleMoveLocations.append((x,d))
d += 1
return possibleMoveLocations
#################################################################
class DiagonalMove(MovementBehavior):
def __init__(self):
self.isJumpingAllowed = False
#super().isJumpingAllowed = False
def getAllMoves(self, x : int, y : int):
possibleMoveLocations : tuple = []
'''
* There are 4 diagonal scenarios from any particular location.
* namely: ++, --, +-, -+
'''
for strategy in CellDiagonalMovements :
count = 1
while (count < BOARD_SIZE):
cell = Utils.getAdjacentDiagonalCell( False, strategy, (x,y), count)
if( Utils.isValidCell(cell)) :
possibleMoveLocations.append(cell)
else :
break
count += 1
return possibleMoveLocations
#################################################################
class KnightlyMove(MovementBehavior):
def __init__(self):
self.isJumpingAllowed = True
def getAllMoves(self, x : int, y : int):
possibleMoveLocations : tuple = []
'''
* There are maximum 8 diagonal scenarios for all particular location.
* namely: +2+1, -2-1, +2-1, -2+1 , +1+2, -1-2, +1-2, -1+2
'''
for strategy in CellDiagonalMovements :
count = 1
cells = Utils.getAdjacentDiagonalCell( True, strategy, (x,y), count)
if( Utils.isValidCell(cells[0])) :
possibleMoveLocations.append(cells[0])
if( Utils.isValidCell(cells[1])) :
possibleMoveLocations.append(cells[1])
return possibleMoveLocations
#################################################################
class KingMove(MovementBehavior):
def __init__(self):
self.isJumpingAllowed = False
def getAllMoves(self, x : int, y : int):
possibleMoveLocations : tuple = []
'''
* There are maximum 8 total scenarios for a King.
* namely: (-1,+1), (0,+1), (+1,+1), (-1,+0), (+1,+0), (-1,-1), (0,-1), (+1,-1)
'''
cells = (
(x-1,y+1), (x,y+1), (x+1,y+1), (x-1,y), (x+1,y), (x-1,y-1), (x,y-1), (x+1,y-1)
)
for cell in cells :
if( Utils.isValidCell(cell)) :
possibleMoveLocations.append(cell)
# TODO : Implement Castling between Rooks & King. Maybe this location is not the right place to implement castling. Investigate
return possibleMoveLocations
#################################################################
#################################################################
class UNIT_TESTS(unittest.TestCase):
def setUp(self):
pass
def SortThenMatchTwoList(self, actualMoves, expectedMoves):
actualMoves.sort(key = lambda eachTuple : eachTuple[0] )
actualMoves.sort(key = lambda eachTuple : eachTuple[1] )
expectedMoves.sort(key = lambda eachTuple : eachTuple[0] )
expectedMoves.sort(key = lambda eachTuple : eachTuple[1] )
# print(actualMoves,expectedMoves)
self.assertListEqual(expectedMoves, actualMoves, 'Assert ERROR: Unexpected Moves found!! ')
def test_RookMovement00(self):
rook : MovementBehavior = AcrossMove()
self.SortThenMatchTwoList( rook.getAllMoves(0,0),
[(1,0),(2,0), (3,0), (4,0), (5,0), (6,0), (7,0), (0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7)]
)
def test_RookMovement11(self):
rook : MovementBehavior = AcrossMove()
self.SortThenMatchTwoList( rook.getAllMoves(1,1),
[(0,1),(2,1), (3,1), (4,1), (5,1), (6,1), (7,1), (1,0),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7)]
)
def test_RookMovement77(self):
rook : MovementBehavior = AcrossMove()
self.SortThenMatchTwoList( rook.getAllMoves(7,7),
[(0,7),(1,7),(2,7),(3,7),(4,7),(5,7),(6,7),(7,6),(7,5),(7,4),(7,3),(7,2),(7,1),(7,0)]
)
def test_RookMovement23(self):
rook : MovementBehavior = AcrossMove()
self.SortThenMatchTwoList( rook.getAllMoves(2,3),
[(0,3),(1,3),(3,3),(4,3),(5,3),(6,3),(7,3), (2,0),(2,1),(2,2),(2,4),(2,5),(2,6),(2,7)]
)
def test_BishopMovement34(self):
bishop : MovementBehavior = DiagonalMove()
self.SortThenMatchTwoList(bishop.getAllMoves(3,5),
[(0,2), (1,3), (2,4), (4,6), (5,7), (2,6), (1,7), (4,4), (5,3), (6,2), (7,1)]
)
def test_BishopMovement00(self):
bishop : MovementBehavior = DiagonalMove()
self.SortThenMatchTwoList(bishop.getAllMoves(0,0),
[(2,2), (3,3), (4,4), (6,6), (5,5), (1,1), (7,7)]
)
def test_KnightlyMovement00(self):
knight : MovementBehavior = KnightlyMove()
self.SortThenMatchTwoList(knight.getAllMoves(0,0),
[(2,1), (1,2)]
)
def test_KnightlyMovement32(self):
knight : MovementBehavior = KnightlyMove()
self.SortThenMatchTwoList(knight.getAllMoves(3,2),
[(5,1), (4,0), (4,4), (5,3), (2,4), (1,3), (2,0), (1,1)]
)
def test_KING_Movement30(self):
king : MovementBehavior = KingMove()
self.SortThenMatchTwoList(king.getAllMoves(3,0),
[(2,0), (2,1), (3,1), (4,1), (4,0)]
)
#################################################################
if __name__ == '__main__':
unittest.main()
<file_sep>import sys
import pygame
import time
# have the members
# member will have category
# each category shall have different kind of moves.
# moves can be inherited (do we need this feature??)
# prepare the nxn battlefield
# Play
# GUI management
class MatchController:
boardSize = 8
def setSize(self, n:int):
self.boardSize = n
clock = pygame.time.Clock()
screen = pygame.display.set_mode((1024,768))
blue = 2, 3, 4
screen.fill(blue)
time.sleep(10)
## TODO : Call the controller engine from here
<file_sep>import Enumerators
## Run tests
Enumerators.UT1()<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
require 'configuration.php';
$id = $_POST['id'];
//$id--;
//echo $id;
//$x = mysql_result(mysql_query($connectify,"SELECT * FROM $tablename WHERE `sequence` = $id "),0,"context");
if(mysqli_query($connectify,"DELETE FROM responses WHERE `sequence` = $id ")) echo " __Delete successful";
else echo "This delete was UNSUCCESSFUL :( ";
?>
<file_sep>
<?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
if(isset($_SESSION['me'])) echo "<script> window.location.replace ('*/..') </script>";
?>
<!doctype HTML>
<meta charset="UTF-8" />
<title>Checklist Login Page</title>
<h5 style='color: #ffffed;' title='Credits!'> Designer Checklist v1.3, ©  2013 snehasys,<br/>Developed by Snehasys®, Sponsored by IDC-IIT Bombay</h5>
<div id='loading'>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<img src="images/ajax-loader2.gif" style="height: 20px;width: 20px;"/><img src="images/ajax-loader2.gif" style="height: 20px;width: 20px;"/>
</div>
<body>
<style>
body { font-size: 82.5%; }
label, input { display:block; }
input.text { margin-bottom:12px; width:95%; padding: .4em; }
fieldset { padding:0; border:0; margin-top:25px; }
h1 { font-size: 1.2em; margin: .6em 0; }
div#users-contain { width: 350px; margin: 20px 0; }
div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
.ui-dialog .ui-state-error { padding: .3em; }
.validateTips { border: 1px solid transparent; padding: 0.3em; }
.hidden {display: none;}
.QspaceStyle {color:dark; border: 2px solid white; background-color: #BBBBFF; font-family: sans-serif; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
.loginStyle { color: grey; border: 2px solid green; background-color: #dfd; padding: .3em;-webkit-border-radius:13px;-moz-border-radius:13px;-ms-border-radius:13px;-o-border-radius:13px;border-radius:13px;}
</style>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.min.js"> </script>
<script src="jquery-ui.js"> </script>
<script>
$(document).ready(function(){
$("#loading").delay(1200).hide(0);
$(function(){
$("#login-fields").dialog({autoOpen : true,
draggable: false, height : 490, width : 390, modal : false, position : "topleft" ,
show : "fold", hide : "fold"});
$("#signup-fields").dialog({autoOpen : false,
draggable: true, height : 352, width : 370, modal : true, position : ['center',150] ,
show : "clip", hide : "blind"}); // puff, bounce, drop, highlight, blind, size, fold, explode,pulsate,shake,
});
$("#f1").submit( function()
{
$.post('user_login.php',$('#f1').serialize(), function(data){
alert(data);
$('#login-fields').dialog( "close" );
window.location.replace ('index.php').delay(5000);
});
return false;
});
$("#f2").submit( function()
{
$.post('createUserAcc.php',$('#f2').serialize(), function(data){
alert(data);
$('#signup-fields').dialog( "close" );
});
return false;
});
});
</script>
<div id="login-fields" title="Authenticate Yourself" class="hidden">
<img src="images/Checklist_assistant_logo.png"> <!style="height:300px; width:250px;" >
<form id="f1"> <!action="user_login.php" method="post">
<br/><center>
<input type="text" name="uname" placeholder="<NAME>" title='Your <NAME>'/>
<input type="<PASSWORD>" name="pwd" placeholder="<PASSWORD>" title='<PASSWORD>'>
<input type="submit" class='loginStyle' value=" Login.. " title='Click to Login'/>
<small> New User? Well, just click <a href="#" onClick="$( '#signup-fields' ).dialog( 'open' );">here</a> <!--If some problem arises add "$('#signup-fields').show();" in the onClick() module.. :D -->
<!center>
</form>
</div>
<!----//////////////// popped signup dialogue \\\\\\\\\\\\\\-------->
<div id="signup-fields" title="Registration" class="hidden" >
<form id="f2">
<center>
<img src="images/Checklist_assistant.jpg">
<br/><br/>
<label>user</label>
<input type="text" name="newUname" placeholder="New_Username"
pattern="[A-Za-z0-9_$]+" title="Preferred unique username, (no special characters allowed but '_'and'$')" /> <! anything but an apostrophe:: pattern = "^((?!').)*$" >
<label>mail-id</label>115
<input type="text" name="newMail" placeholder="Your E-mail"
pattern="^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$" title="Email: <EMAIL>" />
<label>passwords</label>
<input type="<PASSWORD>" name="newPwd" placeholder="<PASSWORD>" title='Type in a password'/>
<input type="password" name="retypePwd" placeholder="<PASSWORD> it <PASSWORD>" title='Retype that Password' />
<input type="submit" class="QspaceStyle" value=" Sign Up "/>
<small>*You know the rules! All fields are required</small>
</form>
</center>
</div>
</body>
</HTML>
<file_sep> <?php
/**
* @author snehasys <<EMAIL>>
*/
session_start();
print_r($_POST);
require '../configuration.php';
$b_id=$_POST['block_id'];
$n_priorities=$_POST['new_priorities'];
/*
$priority_array=explode("/", $n_priorities);
$counter=0;
while($priority_array[$counter]){
$checked=0;
$real_block_arr=mysqli_query($connectify,"SELECT `qblockid` FROM `qmatrix`");
while($real_blocks=mysqli_fetch_array($real_block_arr)){
if ($priority_array['$counter'] === $real_blocks[0]) $checked=1;
}
if ( ! $checked) { echo "this priority matrix either contains fictional BlockIDs or is in wrong format.."; return; }
}
*/
// if (! preg_match("[\d\,]*", $n_priorities)) echo "Wrong pattern detected"; ////<---------- doesn't work :P
if(mysqli_query($connectify,"UPDATE `qmatrix` SET `nextblockpriority`='$n_priorities' WHERE qblockid= $b_id ")) echo "***The edit was Successful*** make sure you have putted only valid BlockIDs and slashes there.. ";
else echo "Your edit was unsuccessful.. :( ";
<file_sep><?php
/**
* @author snehasys <<EMAIL>>
*/
//new block create ajax page
session_start();
if(!isset($_SESSION['me'])) echo "<script>window.location = '../frontpage.php'</script>"; //if not valid user kick him to login page
/////////////////////// $colors=array('red', 'yellow', 'blue'); $_SESSION['color']=$colors;
///////////////////////
require 'allAdmins.php'; ///////// ONLY ADMINS ARE ALLOWED IN THIS PAGE /////////////
if (!in_array($_SESSION['me'] , $admins, true )) { /// ADMIN CHECK...
echo "<h2 style='color: RED;' > <br/><br/>** Unauthorized access DENIED **<h2>";
return ;
}
require '../configuration.php';
if ( mysqli_query($connectify,"INSERT INTO qmatrix VALUES ('','')" )) echo "**Cheers! New Question Block Created :) ";
else echo "** Creation ERROR ** ";
?>
| 0b1b7c708043ffe7924e5d5551da53cd301d2553 | [
"Markdown",
"Java",
"Python",
"PHP",
"C++"
] | 40 | PHP | snehasys/repo1 | 4869aae5528a5db12d16db5cfad0a79c9e3cc3b6 | 92e72dc133aae07e74a3a9ac545a704e6fabc986 |
refs/heads/master | <repo_name>Fale/wp-plugin-frasiNonnaZita<file_sep>/grimp-frasiNonnaZita.php
<?php
/*
Plugin Name: Grimp - Frasi Nonna Zita
Plugin URI: http://git.grimp.eu/projects/wp-plugin-frasiNonnaZita
Description: This plugin will allow you to show a rotating phrase.
Version: 0.1
Author: <NAME>
Author URI: http://grimp.eu
License: GPL2
*/
add_action("widgets_init", "grimp_fnz_init");
function grimp_fnz_init(){
register_widget("grimp_fnz");
}
class grimp_fnz extends WP_Widget {
function grimp_fnz() {
/* Impostazione del widget */
$widget_ops = array( 'classname' => 'grimp-fnz', 'description' => 'This plugin will allow you to show a rotating phrase.' );
/* Impostazioni di controllo del widget */
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'grimp-fnz' );
/* Creiamo il widget */
$this->WP_Widget( 'grimp-fnz', 'Frasi Nonna Zita', $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args );
$frasi = array();
$frasi[] = 'C&è un solo modo di risolvere un problema: affrontarlo';
$frasi[] = 'Perdonare è da cristiani, dimenticare da stupidi';
$frasi[] = 'Togliere le macchie appena possibile, il risultato è sempre migliore';
$frasi[] = 'Anche gli asini lavorano';
$frasi[] = 'Credi ma non scommettere';
$frasi[] = 'Non sfregare le macchie, tamponale';
$frasi[] = 'Credi sempre ma controlla sempre';
$frasi[] = 'Tutto può tornare utile, anche le unghie per sbucciare l&aglio';
$frasi[] = 'Quello che vuoi fallo, quello che non vuoi demandalo';
$frasi[] = 'Tutti hanno un loro credo';
$frasi[] = 'Un leggero appretto facilita la stiratura';
$frasi[] = 'Le grandi spese si programmano, le piccole ti rendono povero';
$frasi[] = 'Si ha più successo con la sfacciataggine che con un portafoglio pieno';
$frasi[] = 'Si sa come si nasce ma non come si muore';
$frasi[] = 'Il cotone si stira umido, la lana asciutta';
$frasi[] = 'Un bel tacer non fu mai detto';
$frasi[] = 'Carta canta e villan dorme';
$frasi[] = 'Le tarme mangiano più volentieri le parti sporche';
$frasi[] = 'Se parli, dì la verità, ma non sempre è il caso di parlare';
$frasi[] = 'Occhio non vede, cuore non duole';
$frasi[] = 'Provare sempre gli smacchiatori in una zona nascosta dell&indumento';
$frasi[] = 'Meglio un avversario intelligente che un socio stupido';
$frasi[] = 'Chi dorme non piglia pesci';
$frasi[] = 'Prevenire è meglio che...smacchiare';
$frasi[] = 'L\'uomo propone ma il Signore dispone';
$frasi[] = 'Il diavolo fa le pentole ma non i coperchi';
$frasi[] = 'Tra il dire ed il fare c&è; di mezzo il mare';
$frasi[] = 'Leggi le etichette';
$frasi[] = 'Solo le forbici tolgono tutte le macchie';
$frasi[] = 'L\'occhio del padrone ingrassa il cavallo';
$frasi[] = 'Via il gatto, i topi ballano';
$frasi[] = 'Sporco o macchiato?';
$frasi[] = 'Tanto va la gatta al lardo che ci lascia lo zampino';
$frasi[] = 'Si sa come si nasce ma non come si muore';
$frasi[] = 'Di notte tutti i gatti sono grigi';
$frasi[] = 'Una rondine non fa primavera';
$frasi[] = 'Le tarme mangiano le parti sporche';
$frasi[] = 'L\'abito non fa il monaco';
$frasi[] = 'Se ti danno un euro per cinquanta centesimi, è un inganno';
$frasi[] = 'Un bucato ben steso si stira meglio';
$frasi[] = 'La vita è fatta anche di piccoli piaceri';
$frasi[] = 'La pelle bagnata sempre lontana dal calore';
$frasi[] = 'Ognuno faccia il suo lavoro';
$frasi[] = 'Per comandare bisogna saper ubbidire';
$frasi[] = 'Candeggina e perborato non vanno assieme';
$frasi[] = 'Non è tutto oro quello che luccica';
$frasi[] = 'A volte, il meglio è nemico del bene';
$frasi[] = 'Comincia col provare la soluzione più semplice';
$frasi[] = 'I bottoni belli, è meglio toglierli';
$frasi[] = 'Il primo guadagno è il risparmio';
$title = apply_filters('widget_title', $instance['title'] );
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
$day= date ('d', time()) + date ('m', time()) + date ('w', time());
$frase = $frasi[$day-1];
echo "<center><b><font color=#FF0000>$frase</font></b></center>";
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
return $instance;
}
function form( $instance ) {
/* Impostazioni di default del widget */
$defaults = array( 'title' => 'I detti di nonna Zita');
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
</p>
<?php
}
}
?>
| acf2b2442aeb93ff00ca32147f6a92698b0de0a2 | [
"PHP"
] | 1 | PHP | Fale/wp-plugin-frasiNonnaZita | d0a8611b346a78a68aa5c53d53f64d52a74eb5c5 | f48800ac7603bed16dc23ad137c9c02ab5722c79 |
refs/heads/master | <repo_name>Xwilarg/WebServerPlus<file_sep>/README.md
# WebServerPlus
Example of implementation of a WebServer in C++ using cpprestsdk
## Endpoints
- /get (GET) Get all the colors store in the server (10x10 array, each color is in the format RRRGGGBBB)
- /update (POST) Set a new color (body argument must be [x position];[y position];[pixel color]
## Dependencies
- [cpprestsdk](https://github.com/Microsoft/cpprestsdk)
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.7)
project(WebServer++)
find_package(cpprestsdk REQUIRED)
if (WIN32)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
endif (WIN32)
if (UNIX)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Weffc++")
endif (UNIX)
include_directories(inc)
add_executable(WebServer++ src/main.cpp src/WebServer.cpp)
target_link_libraries(WebServer++ PRIVATE cpprestsdk::cpprest)<file_sep>/inc/WebServer.hpp
#ifndef WEBSERVER_HPP_
# define WEBSERVER_HPP_
# include <cpprest/http_listener.h>
# include <string>
# include <array>
namespace WebServer
{
class WebServer final
{
public:
WebServer(std::wstring &&ip, std::wstring &&port) noexcept;
~WebServer() noexcept;
private:
void GetColors(web::http::http_request message) const noexcept;
void UpdateColors(web::http::http_request message) noexcept;
web::http::experimental::listener::http_listener _listenerGet;
web::http::experimental::listener::http_listener _listenerUpdate;
std::array<std::wstring, 100> _allcolors;
};
}
#endif //! WEBSERVER_HPP_
<file_sep>/src/WebServer.cpp
#include "WebServer.hpp"
namespace WebServer
{
WebServer::WebServer(std::wstring &&ip, std::wstring &&port) noexcept
: _listenerGet(L"http://" + ip + L":" + port + L"/get"),
_listenerUpdate(L"http://" + std::move(ip) + L":" + std::move(port) + L"/update"),
_allcolors()
{
auto white = std::wstring(L"255255255");
for (int i = 0; i < 100; i++)
{
_allcolors[i] = white;
}
_listenerGet.support(web::http::methods::GET, std::bind(&WebServer::GetColors, this, std::placeholders::_1));
_listenerUpdate.support(web::http::methods::POST, std::bind(&WebServer::UpdateColors, this, std::placeholders::_1));
_listenerGet.open().wait();
_listenerUpdate.open().wait();
}
WebServer::~WebServer() noexcept
{
_listenerGet.close().wait();
_listenerUpdate.close().wait();
}
void WebServer::GetColors(web::http::http_request message) const noexcept
{
auto colors = web::json::value::array(100);
for (int i = 0; i < 100; i++)
colors.at(i) = web::json::value::string(_allcolors[i]);
web::http::http_response response;
response.set_status_code(web::http::status_codes::OK);
response.set_body(colors);
response.headers().add(L"Access-Control-Allow-Origin", "*");
message.reply(response);
}
void WebServer::UpdateColors(web::http::http_request message) noexcept
{
auto body = message.extract_string().get();
std::wstring str(body.begin(), body.end());
size_t pos;
pos = str.find(L";");
int posX = std::stoi(str.substr(0, pos));
str.erase(0, pos + 1);
pos = str.find(L";");
int posY = std::stoi(str.substr(0, pos));
str.erase(0, pos + 1);
_allcolors[posX * 10 + posY] = str;
GetColors(message);
}
}<file_sep>/src/main.cpp
#include <iostream>
#include "WebServer.hpp"
int main()
{
WebServer::WebServer server(L"localhost", L"8082");
std::cout << "Listening..." << std::endl << "Press enter to exit" << std::endl;
std::cin.ignore();
} | 260abb92cfd833557eafc8b2bef21288b4a8f090 | [
"Markdown",
"CMake",
"C++"
] | 5 | Markdown | Xwilarg/WebServerPlus | 9ee3d91dde0b60ced4e9750548bde0f01115a5bf | 43018b7ed547ddc212812e4e1ff0d0998ac0d4e8 |
refs/heads/master | <repo_name>userhf/Monitor<file_sep>/README.ino
# Monitor
Runs an Arduino-powered, autonomous car, with large wheels, a gyroscope, LEDs, and a laser.
#include <Servo.h>
int laserpin = 13;
int LEDpin = 12;
int gyropin = 11;
int trigpin = 9;
int echopin = 8;
int lpin = 6;
int rpin = 7;
Servo left;
Servo right;
int howFar(){
int cm = 0;
int duration = 0;
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
cm = duration / 58.2;
return cm;
}
void forward(){
boolean up;
//read from gyroscope if up or not, and adjust up accordingly
if(up){
left.write(0);
right.write(0);
}
else{
left.write(180);
right.write(180);
}
delay(1000);
left.write(90);
right.write(90);
}
void setup(){
pinMode(laserpin, OUTPUT);
pinMode(LEDpin, OUTPUT);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(lpin, OUTPUT);
pinMode(rpin, OUTPUT);
left.attach(lpin);
right.attach(rpin);
digitalWrite(laserpin, HIGH);
digitalWrite(LEDpin, HIGH);
digitalWrite(trigpin, LOW);
left.write(90);
right.write(90);
delay(5000);
}
void loop(){
int far = howFar();
if (far <= 5){
//stop, turn
}
if (far > 5){
forward();
}
}
| 2dd1319fde82354186687cb7a2ee5075aace7c6b | [
"C++"
] | 1 | C++ | userhf/Monitor | afaf8c509aae52a5b3608cf2ed0ab4ead44f9a2b | 033b08f7937807d5f37f19d2e319f6065b327fb4 |
refs/heads/main | <repo_name>Kim-Chanjong/p2pWebpageProject<file_sep>/p2pWebpage/src/main/java/com/koreait/service/LoginService.java
package com.koreait.service;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.koreait.dao.MemberDAO;
import com.koreait.vo.MemberVO;
@Service
public class LoginService implements MemberService {
@Autowired
MemberDAO dao;
@Override
public boolean loginCheck(MemberVO vo,HttpSession session) {
boolean result = dao.loginCheck(vo);
if (result == true) { //true 일경우 세션 등록
//세션 변수 등록
session.setAttribute("id",vo.getId());
}
return result;
}
@Override
public void logout(HttpSession session) {
dao.logout(session);
}
}<file_sep>/p2pWebpage/src/main/java/com/koreait/dao/MybatisDAO.java
package com.koreait.dao;
import com.koreait.vo.MemberVO;
public interface MybatisDAO {
void insert(MemberVO memberVO);
}
| 5f61dd2145e6fd4bf04d018fa4ef39648f1f132e | [
"Java"
] | 2 | Java | Kim-Chanjong/p2pWebpageProject | 909f9379a0074f88bf78e2e06c84344a6e8e0d4d | bd05468e3dae4952396138dd729e0c79111605d7 |
refs/heads/master | <file_sep>package com.android.vira.utils
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
/**
* Created by HosseinBahrami at 1/19/2020
*/
open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
//CheckInternet
protected fun inNetworkConnected(): Boolean {
return CheckNetwork.isNetworkAvailable(this)
}
protected fun showLongToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
protected fun showShortToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
<file_sep>package com.android.vira.api
import android.view.View
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by HosseinBahrami at 1/19/2020
*/
object RetrofitCallBack {
fun <T> callRetrofit(call: Call<T>, loading: View?, retrofitObject: RetrofitObject<T>) {
//Show Loading if Exists
if (loading != null) loading.visibility = View.VISIBLE
//Call Api With Generic CallBack
call.enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
//Hidden Loading if Exists
if (loading != null) loading.visibility = View.GONE
if (response.isSuccessful) {
retrofitObject.onSuccess(body = response.body()!!)
} else {
retrofitObject.onFailure(message = response.errorBody()!!.string())
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
//Hidden Loading if Exists
if (loading != null) loading.visibility = View.GONE
retrofitObject.onFailure(message = t.message.toString())
}
})
}
}<file_sep>package com.android.vira
import android.app.Application
import android.content.Context
/**
* Created by HosseinBahrami at 1/19/2020
* this class is used for per-process initialization that should always happen, not just for certain activities or other components.
So, for example, you might initialize:
-Dependency injection (e.g., Dagger)
-Crash logging (e.g., ACRA)
-Diagnostic tools (e.g., LeakCanary, Stetho, Sonar)
-Global pools (e.g., OkHttpClient)
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
instance = this
context = this
}
fun getContext(): Context? {
return context
}
companion object {
@get:Synchronized
var instance: App? = null
private var context: Context? = null
}
}
<file_sep>package com.android.vira.utils
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
/**
* Create by HosseinBahrami at 1/19/2020
* Check Connectivity Network Mobile or WIFI
*/
object CheckNetwork {
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connectivityManager!!.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)?.state == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)?.state == NetworkInfo.State.CONNECTED
}
}<file_sep>package com.android.vira.api
import com.android.vira.api.models.response.GameBean
import retrofit2.Call
import retrofit2.http.GET
/**
* Created by HosseinBahrami at 1/19/2020
*/
interface ApiCall {
//Get GamesList
@GET("pnfbu")
fun getGames(): Call<List<GameBean>>
//Get GameDetails
@GET("1bjyoa")
fun getGameDetails(): Call<GameBean>
}
<file_sep>package com.android.vira.databases
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.android.vira.api.models.response.GameBean
/**
* Created by HosseinBahrami at 1/19/2020
*/
@Dao
interface GameListDao {
@Query("SELECT * FROM gamebean")
fun getGameList(): List<GameBean>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAllGames(gameBean: List<GameBean>)
}<file_sep>include ':app'
rootProject.name='ViraTest'
<file_sep>package com.android.vira.gameDetails
import android.os.Bundle
import android.widget.MediaController
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.android.vira.R
import com.android.vira.api.models.response.GameBean
import com.android.vira.databinding.ActivityGameDetailsBinding
import com.android.vira.utils.BaseActivity
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_game_details.*
/**
* Created by HosseinBahrami at 1/20/2020
*/
class GameDetailsActivity : BaseActivity() {
private lateinit var gameDetailsViewModel: GameDetailsViewModel
private lateinit var binding: ActivityGameDetailsBinding
private lateinit var gameBean: GameBean
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_game_details)
gameDetailsViewModel = ViewModelProviders.of(this).get(GameDetailsViewModel::class.java)
getData()
}
private fun getData() {
gameDetailsViewModel.getGameLiveDataDetails(loading, this).observe(this, Observer {
gameBean = it
binding.movieName.text = gameBean.title
binding.description.text = gameBean.description
binding.rate.rating = gameBean.rate.toFloat()
binding.playersCount.text = gameBean.playerCount.toString()
binding.genreName.text = gameBean.genre.genreName
Picasso.get().load(gameBean.image).into(binding.imgGames)
Picasso.get().load(gameBean.genre.genreImage).into(binding.imgGenre)
binding.videoView.setVideoPath(gameBean.video)
val mediaController = MediaController(this)
mediaController.setAnchorView(binding.videoView)
binding.videoView.setMediaController(mediaController)
binding.videoView.setOnPreparedListener {
binding.videoView.start()
}
binding.videoView.setOnCompletionListener { binding.videoView.start() }
})
}
}
<file_sep>package com.android.vira.api.models.response
import com.google.gson.annotations.SerializedName
data class GenreBean(
@SerializedName("id")
val genreId: Int,
@SerializedName("name")
val genreName: String,
@SerializedName("image")
val genreImage: String
) {
constructor() : this(0, "", "")
}<file_sep>package com.android.vira.utils
import android.widget.ImageView
import android.widget.MediaController
import androidx.databinding.BindingAdapter
import com.squareup.picasso.Picasso
/**
* Created by HosseinBahrami at 1/21/2020
*/
object BindingAdapters {
@JvmStatic
@BindingAdapter("loadImage")
fun loadImage(v: ImageView?, url: String?) {
Picasso.get().load(url).into(v)
}
}<file_sep>package com.android.vira.api
import android.os.Build
import okhttp3.Interceptor
import okhttp3.Response
/**
* Created by HosseinBahrami at 1/19/2020
* Set Header for Requests
*/
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val userAgent = "Android ${Build.MANUFACTURER} ${Build.BRAND} ${Build.MODEL} ${Build.VERSION.SDK_INT}"
val request = chain.request().newBuilder()
/**
* SomeTimes No Needed Bearer Word in Authorization
*/
// .addHeader("Authorization", "Bearer ${Constants.ACCESS_TOKEN}")
.addHeader("Accept", "application/json")
.addHeader("User-Agent", userAgent)
.build()
return chain.proceed(request)
}
}<file_sep># ViraTest
This is simple app writtem in kotlin. This app has the following components
- **MVVM architecture**
- **AndroidX libraries**
- **Android Architecture components**
- **Android Data Binding**
- **Retrofit2**
- **Kotlin Coroutines**
<file_sep>package com.android.vira.gameList
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.android.vira.R
import com.android.vira.adapters.GameListAdapter
import com.android.vira.adapters.callBacks.GameClickCallBack
import com.android.vira.api.models.response.GameBean
import com.android.vira.databinding.ActivityGameListBinding
import com.android.vira.gameDetails.GameDetailsActivity
import com.android.vira.utils.BaseActivity
import kotlinx.android.synthetic.main.activity_game_list.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* Created by HosseinBahrami at 1/19/2020
*/
class GameListActivity : BaseActivity() {
private lateinit var gameListViewModel: GameListViewModel
private var gameList = mutableListOf<GameBean>()
private lateinit var binding: ActivityGameListBinding
private lateinit var gamesAdapter: RecyclerView.Adapter<*>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_game_list)
gameListViewModel = ViewModelProviders.of(this).get(GameListViewModel::class.java)
EventBus.getDefault().register(this)
initGamesAdapter()
getData()
}
private fun getData() {
gameListViewModel.getLiveGamesData(loading, this).observe(this, Observer {
gameList.addAll(it)
if (gameList.isNullOrEmpty())
showShortToast("برای گرفتن دیتا باید یکبار به نت وصل شوید")
else
binding.gameLisRecycler.adapter!!.notifyDataSetChanged()
})
}
private fun initGamesAdapter() {
gamesAdapter = GameListAdapter(gameList)
binding.gameLisRecycler.adapter = gamesAdapter
binding.gameLisRecycler.adapter!!.notifyDataSetChanged()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun gameClicked(game: GameBean) {
val intent = Intent(this, GameDetailsActivity::class.java)
startActivity(intent)
}
override fun onStart() {
super.onStart()
EventBus.getDefault().unregister(theme)
}
}
<file_sep>package com.android.vira.databases
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.android.vira.api.models.response.GameBean
/**
* Created by HosseinBahrami at 1/19/2020
*/
@Dao
interface GameDetailsDao {
@Query("SELECT * FROM gamebean")
fun getGameDetails(): GameBean
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertDetailsGame(vararg gameBean: GameBean)
}<file_sep>package com.android.vira.gameDetails
import android.content.Context
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.android.vira.api.RetrofitCallBack
import com.android.vira.api.RetrofitClient
import com.android.vira.api.RetrofitObject
import com.android.vira.api.models.response.GameBean
import com.android.vira.databases.AppDatabase
import com.android.vira.utils.CheckNetwork
/**
* Created by HosseinBahrami at 1/20/2020
*/
class GameDetailsViewModel : ViewModel() {
private var gameDetailsLiveData: MutableLiveData<GameBean> = MutableLiveData()
fun getGameLiveDataDetails(loading: View?, context: Context): MutableLiveData<GameBean> {
if (CheckNetwork.isNetworkAvailable(context)) {
RetrofitCallBack.callRetrofit(
RetrofitClient.getService().getGameDetails(),
loading,
object : RetrofitObject<GameBean> {
override fun onSuccess(body: GameBean) {
gameDetailsLiveData.value = body
AppDatabase.getInstance(context).gameDetailsDao().insertDetailsGame(body)
}
override fun onFailure(message: String) {
//TODO
Log.v("failedGames", message)
}
})
} else {
gameDetailsLiveData.value = GameDetailsRepository.getLocalGameDetails(context)
}
return gameDetailsLiveData
}
}<file_sep>package com.android.vira.api
import com.android.vira.utils.Constants
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by HosseinBahrami at 1/19/2020
* Configuration Retrofit
*/
object RetrofitClient {
private var retrofit: Retrofit? = null
fun getService(): ApiCall {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(
OkHttpClient.Builder()
.addInterceptor(HeaderInterceptor())
.connectTimeout(Constants.CONNECT_TIME_OUT, TimeUnit.SECONDS)
.readTimeout(Constants.READ_TIME_OUT, TimeUnit.SECONDS)
.writeTimeout(Constants.WRITE_TIME_OUT, TimeUnit.SECONDS)
.build()
)
.build()
}
return retrofit!!.create(ApiCall::class.java)
}
}<file_sep>package com.android.vira.utils
/**
* Created by HosseinBahrami at 1/19/2020
*/
object Constants {
const val API_BASE_URL = "https://api.myjson.com/bins/"
const val CONNECT_TIME_OUT: Long = 30
const val READ_TIME_OUT: Long = 30
const val WRITE_TIME_OUT: Long = 30
}<file_sep>package com.android.vira.adapters.callBacks
interface GameClickCallBack {
fun onGameClicked()
}<file_sep>package com.android.vira.databases
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.android.vira.api.models.response.GameBean
/**
* Created by HosseinBahrami at 1/19/2020
*/
@Database(entities = [GameBean::class], version = 1, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
abstract fun gameListDao(): GameListDao
abstract fun gameDetailsDao(): GameDetailsDao
companion object {
private lateinit var db: AppDatabase
fun getInstance(context: Context): AppDatabase {
db = Room.databaseBuilder(context, AppDatabase::class.java, "ViraDatabase")
.allowMainThreadQueries().build()
return db
}
}
}<file_sep>package com.android.vira.api
/**
* Created by HosseinBahrami at 1/19/2020
*/
interface RetrofitObject<T> {
fun onSuccess(body: T)
fun onFailure(message: String)
}<file_sep>package com.android.vira.gameList
import android.content.Context
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.android.vira.api.RetrofitCallBack
import com.android.vira.api.RetrofitClient
import com.android.vira.api.RetrofitObject
import com.android.vira.api.models.response.GameBean
import com.android.vira.databases.AppDatabase
import com.android.vira.utils.CheckNetwork
/**
* Created by HosseinBahrami at 1/19/2020
*/
class GameListViewModel : ViewModel() {
private var gamesData: MutableLiveData<List<GameBean>> = MutableLiveData()
fun getLiveGamesData(loading: View?, context: Context): MutableLiveData<List<GameBean>> {
if (CheckNetwork.isNetworkAvailable(context)) {
RetrofitCallBack.callRetrofit(
RetrofitClient.getService().getGames(),
loading,
object : RetrofitObject<List<GameBean>> {
override fun onSuccess(body: List<GameBean>) {
gamesData.value = body
if (AppDatabase.getInstance(context).gameListDao().getGameList().isNullOrEmpty()) {
AppDatabase.getInstance(context).gameListDao().insertAllGames(body)
}
}
override fun onFailure(message: String) {
//TODO
Log.v("failedGames", message)
}
})
} else {
gamesData.value = GameListRepository.getLocalGameList(context)
}
return gamesData
}
}<file_sep>package com.android.vira.gameDetails
import android.content.Context
import com.android.vira.api.models.response.GameBean
import com.android.vira.databases.AppDatabase
import javax.inject.Singleton
/**
* Created by HosseinBahrami at 1/20/2020
*/
@Singleton
object GameDetailsRepository {
var data = GameBean()
//get gameDetails from dataBase
fun getLocalGameDetails(context: Context): GameBean {
data = AppDatabase.getInstance(context).gameDetailsDao().getGameDetails()
return data
}
}<file_sep>package com.android.vira.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.android.vira.adapters.callBacks.GameClickCallBack
import com.android.vira.api.models.response.GameBean
import com.android.vira.databinding.ItemGamesBinding
import org.greenrobot.eventbus.EventBus
/**
* Created by HosseinBahrami at 1/19/2020
*/
class GameListAdapter(private var games: List<GameBean>) :
RecyclerView.Adapter<GameListAdapter.GamesViewHolder>() {
init {
setHasStableIds(true)
}
inner class GamesViewHolder(
private val binding: ItemGamesBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: GameBean) {
binding.data = item
binding.rate.rating = item.rate.toFloat()
binding.playersCount.text = item.playerCount.toString()
binding.game.setOnClickListener { EventBus.getDefault().post(item) }
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GamesViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemGamesBinding.inflate(inflater)
return GamesViewHolder(binding)
}
override fun onBindViewHolder(holder: GamesViewHolder, position: Int) {
holder.bind(games[position])
}
override fun getItemCount(): Int = games.size
override fun getItemViewType(position: Int): Int = position
override fun getItemId(position: Int): Long = games[position].id.toLong()
}<file_sep>package com.android.vira.api.models.response
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
@Entity
data class GameBean(
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "description") val description: String,
@ColumnInfo(name = "rate") val rate: String,
@ColumnInfo(name = "players_count") @SerializedName("players_count") val playerCount: Int,
@Embedded val genre: GenreBean,
@ColumnInfo(name = "image") val image: String,
@ColumnInfo(name = "video") val video: String
) {
constructor() : this(0,"","","",0,GenreBean(), "","")
} | acb2db7713d842cb4e2efabfbe0134dbbfc2fee3 | [
"Markdown",
"Kotlin",
"Gradle"
] | 24 | Kotlin | hosseinbahrami75/ViraTest | c2f450f14c6ab52728d4da5e228b0b9c71831764 | 7a5d6242f03a16adf53b553f683e86e069b98f83 |
refs/heads/master | <repo_name>rushhit/testvue<file_sep>/src/main.js
import Vue from 'vue';
import App from './App.vue';
import VueResource from 'vue-resource';
import * as VueGoogleMaps from "vue2-google-maps";
import VueRouter from 'vue-router';
import store from './store';
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';
import prompt from 'vue-prompt';
Vue.use(prompt);
Vue.use(Loading);
Vue.use(VueRouter);
Vue.use(VueGoogleMaps, {
load: {
key: "<KEY>",
libraries: "places" // necessary for places input
}
});
Vue.use(VueResource);
Vue.config.productionTip = false
Vue.http.options.emulateJSON = true
new Vue({
render: h => h(App),
store,
}).$mount('#app')
| 19329ad86831efc37e6d816b62ce2947d29ae631 | [
"JavaScript"
] | 1 | JavaScript | rushhit/testvue | f22cd7cf2419da1e527bf1b7689408915fe84dc1 | 4247c79567719d41ad6cc2a1fb4a8cd6d6d8535f |
refs/heads/master | <repo_name>tyhhs/wechat-server<file_sep>/src/main/java/com/tyh/util/Constant.java
package com.tyh.util;
public class Constant {
public static final String TEXT_MESSAGE_TYPE = "text";
public static final String EVENT_MESSAGE_TYPE = "event";
}
| a461311aaeff2773c38a233d0a000243c65905c0 | [
"Java"
] | 1 | Java | tyhhs/wechat-server | c6b9ab335e1cf18d625e15c2bd238c83c7a895ee | e0ef3f68ecd8a3ebdbf3d4910f5bab8e8aeb1293 |
refs/heads/master | <file_sep>window.onload = () => {
const preload = setTimeout( () => {
document.getElementById("loader").classList.add('hidden');
document.getElementById("container").classList.remove('hidden');
}, 2000);
}
window.initMap = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((ubiety) => {
let map, infoWindow, service;
const latitude = ubiety.coords.latitude;
const longitude = ubiety.coords.longitude;
const myPosition = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById ('map'), {
center: myPosition,
zoom: 18
});
const myMarker = new google.maps.Marker({
position: myPosition,
map: map
});
});
const error = (error) => {
alert(error);
}
} else {
alert(error);
}
}
const handleError = () => {
alert('Se ha presentado un error');
}
const getFood = (callback) => {
const foodRequest = new XMLHttpRequest();
foodRequest.open('GET', `data.json`);
foodRequest.onload = callback;
foodRequest.onerror = handleError;
foodRequest.send();
}
const locationFood = (latitude, longitude) => {
const positionFood = new google.maps.LatLng(latitude, longitude);
map = new google.maps.Map(document.getElementById ('map'), {
center: positionFood,
zoom: 18
});
const myMarker = new google.maps.Marker({
position: positionFood,
map: map
});
}
const dataTable = (data) => {
const showFood = document.getElementById('container-food');
showFood.innerHTML = '';
Object.keys(data).forEach((id) => {
const food = data[id];
showFood.innerHTML += `
<div class="row" id=${id}>
<div class="col s12 m12">
<div class="card horizontal">
<div class="card-image waves-effect waves-block waves-light">
<img src="${food.image}" alt="image food" width="400px" height="300px">
</div>
<div class="card-content black-text">
<p class="card-title activator">${food.name}</p>
<p><a href="#" onclick="locationFood('${food.latitude}','${food.longitude}')">Ver Ubicación</a></p>
</div>
<div class="card-reveal black">
<span class="card-title white-text text-darken-4">${food.name}
<i class="material-icons right">close</i></span>
<p>Dirección: ${food.address}</p>
<p>Tel. reserva: ${food.phone}</p>
<p>Tipo de comida: ${food.typeFood}</p>
</div>
</div>
</div>
</div>
`
})
}
const listFood = () => {
getFood(() => {
const dataFood = JSON.parse(event.currentTarget.responseText);
dataTable(dataFood);
})
}
const filterRestaurant = (foods, search, filterOption) => {
let filterFoods;
switch (filterOption) {
case "name" :
filterFoods = foods.filter((food) => {
return food.name.toLowerCase().indexOf(search.toLowerCase()) > -1;
});
return filterFoods;
break;
case "district" :
filterFoods = foods.filter((city) => {
return city.district === search;
});
return filterFoods;
break;
case "type" :
filterFoods = foods.filter((type) => {
return type.typeFood === search;
});
return filterFoods;
break;
}
}
const filterFood = () => {
getFood(() => {
const dataFood = JSON.parse(event.currentTarget.responseText);
const searchFood = document.getElementById('search');
const filterDistrict = document.getElementById('district');
const filterType = document.getElementById('typeFood');
searchFood.addEventListener('keyup', () => {
let search = searchFood.value;
let selectFood = filterRestaurant(dataFood, search, "name");
dataTable(selectFood);
})
filterDistrict.addEventListener('change', (e) => {
let district = e.target.value;
if (district != '') {
let selectDistrict = filterRestaurant(dataFood, district, "district");
dataTable(selectDistrict);
} else {
listFood();
}
})
filterType.addEventListener('change', (e) => {
let typeFood = e.target.value;
if (typeFood != '') {
let selectType = filterRestaurant(dataFood, typeFood, "type");
dataTable(selectType);
} else {
listFood();
}
})
})
}
document.addEventListener('DOMContentLoaded', () => {
const elems = document.querySelectorAll('select');
const instances = M.FormSelect.init(elems);
});
listFood();
filterFood();
getFood();
| 20d70179613a9c99ac001cdf494e4e38434b230e | [
"JavaScript"
] | 1 | JavaScript | Geraldine13/lim-2018-01-foodmap | 4f80bcca89410445d9386c82d915a47f87978f40 | afd344e5bf5f49ddf1dbee05e8f91af28c3ee68c |
refs/heads/master | <file_sep><?php
if(isset($_POST['addTrainer'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['trainerName'];
$desc = $_POST['trainerDesc'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('INSERT INTO trainer_class (class_name, description) VALUES (?, ?)');
$stmt->bind_param('ss', $name, $desc);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addTrainerType'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['trainerDropdown'];
$type = $_POST['typeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('SELECT class_id FROM trainer_class WHERE class_name = (?)');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($trid);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn2->prepare('SELECT type_id FROM types WHERE type_name = (?)');
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->bind_result($tid);
$results = $stmt->fetch();
$conn3 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn3->prepare('INSERT INTO trainer_pkmntypes (trainer_id, type_id) VALUES (?, ?)');
$stmt->bind_param('ss', $trid, $tid);
$types = $_POST['typeDropdown'];
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addPokemon'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$id = $_POST['pokeID'];
$name = $_POST['pokeName'];
$desc = $_POST['pokeDesc'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('INSERT INTO pokemon (pokemon_id, name, description) VALUES (?, ?, ?)');
$stmt->bind_param('dss', $id, $name, $desc);
$stmt->execute();
$stmt->close();
}
if(isset($_POST['addEvolution'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$evolution = $_POST['evolutionDropdown'];
$predecessor = $_POST['predecessorDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('SELECT pokemon_id FROM pokemon WHERE name = (?)');
$stmt->bind_param('s', $evolution);
$stmt->execute();
$stmt->bind_result($eid);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn2->prepare('SELECT pokemon_id FROM pokemon WHERE name = (?)');
$stmt->bind_param('s', $predecessor);
$stmt->execute();
$stmt->bind_result($pid);
$results = $stmt->fetch();
$conn3 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn3->prepare('INSERT INTO pokemon_predecessor (evolution_pid, predecessor_pid) VALUES (?, ?)');
$stmt->bind_param('ss', $eid, $pid);
$types = $_POST['typeDropdown'];
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addSighting'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$location = $_POST['locationDropdown'];
$evolution = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT location_id FROM locations WHERE location_name = ?');
$stmt->bind_param('s', $location);
$stmt->execute();
$stmt->bind_result($lid);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt2 = $conn2->prepare('SELECT pokemon_id from pokemon WHERE name = ?');
$stmt2->bind_param('s', $name);
$stmt2->execute();
$stmt2->bind_result($pid);
$results = $stmt2->fetch();
$conn3 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn3->prepare('INSERT INTO pokemon_location (pid, lid) VALUES (?, ?)');
$stmt->bind_param('ss', $pid, $lid);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addMovePoke'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$move = $_POST['moveDropdown'];
$pokemon = $_POST['pokemonDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT move_id FROM moves WHERE move_name = ?');
$stmt->bind_param('s', $move);
$stmt->execute();
$stmt->bind_result($mid);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt2 = $conn2->prepare('SELECT pokemon_id from pokemon WHERE name = ?');
$stmt2->bind_param('s', $pokemon);
$stmt2->execute();
$stmt2->bind_result($pid);
$results = $stmt2->fetch();
$conn3 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn3->prepare('INSERT INTO pokemon_moves (mid, pid) VALUES (?, ?)');
$stmt->bind_param('dd', $mid, $pid);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addType'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$name = $_POST['typeName'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('INSERT INTO types (type_name) VALUES (?)');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addLocation'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$name = $_POST['locationName'];
$desc = $_POST['locationDesc'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('INSERT INTO locations (location_name, description) VALUES (?, ?)');
$stmt->bind_param('ss', $name, $desc);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['deletePokemon'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$name = $_POST['pokemonName'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('DELETE FROM pokemon WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['deleteType'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$type = $_POST['pokemonType'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('DELETE FROM types WHERE type_name = ?');
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['deleteLocation'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$location = $_POST['locationName'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('DELETE FROM locations WHERE location_name = ?');
$stmt->bind_param('s', $location);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['deleteTrainer'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$name = $_POST['trainerName'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('DELETE FROM trainer_class WHERE class_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addPokeType'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokemonName'];
$type = $_POST['pokemonType'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('SELECT type_id FROM types WHERE type_name = ?');
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->bind_result($tid);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn2->prepare('SELECT pokemon_id FROM pokemon WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($pid);
$results = $stmt->fetch();
$conn3 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn3->prepare('INSERT INTO pokemon_types (pid, tid) VALUES (?, ?)');
$stmt->bind_param('dd', $pid, $tid);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['addMove'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['moveName'];
$base = $_POST['baseDmg'];
$power = $_POST['power'];
$desc = $_POST['moveDesc'];
$type = $_POST['moveType'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('SELECT type_id FROM types WHERE type_name = (?)');
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->bind_result($moveType);
$results = $stmt->fetch();
$conn2 = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn2->prepare('INSERT INTO moves (move_name, type, base_dmg, power_pts, description) VALUES (?, ?, ?, ?, ?)');
$stmt->bind_param('sddds', $name, $moveType, $base, $power, $desc);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['deleteMove'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$move = $_POST['moveOptions'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('DELETE FROM moves WHERE move_name = ?');
$stmt->bind_param('s', $move);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
if(isset($_POST['updateMove'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$base = $_POST['baseDmg'];
$power = $_POST['power'];
$move = $_POST['moveName'];
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('UPDATE moves SET base_damage = (?), power_pts = (?) WHERE move_name = (?)');
$stmt->bind_param('dds', $base, $power, $move);
$stmt->execute();
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
header("Location:main.php");
exit();
?><file_sep><?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT pokemon_id, name, description FROM pokemon";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo '<table cellpadding="1" cellspacing="0.5" class="poke-table" border="solid">';
echo '<tr><th>Pokemon Index</th><th>Name</th><th>Description</th></tr>';
while($row = $result->fetch_assoc()) {
echo '<tr>';
foreach($row as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
} else {
echo "0 results";
}
$conn->close();
?><file_sep># pokedb
Pokémon database for CS 340: Introduction to Databases
[Final page](http://web.engr.oregonstate.edu/~kuos/pokemon/main.php)
Based on Generation I (Red/Blue/Yellow).
Outline and description of project, with entity-relationship (ER) diagram and schema: [pokemondb.pdf](https://github.com/cherun/pokedb/blob/master/pokemondb.pdf)
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pokemon Database</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<script src="javascript/jquery.min.js"></script>
<script src="javascript/bootstrap.min.js"></script>
</head>
<body>
<div id="headline" class="jumbotron">
<h1>The Pokemon Database</h1>
</div>
<div>
<div class="container-fluid">
<form action="main.php" method="POST">
Select a Pokemon to learn more about it: <select id = "pokeDropdown" name = "pokeDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="pokeButton" type="submit" class="btn-primary" value="Scan PokeDex"/>
</form>
</div>
</div>
<div id="tableHolder">
<table class="table">
<tr>
<th>Pokedex ID</th>
<th>Pokemon Name</th>
<th>Description</th>
<th>Possible Moves</th>
<th>Type</th>
<th>Locations</th>
<th>Evolves From</th>
</tr>
<tr>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT pokemon_id FROM pokemon WHERE name=?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($pokeID);
$results = $stmt->fetch();
echo $pokeID;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
echo $_POST['pokeDropdown'];
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT description FROM pokemon WHERE name=?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($pokeDesc);
$results = $stmt->fetch();
echo $pokeDesc;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT move_name FROM moves
INNER JOIN pokemon_moves
ON moves.move_id = pokemon_moves.mid
INNER JOIN pokemon
ON pokemon_moves.pid = pokemon.pokemon_id
WHERE pokemon.name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$moves = "";
$stmt->bind_result($moves);
while ($stmt->fetch()) {
echo $moves."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT type_name FROM types
INNER JOIN pokemon_types
ON types.type_id = pokemon_types.tid
INNER JOIN pokemon
ON pokemon_types.pid = pokemon.pokemon_id
WHERE pokemon.name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$types = "";
$stmt->bind_result($types);
while ($stmt->fetch()) {
echo $types."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT location_name FROM locations
INNER JOIN pokemon_location
ON locations.location_id = pokemon_location.lid
INNER JOIN pokemon
ON pokemon_location.pid = pokemon.pokemon_id
WHERE pokemon.name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$location = "";
$stmt->bind_result($location);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
while ($stmt->fetch()) {
echo $location."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['pokeButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['pokeDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT p1.name FROM pokemon p1
INNER JOIN pokemon_predecessor pp ON pp.predecessor_pid = p1.pokemon_id
INNER JOIN pokemon p2 ON p2.pokemon_id = pp.evolution_pid
WHERE p2.name = ?;');
$stmt->bind_param('s', $name);
$stmt->execute();
$predecessor = "";
$stmt->bind_result($predecessor);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
while ($stmt->fetch()) {
echo $predecessor."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
</tr>
</table>
</div>
<hr>
<div>
<div class="container-fluid">
<form name="addPokeForm" action='queries.php' method='POST'>
Add a new Pokemon:<br>
ID: <input type="number" id="pokeID" name="pokeID" value="Pokemon ID" min="1" max="151"/>
Name: <input type="text" id="pokeName" name ="pokeName" value="Pokemon Name" onfocus="if (this.value=='Pokemon Name') this.value='';"/>
Description: <input type="text" id="pokeDesc" name ="pokeDesc" value="Description" onfocus="if (this.value=='Description') this.value='';"/>
<input name="addPokemon" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method = 'POST'>
Add a Pokemon evolution:<br>
Evolution: <select id = "evolutionDropdown" name = "evolutionDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($evolution);
$evolution = $row['name'];
echo '<option value="'.$evolution.'">'.$evolution.'</option>';
}
$conn->close();
?>
</select>
Predecessor: <select id = "predecessorDropdown" name = "predecessorDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($predecessor);
$predecessor = $row['name'];
echo '<option value="'.$predecessor.'">'.$predecessor.'</option>';
}
$conn->close();
?>
</select>
<input name="addEvolution" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form name="addPokeForm" action='queries.php' method='POST'>
Add a type to a pokemon:<br>
Name: <select id = "pokemonName" name = "pokemonName">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
Type: <select id = "pokemonType" name = "pokemonType">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT type_name FROM types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($type);
$type = $row['type_name'];
echo '<option value="'.$type.'">'.$type.'</option>';
}
$conn->close();
?>
</select>
<input name="addPokeType" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Delete a Pokemon:<br>
Name: <select id = "pokemonName" name = "pokemonName">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="deletePokemon" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Add a type:<br>
Name: <input type="text" id="typeName" name="typeName" value="Type Name" onfocus="if (this.value=='Type Name') this.value='';"/>
<input name="addType" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Delete type:<br>
Name: <select id = "pokemonType" name = "pokemonType">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT type_name FROM types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($types);
$types = $row['type_name'];
echo '<option value="'.$types.'">'.$types.'</option>';
}
$conn->close();
?>
</select>
<input name="deleteType" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action="main.php" method="POST">
Select a Move to learn more about it: <select id = "moveDropdown" name = "moveDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT move_name FROM moves";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['move_name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="moveButton" type="submit" class="btn-primary" value="Scan PokeDex"/>
</form>
</div>
</div>
<div id="tableHolder">
<table class="table">
<tr>
<th>Move Name</th>
<th>Type</th>
<th>Base Damage</th>
<th>Power Points</th>
<th>Description</th>
</tr>
<tr>
<td>
<?php
if(isset($_POST['moveButton'])){
echo $_POST['moveDropdown'];
}
?>
</td>
<td>
<?php
if(isset($_POST['moveButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['moveDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT type_name FROM types
INNER JOIN moves
ON moves.type = types.type_id
WHERE moves.move_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($type);
$result = $stmt->fetch();
echo $type;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['moveButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['moveDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT base_dmg FROM moves WHERE move_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($base);
$results = $stmt->fetch();
echo $base;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['moveButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['moveDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT power_pts FROM moves WHERE move_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($power);
$results = $stmt->fetch();
echo $power;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['moveButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['moveDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT description FROM moves WHERE move_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($desc);
$results = $stmt->fetch();
echo $desc;
$stmt->close();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
}
?>
</td>
</tr>
</table>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Add a move:<br>
Name: <input type="text" id="moveName" name="moveName" value="Move Name" onfocus="if (this.value=='Move Name') this.value='';"/>
Type: <select id = "moveType" name = "moveType">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT type_name FROM types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($type);
$type = $row['type_name'];
echo '<option value="'.$type.'">'.$type.'</option>';
}
$conn->close();
?>
</select>
Base Damage: <input type="number" id="baseDmg" name="baseDmg" max="120"/>
Power Points: <input type="number" id="power" name="power" min = "0" max = "100"/>
Description: <input type="text" id="moveDesc" name="moveDesc" value="Move Description" onfocus="if (this.value=='Move Description') this.value='';"/>
<input name="addMove" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Update a move:<br>
Name: <select id = "moveName" name = "moveName">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT move_name FROM moves";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['move_name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
Base Damage: <input type="number" id="baseDmg" name="baseDmg" value="Base Damage" min="0" max="120"/>
Power Points: <input type="number" id="power" name="power" value="Type Name" min = "0" max = "100" />
<input name="updateMove" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method = 'POST'>
Add a move to a Pokemon:<br>
Move: <select id = "moveDropdown" name = "moveDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT move_name FROM moves";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($move);
$move = $row['move_name'];
echo '<option value="'.$move.'">'.$move.'</option>';
}
$conn->close();
?>
</select>
Pokemon: <select id = "pokemonDropdown" name = "pokemonDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($pokemon);
$pokemon = $row['name'];
echo '<option value="'.$pokemon.'">'.$pokemon.'</option>';
}
$conn->close();
?>
</select>
<input name="addMovePoke" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Delete move:<br>
Name: <select id = "moveOptions" name = "moveOptions">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT move_name FROM moves";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($moves);
$moves = $row['move_name'];
echo '<option value="'.$moves.'">'.$moves.'</option>';
}
$conn->close();
?>
</select>
<input name="deleteMove" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Add a location:<br>
Name: <input type="text" id="locationName" name="locationName" value="Location Name" onfocus="if (this.value=='Location Name') this.value='';"/>
Description: <input type="text" id="locationDesc" name="locationDesc" value="Location Description" onfocus="if (this.value=='Location Description') this.value='';"/>
<input name="addLocation" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Delete a location:<br>
Location: <select id = "locationName" name = "locationName">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT location_name FROM locations";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($location);
$location = $row['location_name'];
echo '<option value="'.$location.'">'.$location.'</option>';
}
$conn->close();
?>
</select>
<input name="deleteLocation" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Add a known Pokemon sighting:<br>
Pokemon: <select id = "pokeDropdown" name = "pokeDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM pokemon";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
Location: <select id = "locationDropdown" name = "locationDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT location_name FROM locations";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['location_name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="addSighting" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action="main.php" method="POST">
Select a trainer to learn about them: <select id = "trainerDropdown" name = "trainerDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT class_name FROM trainer_class";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['class_name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="trainerButton" type="submit" class="btn-primary" value="Scan PokeDex"/>
</form>
</div>
</div>
<div id="tableHolder">
<table class="table"
<tr>
<th>Trainer Class</th>
<th>Description</th>
<th>Pokemon Types</th>
</tr>
<tr>
<td>
<?php
echo $_POST['trainerDropdown'];
?>
</td>
<td>
<?php
if(isset($_POST['trainerButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['trainerDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT description FROM trainer_class
WHERE class_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$desc = "";
$stmt->bind_result($desc);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
while ($stmt->fetch()) {
echo $desc."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
<td>
<?php
if(isset($_POST['trainerButton'])){
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
$name = $_POST['trainerDropdown'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare('SELECT type_name FROM types
INNER JOIN trainer_pkmntypes
ON types.type_id = trainer_pkmntypes.type_id
INNER JOIN trainer_class
ON trainer_pkmntypes.trainer_id = trainer_class.class_id
WHERE class_name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$types = "";
$stmt->bind_result($types);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
while ($stmt->fetch()) {
echo $types."<br>";
}
$stmt->close();
$conn->close();
}
?>
</td>
</tr>
</table>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method = 'POST'>
Add a trainer<br>
Name: <input type="text" id="trainerName" name ="trainerName" value="Trainer Name" onfocus="if (this.value=='Trainer Name') this.value='';"/>
Description: <input type="text" id="trainerDesc" name ="trainerDesc" value="Description" onfocus="if (this.value=='Description') this.value='';"/>
<input name="addTrainer" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method = 'POST'>
Add a type to a trainer:<br>
Trainer Name: <select id = "trainerDropdown" name = "trainerDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT class_name FROM trainer_class";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($class);
$class = $row['class_name'];
echo '<option value="'.$class.'">'.$class.'</option>';
}
$conn->close();
?>
</select>
Pokemon Types: <select id = "typeDropdown" name = "typeDropdown">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT type_name FROM types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($type);
$type = $row['type_name'];
echo '<option value="'.$type.'">'.$type.'</option>';
}
$conn->close();
?>
</select>
<input name="addTrainerType" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<div class="container-fluid">
<form action='queries.php' method='POST'>
Delete a trainer class:<br>
Location: <select id = "trainerName" name = "trainerName">
<?php
$servername = "oniddb.cws.oregonstate.edu";
$username = "anderleo-db";
$password = "<PASSWORD>";
$dbname = "anderleo-db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT class_name FROM trainer_class";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
unset($name);
$name = $row['class_name'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
$conn->close();
?>
</select>
<input name="deleteTrainer" type="submit" class="btn-primary" value="Update PokeDex"/>
</form>
</div>
</div>
<hr>
<div>
<br/><br/>
</div>
</body>
</html><file_sep>-- ----------------------------------------------------------------------------
-- Pokémon Database
-- Generation I (Red/blue/yellow/green)
-- Kanto region
-- ----------------------------------------------------------------------------
DROP TABLE IF EXISTS `pokemon_types`;
DROP TABLE IF EXISTS `pokemon_predecessor`;
DROP TABLE IF EXISTS `pokemon_moves`;
DROP TABLE IF EXISTS `pokemon_location`;
DROP TABLE IF EXISTS `trainer_pkmntypes`;
DROP TABLE IF EXISTS `trainer_class`;
DROP TABLE IF EXISTS `moves`;
DROP TABLE IF EXISTS `locations`;
DROP TABLE IF EXISTS `pokemon`;
DROP TABLE IF EXISTS `types`;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`types`
-- Pokémon types in Generation I
-- ----------------------------------------------------------------------------
CREATE TABLE `types` (
`type_id` int(11) NOT NULL AUTO_INCREMENT,
`type_name` varchar(255) NOT NULL,
PRIMARY KEY (`type_id`),
UNIQUE KEY (`type_name`)
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`pokemon`
-- Pokémon species in Generation I
-- ----------------------------------------------------------------------------
CREATE TABLE `pokemon` (
`pokemon_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255),
PRIMARY KEY (`pokemon_id`),
UNIQUE KEY (`name`)
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`locations`
-- Locations in the Kanto region
-- ----------------------------------------------------------------------------
CREATE TABLE `locations` (
`location_id` int(11) NOT NULL AUTO_INCREMENT,
`location_name` varchar(255) NOT NULL,
`description` varchar(255),
PRIMARY KEY (`location_id`),
UNIQUE KEY (`location_name`)
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`moves`
-- Pokémon moves in Generation I
-- ----------------------------------------------------------------------------
CREATE TABLE `moves` (
`move_id` int(11) NOT NULL AUTO_INCREMENT,
`move_name` varchar(255) NOT NULL,
`type` int(11) NOT NULL,
`base_dmg` int(11) DEFAULT NULL,
`power_pts` int(11),
`description` varchar(255),
PRIMARY KEY (`move_id`),
UNIQUE KEY (`move_name`),
FOREIGN KEY (`type`) REFERENCES `types` (`type_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`trainer_class`
-- Trainer classes encountered in Generation I games
-- ----------------------------------------------------------------------------
CREATE TABLE `trainer_class` (
`class_id` int(11) NOT NULL AUTO_INCREMENT,
`class_name` varchar(255) NOT NULL,
`description` varchar(255),
PRIMARY KEY (`class_id`),
UNIQUE KEY (`class_name`)
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`trainer_pkmntypes`
-- Trainers and Pokémon types typically owned by trainer classes
-- Many-to-many (trainer and Pokemon types)
-- ----------------------------------------------------------------------------
CREATE TABLE `trainer_pkmntypes` (
`trainer_id` int(11) NOT NULL,
`type_id` int(11) NOT NULL,
PRIMARY KEY (`trainer_id`, `type_id`),
FOREIGN KEY (`trainer_id`) REFERENCES `trainer_class` (`class_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`type_id`) REFERENCES `types` (`type_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`pokemon_location`
-- Pokémon found in locations in the Kanto region
-- Many-to-many (location and Pokémon species)
-- ----------------------------------------------------------------------------
CREATE TABLE `pokemon_location` (
`pid` int(11) NOT NULL,
`lid` int(11) NOT NULL,
PRIMARY KEY (`pid`, `lid`),
FOREIGN KEY (`pid`) REFERENCES `pokemon` (`pokemon_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`lid`) REFERENCES `locations` (`location_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`pokemon_moves`
-- Moves learned by Pokemon species
-- Many-to-many (moves and Pokémon species)
-- ----------------------------------------------------------------------------
CREATE TABLE `pokemon_moves` (
`mid` int(11) NOT NULL,
`pid` int(11) NOT NULL,
PRIMARY KEY (`mid`, `pid`),
FOREIGN KEY (`mid`) REFERENCES `moves` (`move_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`pid`) REFERENCES `pokemon` (`pokemon_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`pokemon_predecessor`
-- Pokémon and their predecessors
-- One-to-many relationship (one Pokémon can have many predecessors)
-- ----------------------------------------------------------------------------
CREATE TABLE `pokemon_predecessor` (
`evolution_pid` int(11) NOT NULL,
`predecessor_pid` int(11) NOT NULL,
PRIMARY KEY (`evolution_pid`, `predecessor_pid`),
FOREIGN KEY (`evolution_pid`) REFERENCES `pokemon` (`pokemon_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`predecessor_pid`) REFERENCES `pokemon` (`pokemon_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
-- ----------------------------------------------------------------------------
-- `pokemon_db`.`pokemon_types`
-- Pokémon and their types
-- Many-to-many relationship (Pokémon can have 1-2 types, and types can have
-- many Pokémon)
-- ----------------------------------------------------------------------------
CREATE TABLE `pokemon_types` (
`pid` int(11) NOT NULL,
`tid` int(11) NOT NULL,
PRIMARY KEY (`pid`, `tid`),
FOREIGN KEY (`pid`) REFERENCES `pokemon` (`pokemon_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`tid`) REFERENCES `types` (`type_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB; | 52e2f98fcb02ec76d1ed2179a59a36f9cedec88a | [
"Markdown",
"SQL",
"PHP"
] | 5 | PHP | cherun/pokedb | 112714f7795848ceef34811425beeafbeef7cbbb | 0dcf69be599e5fbf8151f3468f164e118b8b6287 |
refs/heads/master | <file_sep>Run files in this order;
1. processingscript.R
2. exploration.Rmd
3. analysis.Rmd
4. model_analysis.Rmd
5. mach_learn_analysis.Rmd<file_sep>---
title: "exploration"
author: "<NAME>"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
#Overview
This markdown loads processed data and explores relationships among these variables:
- SwollenLymphNodes: yes/no experienced swollen lymph nodes
- ChestCongestion: yes/no experienced chest congestion
- ChillsSweats: yes/no experienced chills or sweats
- Fatigue: yes/no experienced fatigue
- Headache: yes/no experienced headache
- RunnyNose: yes/no experienced runny nose
- Nausea: yes/no experienced nausea
- Pharyngitis: yes/no experienced sore throat
- BodyTemp: numeric, body temperature (F)
- AbPain: yes/no experienced abdominal pain
- NasalCongestion: yes/no experienced nasal congestion
#Main outcomes
Main continuous outcome: BodyTemp
Main categorical outcome: Nausea
# load packages and data
```{r}
library(dplyr)
library(tidyverse)
library(here)
library(gtsummary) #for summary table
# set data location
data_location <- data_location <- here::here("data","processed_data","processeddata.rds")
# load data
data <- readRDS(data_location)
```
# view summary statistics for variables of interest
```{r}
summary(data) %>% print()
```
In this summary view, we can see the values for each variables (yes vs no) and the statistics for our one continuous variable, BodyTemp. For our key categorical variable, let's view our summary statistics as proportions.
# Nausea proportions
```{r}
table1 <- table(data$Nausea)
prop.table(table1) %>% print()
```
Significantly more people did NOT experience nausea than did experience nausea.
# make a nicer looking summary table for our variables
```{r}
table2 <- tbl_summary(data, type = all_categorical() ~ "categorical")
#view table
table2
#save table
saveRDS(table2, file = here("results", "EDA", "summarytable.rds"))
```
# plot for continuous variable (BodyTemp)
```{r}
histogram <- data %>% ggplot(aes(BodyTemp)) + geom_histogram(bins = 30)
#save table
saveRDS(histogram, file = here("results", "EDA", "histogrambodytemp.rds"))
#view table
histogram
```
Our summary statistics above tell us that the mean BodyTemp is 98.9. A median of 98.5 and the histogram above tell us that the values range up to 103, relatively high.
# plot for categorical outcome of interest
```{r}
nauseabarplot <- data %>% ggplot(aes(Nausea)) + geom_bar()
#view plot
nauseabarplot
#save plot
saveRDS(nauseabarplot, file = here("results", "EDA", "nauseabarplot.rds"))
```
Next, let's look at our outcomes of interest (**BodyTemp** and **Nausea**) versus some potential predictors. A few predictors I'd like to look at are:
- RunnyNose
- Pharyngitis
- Fatigue
- ChillsSweats
- SwollenLymphNodes
### plots for outcomes vs predictors
##Plots for body temperature
#BodyTemp and nausea
```{r}
data %>% ggplot(aes(Nausea, BodyTemp)) + geom_boxplot()
```
Here, we are looking to see how our outcomes of interest relate to each other. Cases with Nausea are shifted slightly updwards for BodyTemp, but only equivalent to <0.25 degrees F.
Let's look at some other predictors for our main outcomes.
# BodyTemp and RunnyNose
```{r}
data %>% ggplot(aes(RunnyNose, BodyTemp)) + geom_boxplot()
```
Body temperature appears to decrease in cases of runny nose.
# BodyTemp and fatigue
```{r}
data %>% ggplot(aes(Fatigue, BodyTemp)) + geom_boxplot()
```
This figure shows that individuals experiencing fatigue had higher body temperatures than those not experiencing fatigue.
# Body temperature and swollen lymph nodes
```{r}
data %>% ggplot(aes(SwollenLymphNodes, BodyTemp)) + geom_boxplot()
```
There isn't a clear difference in Body Temp for cases experiencing swollen lymph nodes versus not.
#body temp and chills/sweats
```{r}
data %>% ggplot(aes(ChillsSweats, BodyTemp)) + geom_boxplot()
```
This figure shows that individuals experiencing chills/sweats had higher body temperatures than those not experiencing chills/sweats. Based on these preliminary figures, my predictors of interest for BodyTemp could be **ChillsSweats** and **Fatigue**.
Next, let's look at Nausea. The data visualization cheat sheet suggests `geom_count` for comparing two categorical variables. We'll see what that looks like. With these plots, we're looking for yes/yes cases to have the largest frequency - that would help us narrow down what might be a predictor of Nausea.
##Plots for nausea
# Nausea and fatigue
```{r}
data %>% ggplot(aes(Nausea, Fatigue)) + geom_count()
```
There are more cases of fatigue and no nausea, than of fatigue and nausea.
# Nausea and swollen lymph nodes
```{r}
data %>% ggplot(aes(Nausea, SwollenLymphNodes)) + geom_count()
```
This figure shows that the majority the observations are no/no. No clear relationships here.
# Nausea and chills/sweats
```{r}
data %>% ggplot(aes(Nausea, ChillsSweats)) + geom_count()
```
There aren't any super clear assocations between nausea and the other predictors we have explored so far (clear association = significantly different counts of yes/yes observations vs yes/no or no/no). Let's look at headache and abdominal pain before moving on.
# Nausea and headache
```{r}
data %>% ggplot(aes(Nausea, Headache)) + geom_count()
```
It looks like the most frequent pairing of observations is yes/headache and no/nausea, but I can't tell from this figure how different that association is from the yes/headache and yes/nausea observations.
# Nausea and abdominal pain
```{r}
data %>% ggplot(aes(Nausea, AbPain)) + geom_count()
```
This figure shows what is probably the most noticable association, but since the association is for no/no responses, this may not be very informative for modeling our data. We can check out a few more variables to see if there are assocations.
# Nausea and chest congestion
```{r}
data %>% ggplot(aes(Nausea, ChestCongestion)) + geom_count()
```
There are some cases of nausea and chest congestion, but at a lower frequency than cases of no/no or yes/chest congestion and no/nausea.
#Nausea and ChestCongestion
```{r}
data %>% ggplot(aes(Nausea, ChestCongestion)) + geom_count()
```
This figure shows us that the most frequent observations are for cases of no/nausea and yes/nasal congestion.
#Nausea and runny nose
```{r}
data %>% ggplot(aes(Nausea, RunnyNose)) + geom_count()
```
This figure shows the most cases of yes/runnynose and no/nausea.
Based on this exploration, **ChillsSweats** and **Fatigue** might be predictors of body temperature, while I am unsure of which predictors will be suitable for cases of nausea. The figures that I looked at showed some associations, but I am unsure if they are strong enough associations for our modeling exericise, or if the associations themselves are informative enough.
For now, my exploration did not lead me to do any additional cleaning, so no additional cleaned data file needs to be saved at this point. I could potentially remove some variables to create a smaller, streamlined dataset, but I think that some symptom variables may be useful during the modeling portion (even if I don't realize it yet).
<file_sep>###############################
# processing script
#
#this script loads the raw data, processes and cleans it
#and saves it as Rds file in the processed_data folder
#load needed packages. make sure they are installed.
library(readxl) #for loading Excel files
library(dplyr) #for data processing
library(here) #to set paths
#path to data
#note the use of the here() package and not absolute paths
data_location <- here::here("data","raw_data","SympAct_Any_Pos.Rda")
#load data.
#note that for functions that come from specific packages (instead of base R)
# I often specify both package and function like so
#package::function() that's not required one could just call the function
#specifying the package makes it clearer where the function "lives",
#but it adds typing. You can do it either way.
rawdata <- readRDS(data_location)
#take a look at the data
dplyr::glimpse(rawdata)
#removing unneeded variables
cleandata1 <- rawdata %>% select(-contains("Score"))
cleandata2 <- cleandata1 %>% select(-contains("FluA"))
cleandata3 <- cleandata2 %>% select(-contains("FluB"))
cleandata4 <- cleandata3 %>% select(-contains("Total"))
cleandata5 <- cleandata4 %>% select(-contains("FluA"))
cleandata6 <- cleandata5 %>% select(-contains("Dxname"))
cleandata7 <- cleandata6 %>% select(-contains("Activity"))
cleandata8 <- cleandata7 %>% select(-"Unique.Visit")
#After cleaning the data according to the instructions we have 32 variables, as expected.
#We know that one variable, BodyTemp, should be continuous. Let's check the class.
class(cleandata8$BodyTemp)
#It is numeric, so we should be good to go.
#Remove missing values
processeddata <- na.omit(cleandata8)
#Now we have 730 observations of 32 variables, as expected.
#11/4/21 - After learning about model evaluation and machine learning, we will
#do additional pre-processing of the data
#Feature/variable removal
#We want to remove redundant variables by removing yes/no versions of 4 variables
processeddata <- processeddata %>% select(-"CoughYN",
-"WeaknessYN",
-"CoughYN2",
-"MyalgiaYN")
#code three symptom severity factors as ordinal
#desired order: none < mild < moderate < severe
#checking current levels
factor(processeddata$CoughIntensity)
factor(processeddata$Weakness)
factor(processeddata$Myalgia)
#currently the levels are not ordered
#mutate variables to save factor order
processeddata <- processeddata %>% mutate(CoughIntensity = ordered(processeddata$CoughIntensity,
levels = c("None", "Mild", "Moderate", "Severe")),
Weakness = ordered(processeddata$Weakness,
levels = c("None", "Mild", "Moderate", "Severe")),
Myalgia = ordered(processeddata$Myalgia,
levels = c("None", "Mild", "Moderate", "Severe")))
#checking factor order
factor(processeddata$CoughIntensity)
factor(processeddata$Weakness)
factor(processeddata$Myalgia)
#remove low variance predictors
#check for variance in predictors
summary(processeddata)
#we'll remove binary predictors with <50 entries in a given category
#remove: Hearing, Vision
processeddata <- processeddata %>% select(-"Hearing",
-"Vision")
#now our processeddata dataframe has 730 observations or 26 variables. This is
#the data we will use for modeling.
# save data as RDS
# location to save file
save_data_location <- here::here("data","processed_data","processeddata.rds")
saveRDS(processeddata, file = save_data_location)
# for the rest of the analysis, our main continuous outcome of interest is
# BodyTemp, and our categorical outcome of interest is Nausea
<file_sep>---
title: "Machine Learning Analysis"
output: html_document
---
In this file, we will refine our analysis for this exercise and incorporate some machine learning models
Outcome of interest = Body temperature (continuous, numerical)
- Corresponding model = regression
- Performance metric = RMSE
# load packages and data
```{r}
library(ggplot2) #for plotting
library(broom) #for cleaning up output from lm()
library(here) #for data loading/saving
library(tidymodels) #for modeling
library(rpart)
library(glmnet)
library(ranger)
library(rpart.plot) # for visualizing a decision tree
library(vip) # for variable importance plots
#path to data
#note the use of the here() package and not absolute paths
data_location <- here::here("data","processed_data","processeddata.rds")
#load cleaned data.
mydata <- readRDS(data_location)
```
# split data into train and test subsets
```{r}
# set seed for reproducible analysis (instead of random subset each time)
set.seed(123)
#subset 3/4 of data as training set
data_split <- initial_split(mydata,
prop = 7/10,
strata = BodyTemp) #stratify by body temp for balanced outcome
#save sets as data frames
train_data <- training(data_split)
test_data <- testing(data_split)
```
# Cross validation
We want to perform 5-fold CV, 5 times repeated
```{r}
#create folds (resample object)
set.seed(123)
folds <- vfold_cv(train_data,
v = 5,
repeats = 5,
strata = BodyTemp) #folds is set up to perform our CV
#linear model set up
lm_mod <- linear_reg() %>%
set_engine('lm') %>%
set_mode('regression')
#create recipe for data and fitting and make dummy variables
BT_rec <- recipe(BodyTemp ~ ., data = train_data) %>% step_dummy(all_nominal())
#workflow set up
BT_wflow <-
workflow() %>% add_model(lm_mod) %>% add_recipe(BT_rec)
#use workflow to prepare recipe and train model with predictors
BT_fit <-
BT_wflow %>% fit(data = train_data)
#extract model coefficient
BT_fit %>% extract_fit_parsnip() %>% tidy()
```
# Null model performance
```{r}
#recipe for null model
null_train_rec <- recipe(BodyTemp ~ 1, data = train_data) #predicts mean of outcome
#null model workflow incorporating null model recipe
null_wflow <- workflow() %>% add_model(lm_mod) %>% add_recipe(null_train_rec)
# I want to check and make sure that the null model worked as it was supposed to, so I want to view the predictions and make sure they are all the mean of the outcome
#get fit for train data using null workflow
nullfittest <- null_wflow %>% fit(data = train_data)
#get predictions based on null model
prediction <- predict(nullfittest, train_data)
test_pred <- predict(nullfittest, test_data)
#the predictions for the train and test data are all the same mean value, so this tells us the null model was set up properly
#Now, we'll use fit_resamples based on the tidymodels tutorial for CV/resampling (https://www.tidymodels.org/start/resampling/)
#fit model with training data
null_fit_train <- fit_resamples(null_wflow, resamples = folds)
#get results
metrics_null_train <- collect_metrics(null_fit_train)
#RMSE for null train fit is 1.204757
#repeat for test data
null_test_rec <- recipe(BodyTemp ~ 1, data = test_data) #predicts mean of outcome
null_test_wflow <- workflow() %>% add_model(lm_mod) %>% add_recipe(null_test_rec) #sets workflow with new test recipe
null_fit_test <- fit_resamples(null_test_wflow, resamples = folds) #performs fit
metrics_null_test <- collect_metrics(null_fit_test) #gets fit metrics
#RMSE for null test fit is 1.204757
```
The RMSE that we get for both the null test and null train models is 1.204757. We'll use this later to compare to the performance of our real models (we want any real models to perform better than this null model).
# Model tuning and fitting
Include:
1. Model specification
2. Workflow definition
3. Tuning grid specification
4. Tuning w/ cross-validation + `tune_grid()`
## Decision tree
```{r}
#going based off of tidymodels tutorial: tune parameters
#since we already split our data into test and train sets, we'll continue to use those here. they are `train_data` and `test_data`
#model specification
tune_spec <-
decision_tree(
cost_complexity = tune(),
tree_depth = tune()
) %>%
set_engine("rpart") %>%
set_mode("regression")
tune_spec
#tuning grid specification
tree_grid <- grid_regular(cost_complexity(),
tree_depth(),
levels = 5)
tree_grid
#cross validation
set.seed(123)
cell_folds <- vfold_cv(train_data)
#workflow
set.seed(123)
tree_wf <- workflow() %>%
add_model(tune_spec) %>%
add_recipe(BT_rec)
#model tuning with `tune_grid()`
tree_res <-
tree_wf %>%
tune_grid(
resamples = cell_folds,
grid = tree_grid
)
tree_res %>% collect_metrics()
#Here we see 25 candidate models, and the RMSE and Rsq for each
tree_res %>% autoplot() #view plot
#select the best decision tree model
best_tree <- tree_res %>% select_best("rmse")
best_tree #view model details
#finalize model workflow with best model
tree_final_wf <- tree_wf %>%
finalize_workflow(best_tree)
#fit model
tree_fit <-
tree_final_wf %>% fit(train_data)
tree_fit
```
### Decision tree plots
```{r}
#diagnostics
autoplot(tree_res)
#calculate residuals - originally got stuck trying out lots of different methods for this. took inspiration from Zane's code to manually calculate residuals rather than using some of the built in functions that I could not get to cooperate
tree_resid <- tree_fit %>%
augment(train_data) %>% #this will add predictions to our df
select(.pred, BodyTemp) %>%
mutate(.resid = BodyTemp - .pred) #manually calculate residuals
#model predictions from tuned model vs actual outcomes
tree_pred_plot <- ggplot(tree_resid, aes(x = BodyTemp, y = .pred)) + geom_point() +
labs(title = "Predictions vs Actual Outcomes: Decision Tree", x = "Body Temperature Outcome", y = "Body Temperature Prediction")
tree_pred_plot
#plot residuals vs predictions
tree_resid_plot <- ggplot(tree_resid, aes(y = .resid, x = .pred)) + geom_point() +
labs(title = "Predictions vs Residuals: Decision Tree", x = "Body Temperature Prediction", y = "Residuals")
tree_resid_plot #view plot
#compare to null model
metrics_null_train #view null RMSE for train data
tree_res %>% show_best(n=1) #view RMSE for best decision tree model
```
I am unsure if these plots look like what they are supposed to...and what exactly this means for our model. It is odd that there are only two different predictions (two distinct horizontal lines on the pred vs bodytemp plot) even with a range of actual outcome values. It looks like as a result, we also have two distinct vertical lines for our residuals plot, since we only had two different predictions.
For the performance comparison, we see a null RMSE of 1.2 and a decision tree RMSE of 1.18. These are very similar values
## LASSO model
```{r}
#based on tidymodels tutorial: case study
#model specification
lasso <- linear_reg(penalty = tune()) %>% set_engine("glmnet") %>% set_mode("regression")
#set workflow
lasso_wf <- workflow() %>% add_model(lasso) %>% add_recipe(BT_rec)
#tuning grid specification
lasso_grid <- tibble(penalty = 10^seq(-3, 0, length.out = 30))
#tuning with CV and tune_grid
lasso_res <- lasso_wf %>% tune_grid(resamples = cell_folds,
grid = lasso_grid,
control = control_grid(save_pred = TRUE),
metrics = metric_set(rmse))
#view model metrics
lasso_res %>% collect_metrics()
#select top models
top_lasso <-
lasso_res %>% show_best("rmse") %>% arrange(penalty)
top_lasso #view
#see best lasso
best_lasso <- lasso_res %>% select_best()
best_lasso #view
#finalize workflow with top model
lasso_final_wf <- lasso_wf %>% finalize_workflow(best_lasso)
#fit model with finalized WF
lasso_fit <- lasso_final_wf %>% fit(train_data)
```
### LASSO plots
```{r}
#diagnostics
autoplot(lasso_res)
#calculate residuals
lasso_resid <- lasso_fit %>%
augment(train_data) %>% #this will add predictions to our df
select(.pred, BodyTemp) %>%
mutate(.resid = BodyTemp - .pred) #manually calculate residuals
#model predictions from tuned model vs actual outcomes
lasso_pred_plot <- ggplot(lasso_resid, aes(x = BodyTemp, y = .pred)) + geom_point() +
labs(title = "Predictions vs Actual Outcomes: LASSO", x = "Body Temperature Outcome", y = "Body Temperature Prediction")
lasso_pred_plot
#plot residuals vs predictions
lasso_resid_plot <- ggplot(lasso_resid, aes(y = .resid, x = .pred)) + geom_point() +
labs(title = "Predictions vs Residuals: LASSO", x = "Body Temperature Prediction", y = "Residuals")
lasso_resid_plot #view plot
#compare to null model
metrics_null_train #view null RMSE for train data
lasso_res %>% show_best(n=1) #view RMSE for best lasso model
```
From these plots, we can tell the difference between the LASSO model and the decision tree model that we started with. There is clearly more variety in the predictions for this model, as well as for the residuals. Ultimately, we compare the RMSE for this LASSO model to the null model RMSE. The null model RMSE was 1.2, and the LASSO model RMSE is 1.14. This is a bit better of a model, but not by a whole lot. The
## Random forest
```{r}
#based on tidymodels tutorial: case study
library(parallel)
cores <- parallel::detectCores()
cores
#model specification
r_forest <- rand_forest(mtry = tune(), min_n = tune(), trees = tune()) %>% set_engine("ranger", num.threads = cores) %>% set_mode("regression")
#set workflow
r_forest_wf <- workflow() %>% add_model(r_forest) %>% add_recipe(BT_rec)
#tuning grid specification
rf_grid <- expand.grid(mtry = c(3, 4, 5, 6), min_n = c(40,50,60), trees = c(500,1000) )
#what we will tune:
r_forest %>% parameters()
#tuning with CV and tune_grid
r_forest_res <-
r_forest_wf %>%
tune_grid(resamples = cell_folds,
grid = rf_grid,
control = control_grid(save_pred = TRUE),
metrics = metric_set(rmse))
#view top models
r_forest_res %>% show_best(metric = "rmse")
#view plot of models performance
autoplot(r_forest_res)
#select best model
rf_best <- r_forest_res %>% select_best(metric = "rmse")
rf_best
#finalize workflow with top model
rf_final_wf <- r_forest_wf %>% finalize_workflow(rf_best)
#fit model with finalized WF
rf_fit <- rf_final_wf %>% fit(train_data)
```
### Random forest plots
```{r}
#diagnostics
autoplot(r_forest_res)
#calculate residuals
rf_resid <- rf_fit %>%
augment(train_data) %>% #this will add predictions to our df
select(.pred, BodyTemp) %>%
mutate(.resid = BodyTemp - .pred) #manually calculate residuals
#model predictions from tuned model vs actual outcomes
rf_pred_plot <- ggplot(rf_resid, aes(x = BodyTemp, y = .pred)) + geom_point() +
labs(title = "Predictions vs Actual Outcomes: Random Forest", x = "Body Temperature Outcome", y = "Body Temperature Prediction")
rf_pred_plot
#plot residuals vs predictions
rf_resid_plot <- ggplot(rf_resid, aes(y = .resid, x = .pred)) + geom_point() +
labs(title = "Predictions vs Actual Outcomes: Random Forest", x = "Body Temperature Prediction", y = "Residuals")
rf_resid_plot #view plot
#compare to null model
metrics_null_train #view null RMSE for train data
r_forest_res %>% show_best(n=1) #view RMSE for best decision tree model
```
Here, we see that the random forest plots for residuals and outcomes vs predictors look somewhat similar to the LASSO plots, still quite different from the decision tree plots. Remember, the RMSE for our null model for the train data was 1.2. the RMSE that we get for our best random forest model is 1.15. It seems that the random forest performs better than the null and the better than the decision tree, but not by a lot. It has a similar performance to the LASSO model.
# Model selection
```{r}
#recall model performance metrics side by side
metrics_null_train #view null model performance
tree_res %>% show_best(n=1) #view RMSE for best decision tree model
lasso_res %>% show_best(n=1) #view RMSE for best lasso tree model
r_forest_res %>% show_best(n=1) #view RMSE for best random forest model
```
Our null model has an RMSE of 1.2 and std error of 0.017. Any model we pick should do better than that.
Decision tree: RMSE 1.18, std err 0.053
LASSO: RMSE 1.14, std err 0.051
Random forest: RMSE 1.15, std err 0.053
While LASSO performs only slightly better than the random forest, it is the frontrunning model with the lowest RMSE model and lowest standard error. I will select the LASSO model as my top model for this data.
## Final model evaluation
```{r}
#fit to test data
last_lasso_fit <- lasso_final_wf %>% last_fit(data_split)
last_lasso_fit %>% collect_metrics()
```
Here we see that the RMSE for the LASSO model on the test data (using function `last_fit()`) is 1.15..., which is very close to the RMSE we saw on the train data in the LASSO model. This is a reflection of good model performance. Let's see some diagnostics for this final model.
## Final model diagnostics/plots
```{r}
#calculate residuals
final_resid <- last_lasso_fit %>%
augment() %>% #this will add predictions to our df
select(.pred, BodyTemp) %>%
mutate(.resid = BodyTemp - .pred) #manually calculate residuals
#model predictions from tuned model vs actual outcomes
final_pred_plot <- ggplot(final_resid, aes(x = BodyTemp, y = .pred)) + geom_point() +
labs(title = "Predictions vs Actual Outcomes: LASSO", x = "Body Temperature Outcome", y = "Body Temperature Prediction")
final_pred_plot
#plot residuals vs predictions
final_resid_plot <- ggplot(final_resid, aes(y = .resid, x = .pred)) + geom_point() +
labs(title = "Predictions vs Residuals: LASSO", x = "Residuals", y = "Body Temperature Prediction")
final_resid_plot #view plot
#compare to null model
metrics_null_train #view null RMSE for train data
last_lasso_fit %>% collect_metrics() #view RMSE for final model
```
<file_sep>---
title: "model_analysis"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# load packages and data
```{r}
library(ggplot2) #for plotting
library(broom) #for cleaning up output from lm()
library(here) #for data loading/saving
library(tidymodels) #for modeling
#path to data
#note the use of the here() package and not absolute paths
data_location <- here::here("data","processed_data","processeddata.rds")
#load cleaned data.
mydata <- readRDS(data_location)
```
# split data into train and test subsets
```{r}
# set seed for reproducible analysis (instead of random subset each time)
set.seed(222)
#subset 3/4 of data as training set
data_split <- initial_split(mydata, prop = 3/4)
#save sets as data frames
train_data <- training(data_split)
test_data <- testing(data_split)
```
# recipe to fit categorical outcome to all predictors
```{r}
# categorical outcome: Nausea
#recipe for categorical outcome with all predictors
nausea_rec <-
recipe(Nausea ~ ., data = train_data)
#logistic model set up
log_mod <- logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
#workflow set up
nausea_wflow <-
workflow() %>% add_model(log_mod) %>% add_recipe(nausea_rec)
#use workflow to prepare recipe and train model with predictors
nausea_fit <-
nausea_wflow %>% fit(data = train_data)
#extract model coefficient
nausea_fit %>% extract_fit_parsnip() %>% tidy()
```
# evaluate model
```{r}
#look at ROC and ROC-AUC (performance metric for categorical outcomes)
#used trained workflow to predict using test data
predict(nausea_fit, test_data)
#include probabilities
nausea_aug <- augment(nausea_fit, test_data)
#generate ROC curve
nausea_aug %>%
roc_curve(truth = Nausea, .pred_No) %>% autoplot()
#estimate area under the curve
nausea_aug %>% roc_auc(truth = Nausea, .pred_No)
```
We have an ROC-AUC of 0.724, indicating that the model could be useful! And, the ROC looks similar to the Tidymodels tutorial
# fit alternative model using only main predictor
```{r}
#categorical outcome: Nausea
#main predictor: RunnyNose
#recipe for categorical outcome with Runny Nose predictor
runnynose_rec <-
recipe(Nausea ~ RunnyNose, data = train_data)
#logistic model set up
log_mod <- logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
#workflow set up
runnynose_wflow <-
workflow() %>% add_model(log_mod) %>% add_recipe(runnynose_rec)
#use workflow to prepare recipe and train model with predictors
runnynose_fit <-
runnynose_wflow %>% fit(data = train_data)
#extract model coefficient
runnynose_fit %>% extract_fit_parsnip() %>% tidy()
```
# evaluate alternative model with only main predictor
```{r}
#look at ROC and ROC-AUC (performance metric for categorical outcomes)
#used trained workflow to predict using test data
predict(runnynose_fit, test_data)
#include probabilities
runnynose_aug <- augment(runnynose_fit, test_data)
#generate ROC curve
runnynose_aug %>%
roc_curve(truth = Nausea, .pred_No) %>% autoplot()
#estimate area under the curve
runnynose_aug %>% roc_auc(truth = Nausea, .pred_No)
```
For the alternative model, we have an ROC-AUC of 0.465, which tells us this model is no good for predictions
\newpage
# Part 2:
## recipe to fit continious outcome to all predictors
```{r}
# continuous outcome: BodyTemp
#recipe for continuous outcome with all predictors
BT_rec <- recipe(BodyTemp ~ ., data = train_data)
#linear model set up
lm_model <- linear_reg() %>%
set_engine('lm') %>%
set_mode('regression')
#workflow set up
BT_wflow <-
workflow() %>% add_model(lm_model) %>% add_recipe(BT_rec)
#use workflow to prepare recipe and train model with predictors
BT_fit <-
BT_wflow %>% fit(data = train_data)
#extract model coefficient
BT_fit %>% extract_fit_parsnip() %>% tidy()
```
# evaluate model
```{r}
#look at RMSE (performance metric for continuous outcomes)
#used trained workflow to predict using test data
predict(BT_fit, test_data)
#include probabilities
BT_aug <- augment(BT_fit, test_data)
#generate RMSE, setting the "truth" and .pred values
BT_aug %>%
rmse(truth = BodyTemp, .pred)
# Plotting results
ggplot(BT_aug, aes(x = BodyTemp, y = .pred)) +
# Create a diagonal line:
geom_abline(lty = 2) +
geom_point(alpha = 0.5) +
labs(y = "Predicted Body Temp (f)", x = "Body Temp (f)") +
# Scale and size the x- and y-axis uniformly:
coord_obs_pred()
# r-squared is another good metric
metrics <- metric_set(rmse, rsq, mae)
metrics(BT_aug, truth = BodyTemp, estimate = .pred)
```
We have an RMSE of 1.148515. Not too bad, the lower the better for RMSE.
Not too surprised about the distribution of body temp, considering a majority of participants had normal body temps (around 98 degrees)
r-squared is 0.0468187
# fit alternative model using only main predictor
```{r}
#continuous outcome: BodyTemp
#main predictor: RunnyNose
#recipe for continuous outcome with all predictors
BT_rec2 <- recipe(BodyTemp ~ RunnyNose, data = train_data)
#linear model set up
lm_model2 <- linear_reg() %>%
set_engine('lm') %>%
set_mode('regression')
#workflow set up
BT_wflow2 <-
workflow() %>% add_model(lm_model2) %>% add_recipe(BT_rec2)
#use workflow to prepare recipe and train model with predictors
BT_fit2 <-
BT_wflow2 %>% fit(data = train_data)
#extract model coefficient
BT_fit2 %>% extract_fit_parsnip() %>% tidy()
```
# evaluate alternative model with only main predictor
```{r}
#look at RMSE (performance metric for continuous outcomes)
#used trained workflow to predict using test data
predict(BT_fit2, test_data)
#include probabilities
BT_aug2 <- augment(BT_fit2, test_data)
#generate RMSE, setting the "truth" and .pred values
BT_aug2 %>%
rmse(truth = BodyTemp, .pred)
# Plotting results
ggplot(BT_aug2, aes(x = BodyTemp, y = .pred)) +
# Create a diagonal line:
geom_abline(lty = 2) +
geom_point(alpha = 0.5) +
labs(y = "Predicted Body Temp (f)", x = "Body Temp (f)") +
# Scale and size the x- and y-axis uniformly:
coord_obs_pred()
# r-squared is another good metric
metrics <- metric_set(rmse, rsq, mae)
metrics(BT_aug2, truth = BodyTemp, estimate = .pred)
```
We have an RMSE of 1.134553. Lower than the first model.
Once again the distribution of body temp is looking a bit odd
r-squared is 0.02399179
<file_sep>---
title: "analysis"
author: "<NAME>"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# load packages and cleaned data
```{r}
#load needed packages. make sure they are installed.
library(ggplot2) #for plotting
library(broom) #for cleaning up output from lm()
library(here) #for data loading/saving
library(tidymodels) #for modeling
#path to data
#note the use of the here() package and not absolute paths
data_location <- here::here("data","processed_data","processeddata.rds")
#load cleaned data.
mydata <- readRDS(data_location)
```
# fit linear model to contiuous outcome (BodyTemp) - only main predictor (RunnyNose)
```{r}
#attempting to visualize data
ggplot(mydata, aes(x = BodyTemp, y = RunnyNose)) + geom_point() + geom_smooth(method = lm)
#linear regression model specification set up
lm_mod <- linear_reg() %>% set_engine("lm")
#estimating/training linear model
lm_fit1 <- lm_mod %>% fit(BodyTemp ~ RunnyNose, data = mydata)
#view summary of fit
tidy(lm_fit1)
#save as table
lm_fit1_table <- tidy(lm_fit1)
```
# fit linear model to continuous outcome (BodyTemp) using all predictors
```{r}
# running linear model 2
lm_fit2 <- lm_mod %>% fit(BodyTemp ~ ., data = mydata)
#view summary of fit
tidy(lm_fit2)
#save as table
lm_fit2_table <- tidy(lm_fit2)
```
# compare model results for main predictor (RunnyNose) vs all predictors
```{r}
#display model results
glance(lm_fit1)
glance(lm_fit2)
#use ANOVA to compare model with one predictor vs model with all predictors
lm_comp <- anova(lm_fit1$fit, lm_fit2$fit, test = "Chisq")
lm_comp
```
The ANOVA test tells us that we should use the second linear model, which includes all predictors. lm_fit2 is a statistically significant model
# fit logistic model to categorical outcome (Nausea) using main predictor of interest (RunnyNose)
```{r}
#logistic model set up
log_mod <- logistic_reg() %>%
set_engine("glm") %>%
set_mode("classification")
#run logistic model for RunnyNose predictor
log_fit1 <- log_mod %>% fit(Nausea ~ RunnyNose, data = mydata)
```
# fits logistic model to categorical outcome (Nausea) with all predictors of interest
```{r}
#run logistic model with all predictors
log_fit2 <- log_mod %>% fit(Nausea ~ ., data = mydata)
```
# compare model results with main predictor (RunnyNose) vs all predictors
```{r}
#display logistic model results
glance(log_fit1)
glance(log_fit2)
#compare model results using ANOVA
log_comp <- anova(log_fit1$fit, log_fit2$fit, test = "Chisq")
log_comp
```
This ANOVA test tells us that the more complex model, log_fit2, which uses all predictors, is a more suitable model (having a significant p-value).
#saving results
```{r}
saveRDS(lm_comp, file = here("results", "LinearComp.rds"))
saveRDS(log_comp, file = here("results", "LogisticComp.rds"))
```
#testing out K-nearest neighbors model fit
```{r}
library(kknn) #load KNN package
#set up K-nearest neighbors model fit
knn_mod <- nearest_neighbor() %>%
set_mode("regression")
#fit model for BodyTemp and all predictors
knn_fit1 <- knn_mod %>% fit(BodyTemp ~ ., data = mydata)
#view model
knn_fit1
#predicting BodyTemp values based on K nearest neighbors model
predict(knn_fit1, new_data = mydata)
```
Okay, now I have created the model and some predictions. I am not 100% confident in interpreting/evaluating this type of model, but it is neat to see how easily we can switch models in R.
<file_sep># Overview
This repository contains my analysis for MADA modules 8 and 9. Scripts should be run in this order to reproduce:
1. processingscript.R
2. exploration.Rmd
3. analysis.Rmd
4. model_analysis.Rmd
5. mach_learn_analysis.Rmd
| e6c87e1ad725b898662880ea9384ec8a6060bb18 | [
"Markdown",
"R",
"RMarkdown"
] | 7 | Markdown | ameliafoley/AmeliaFoley-MADA-analysis3 | 3b26947d48f6eb29976be32e2326ab9829ef8688 | 0deb3e516124f7330959d12ad1f00391c9e84f61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.