branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#/bin/bash git pull npm set registry https://registry.npm.taobao.org yarn docker-compose -f ./docker/docker-compose.dev.yml up<file_sep>## superlative-admin
6a3f8914e878577208f2053f8be3b6e187ea34b8
[ "Markdown", "Shell" ]
2
Shell
SuperlativeCoder/superlative-admin
fd397e699baedf8bbe8f59d0e120e4b766645811
d8e5273c28c33cec879ae4de38f3498fab38ac03
refs/heads/master
<repo_name>tony-andreev94/Python-Advanced<file_sep>/06. File Handling/LAB/03. File Writer.py # Task 3 file_path = "W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\demos\\my_first_file.txt" with open(file_path, 'w') as file: file.write('I just created my first file!') <file_sep>/04. Comprehension/Exercise/03. Capitals.py # https://judge.softuni.bg/Contests/Compete/Index/1837#2 countries = input().split(", ") capitals = input().split(", ") zipped = tuple(zip(countries, capitals)) capitals_dict = {zipped[i][0]: zipped[i][1] for i in range(len(zipped))} for key, value in capitals_dict.items(): print(f"{key} -> {value}") # no comprehension countries = input().split(", ") capitals = input().split(", ") my_dict = {} for i in range(len(countries)): my_dict[countries[i]] = capitals[i] for key, value in my_dict.items(): print(f"{key} -> {value}") <file_sep>/06. File Handling/LAB/02. File Reader.py # Task 2 file_path = 'W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\08-File-Handling-Lab-Resources\\File Reader\\numbers.txt' with open(file_path, 'r') as file: numbers_sum = 0 while True: number = file.readline() if number == '': print(numbers_sum) break else: numbers_sum += int(number) <file_sep>/04. Comprehension/LAB/02. No Vowels.py # https://judge.softuni.bg/Contests/Practice/Index/1836#1 string = input() vowels = ['a', 'A', 'o', 'O', 'u', 'U', 'e', 'E', 'i', 'I'] formatted_string = [letter for letter in string if letter not in vowels] print(*formatted_string, sep="") <file_sep>/04. Comprehension/LAB/03. Even Matrix.py # https://judge.softuni.bg/Contests/Practice/Index/1836#2 sublists = int(input()) # build matrix matrix2 = [[int(x) for x in input().split(", ")] for _ in range(sublists)] # remove odd numbers print([[x for x in row if x % 2 == 0] for row in matrix2]) # no comprehensions matrix = [] # build matrix for _ in range(sublists): sublist = [int(x) for x in input().split(", ")] matrix.append(sublist) # remove odds for row in matrix: for element in row: if not element % 2 == 0: row.pop(row.index(element)) print(matrix) <file_sep>/10. Exam Prep/01_paint_colors.py # https://judge.softuni.bg/Contests/Practice/Index/2306#0 input_str = input().split() main_colors = ['red', 'yellow', 'blue'] sec_colors = {'orange': ['red', 'yellow'], 'purple': ['red', 'blue'], 'green': ['yellow', 'blue'] } results = [] while input_str: first = input_str.pop(0) last = "" if len(input_str) != 0: last = input_str.pop() first_comb = first + last second_comb = last + first if first_comb in main_colors or first_comb in sec_colors: results.append(first_comb) elif second_comb in main_colors or second_comb in sec_colors: results.append(second_comb) else: index = len(input_str) // 2 if not first[:-1] == "": input_str.insert(index, first[:-1]) if not last[:-1] == "": input_str.insert(index, last[:-1]) for each in results: if each in sec_colors.keys(): if not sec_colors[each][0] in results or sec_colors[each][1] not in results: results.remove(each) print(results) <file_sep>/05. Functions Advanced/LAB/04. Sort.py # https://judge.softuni.bg/Contests/Practice/Index/1838#3 def sort_func(values): return sorted(values) print(sort_func(map(int, input().split()))) print(sorted([int(x) for x in input().split()])) <file_sep>/02. Tuples and Sets/Exercise/03. Periodic Table.py # https://judge.softuni.bg/Contests/Compete/Index/1833#2 # redo and make a return instead of print? def find_unique_elements(num): elements_list = [] for i in range(num): user_input = input().split(" ") elements_list.extend(user_input) for each in set(elements_list): print(each) num = int(input()) find_unique_elements(num) <file_sep>/01. Lists as Stacks and Queues/LAB/05. Hot Potato.py # https://judge.softuni.bg/Contests/Practice/Index/1830#4 # 80/100 from collections import deque def potato_func(kids_list, n): queue = deque(kids_list) index = 0 while queue: queue.append(queue.popleft()) index += 1 if index == n: name = queue.pop() print(f"Removed {name}") index = 0 if len(queue) == 1: print(f"Last is {queue.pop()}") break kids = input().split(" ") toss = int(input()) potato_func(kids, toss) <file_sep>/10. Exam Prep/02_war_planes.py # https://judge.softuni.bg/Contests/Practice/Index/2025#1 def is_in_field(cords_list): if 0 <= cords_list[0] < len(field) and 0 <= cords_list[1] < len(field): return True directions = {'right': [0, 1], 'left': [0, -1], 'up': [-1, 0], 'down': [1, 0] } field_size = int(input()) field = [] total_targets = 0 plane_position = (0, 0) for _ in range(field_size): row = input().split() field.append(row) for char in row: if char == 't': total_targets += 1 elif char == 'p': plane_position = (field.index(row), row.index('p')) current_targets = total_targets commands_amount = int(input()) for _ in range(commands_amount): command_tokens = input().split() command = command_tokens[0] direction = command_tokens[1] steps = int(command_tokens[2]) # logic: # get new cords/direction cell_position = [plane_position[0], plane_position[1]] for _ in range(steps): cell_position[0] += directions[direction][0] cell_position[1] += directions[direction][1] # check validity if is_in_field(cell_position): if command == 'shoot': if field[cell_position[0]][cell_position[1]] == 't': current_targets -= 1 field[cell_position[0]][cell_position[1]] = 'x' elif command == 'move': if field[cell_position[0]][cell_position[1]] == '.': field[plane_position[0]][plane_position[1]] = '.' field[cell_position[0]][cell_position[1]] = 'p' plane_position = (cell_position[0], cell_position[1]) if current_targets == 0: print(f"Mission accomplished! All {total_targets} targets destroyed.") elif current_targets > 0: print(f"Mission failed! {current_targets} targets left.") for each in field: print(*each) <file_sep>/05. Functions Advanced/LAB/05. Min Max and Sum.py # https://judge.softuni.bg/Contests/Practice/Index/1838#4 def min_max_sum_func(values): print(f"The minimum number is {min(values)}") print(f"The maximum number is {max(values)}") print(f"The sum number is: {sum(values)}") min_max_sum_func(list(map(int, input().split()))) <file_sep>/10. Exam Prep/02_easter_bunny.py # https://judge.softuni.bg/Contests/Practice/Index/2306#1 def is_valid(cell_position): if 0 <= cell_position[0] < len(field) and 0 <= cell_position[1] < len(field): return True field_size = int(input()) field = [] for i in range(field_size): row = input().split() field.append(row) if "B" in row: bunny_pos = (field.index(row), row.index('B')) directions = {"right": [0, 1], "left": [0, -1], "down": [1, 0], "up": [-1, 0] } eggs_collected = {'right': 0, 'left': 0, 'down': 0, 'up': 0 } cell_steps = {'right': [], 'left': [], 'down': [], 'up': [] } best_direction = 'right' for each_direction in directions: row = bunny_pos[0] col = bunny_pos[1] current_position = [row, col] while is_valid(current_position): cell = field[current_position[0]][current_position[1]] if cell == 'X': break elif cell == 'B': pass else: eggs_collected[each_direction] += int(cell) cell_steps[each_direction].append([current_position[0], current_position[1]]) current_position[0] += directions[each_direction][0] current_position[1] += directions[each_direction][1] if eggs_collected[each_direction] > eggs_collected[best_direction]: best_direction = each_direction print(best_direction) for each in cell_steps[best_direction]: print(each) print(eggs_collected[best_direction]) <file_sep>/03. Multidimensional lists/EXERCISE/02. 2X2 Squares in Matrix.py # https://judge.softuni.bg/Contests/Compete/Index/1835#1 matrix = [] (rows, columns) = [int(x) for x in input().split(" ")] for _ in range(rows): row = input().split(" ") matrix.append(row) matches = 0 for each_row in matrix: each_row_index = matrix.index(each_row) if each_row_index == len(matrix) - 1: break for index in range(len(each_row)): if index == columns - 1: break if each_row[index] == each_row[index + 1] == matrix[each_row_index + 1][index] == matrix[each_row_index + 1][index + 1]: matches += 1 print(matches) <file_sep>/03. Multidimensional lists/LAB/03. Primary diagonal.py # https://judge.softuni.bg/Contests/Practice/Index/1834#1 def build_matrix(matrix_size): matrix = [] for _ in range(matrix_size): row = [int(x) for x in input().split(" ")] matrix.append(row) return matrix def find_diagonal_sum(matrix): diagonal_sum = 0 index = 0 for each_row in matrix: diagonal_sum += each_row[index] index += 1 return diagonal_sum matrix_size = int(input()) print(find_diagonal_sum(build_matrix(matrix_size))) <file_sep>/04. Comprehension/LAB/01. ASCII Values.py # https://judge.softuni.bg/Contests/Practice/Index/1836#0 values_list = input().split(", ") ascii_dict = {char: ord(char) for char in values_list} print(ascii_dict) <file_sep>/05. Functions Advanced/Exercise/02. Odd or Even.py # https://judge.softuni.bg/Contests/Compete/Index/1839#1 def find_sum(command, values): if command == "Odd": return sum([x for x in values if not x % 2 == 0]) * len(values) elif command == "Even": return sum([x for x in values if x % 2 == 0]) * len(values) command = input() values_list = [int(x) for x in input().split()] print(find_sum(command, values_list)) <file_sep>/01. Lists as Stacks and Queues/Excercise/04. Fashion Boutique.py # https://judge.softuni.bg/Contests/Compete/Index/1831#3 def organize_clothes(clothes_value, rack_capacity): racks = 1 stack = clothes_value current_clothes = 0 while stack: clothes_amount = int(stack.pop()) if current_clothes + clothes_amount <= rack_capacity: current_clothes += clothes_amount else: racks += 1 current_clothes = clothes_amount return racks clothes = input().split(" ") rack_capacity = int(input()) print(organize_clothes(clothes, rack_capacity)) <file_sep>/02. Tuples and Sets/LAB/03. Record Unique Names v2.py # https://judge.softuni.bg/Contests/Practice/Index/1832#2 def unique_names(number): # names = set() # [names.add(input()) for _ in range(number)] # list comprehension names = {input() for _ in range(number)} # set comprehension return names def print_func(names_set): [print(each) for each in names_set] names_amount = int(input()) print_func(unique_names(names_amount)) <file_sep>/03. Multidimensional lists/EXERCISE/01. Diagonal Difference.py # https://judge.softuni.bg/Contests/Compete/Index/1835#0 def build_matrix(matrix_size): matrix = [] for _ in range(matrix_size): row = [int(x) for x in input().split(" ")] matrix.append(row) return matrix def find_first_diagonal(matrix): diagonal_sum = 0 index = 0 for each_row in matrix: diagonal_sum += each_row[index] index += 1 return diagonal_sum def find_sec_diagonal(matrix): diagonal_sum = 0 index = len(matrix[0]) - 1 for each_row in matrix: diagonal_sum += each_row[index] index -= 1 return diagonal_sum matrix_size = int(input()) matrix = build_matrix(matrix_size) first_diag = find_first_diagonal(matrix) second_diag = find_sec_diagonal(matrix) print(abs(first_diag - second_diag)) <file_sep>/05. Functions Advanced/LAB/09. Character Combinations.py # https://judge.softuni.bg/Contests/Practice/Index/1838#9 def combinations(string): pass combinations('abc') <file_sep>/11. Exam/03_list_manipulator.py # https://judge.softuni.bg/Contests/Compete/Index/2456#2 def list_manipulator(input_list, *args): action = args[0] place = args[1] numbers = [*args] numbers.pop(0) numbers.pop(0) if action == 'remove': if len(numbers) > 0: boundary = numbers[0] else: boundary = 1 for _ in range(int(boundary)): if place == 'beginning': input_list.pop(0) elif place == 'end': input_list.pop() elif action == 'add': if place == 'beginning': for each_number in numbers[::-1]: input_list.insert(0, each_number) elif place == 'end': for each_number in numbers: input_list.append(each_number) return input_list print(list_manipulator([1, 2, 3], "remove", "end")) print(list_manipulator([1, 2, 3], "remove", "beginning")) print(list_manipulator([1, 2, 3], "add", "beginning", 20)) print(list_manipulator([1, 2, 3], "add", "end", 30)) print(list_manipulator([1, 2, 3], "remove", "end", 2)) print(list_manipulator([1, 2, 3], "remove", "beginning", 2)) print(list_manipulator([1, 2, 3], "add", "beginning", 20, 30, 40)) print(list_manipulator([1, 2, 3], "add", "end", 30, 40, 50)) <file_sep>/04. Comprehension/LAB/05. Filter Numbers.py # https://judge.softuni.bg/Contests/Practice/Index/1836#4 range_lower = int(input()) range_upper = int(input()) print([x for x in range(range_lower, range_upper + 1) if any([x % d == 0 for d in range(2, 11)])]) # no comprehension divisors = [2, 3, 4, 5, 6, 7, 8, 9, 10] result = [] for num in range(range_lower, range_upper + 1): for divisor in divisors: if num % divisor == 0 and num not in result: result.append(num) print(result) <file_sep>/11. Exam/01_bombs.py # https://judge.softuni.bg/Contests/Compete/Index/2456#0 def is_full(dict): if dict['Datura Bombs'] >= 3 and dict['Cherry Bombs'] >= 3 and dict['Smoke Decoy Bombs'] >= 3: return True else: return False bombs_dict = {40: 'Datura Bombs', 60: 'Cherry Bombs', 120: 'Smoke Decoy Bombs' } pouch_dict = {'Cherry Bombs': 0, 'Datura Bombs': 0, 'Smoke Decoy Bombs': 0 } datura = 0 cherry = 0 smoke = 0 bomb_effects = [int(x) for x in input().split(", ")] bomb_casings = [int(x) for x in input().split(", ")] while len(bomb_effects) > 0 and len(bomb_casings) > 0: temp_bomb = int(bomb_effects[0]) + int(bomb_casings[-1]) if temp_bomb in bombs_dict: bomb_effects.pop(0) bomb_casings.pop() pouch_dict[bombs_dict[temp_bomb]] += 1 if is_full(pouch_dict): break else: bomb_casings[-1] -= 5 if is_full(pouch_dict): print("Bene! You have successfully filled the bomb pouch!") else: print("You don't have enough materials to fill the bomb pouch.") if len(bomb_effects) == 0: print("Bomb Effects: empty") else: print(f"Bomb Effects: {', '.join(str(item) for item in bomb_effects)}") if len(bomb_casings) == 0: print("Bomb Casings: empty") else: print(f"Bomb Casings: {', '.join(str(item) for item in bomb_casings)}") for pair in pouch_dict.items(): print(f"{pair[0]}: {pair[1]}") <file_sep>/06. File Handling/LAB/01. File Opener.py # Task 1 file_path = 'W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\08-File-Handling-Lab-Resources\\File Opener\\text.txt' try: open(file_path, 'r') print("File found") except FileNotFoundError: print("File not found") <file_sep>/10. Exam Prep/03_find_eggs.py # https://judge.softuni.bg/Contests/Practice/Index/2306#2 def find_strongest_eggs(string, sublists): grid = [] strong_eggs = [] # build lists for _ in range(sublists): grid.append([]) # populate lists i = 0 for el in string: grid[i].append(el) i += 1 if i == sublists: i = 0 # find eggs mid_index = len(grid[0]) // 2 for each_list in grid: number = each_list[mid_index] left_number = each_list[mid_index - 1] right_number = each_list[mid_index + 1] if left_number < number and right_number < number: if left_number < right_number: strong_eggs.append(number) return strong_eggs # Testing print(find_strongest_eggs([-1, 7, 3, 15, 2, 12], 2)) print(find_strongest_eggs([-1, 0, 2, 5, 2, 3], 2)) print(find_strongest_eggs([51, 21, 83, 52, 55], 1)) <file_sep>/05. Functions Advanced/LAB/06. Multiplication Function.py # https://judge.softuni.bg/Contests/Practice/Index/1838#5 def multiply(*args): result = 1 for x in args: result *= x return result print(multiply(1, 4, 5)) <file_sep>/01. Lists as Stacks and Queues/LAB/02. Matching Brackets.py # https://judge.softuni.bg/Contests/Practice/Index/1830#1 def find_exp(data): stack = [] result = [] for index in range(len(data)): char = data[index] if char == "(": stack.append(index) elif char == ")": start_index = stack.pop() result.append(data[start_index:index + 1]) return result expression = input() for each in find_exp(expression): print(each) <file_sep>/01. Lists as Stacks and Queues/LAB/04. Water Dispencer.py # https://judge.softuni.bg/Contests/Practice/Index/1830#3 from collections import deque water_quantity = int(input()) queue = deque() while True: command = input() if command == "Start": break else: queue.append(command) while True: command = input().split(" ") if command[0] == "End": print(f"{water_quantity} liters left") break elif command[0] == "refill": water_quantity += int(command[1]) else: needed_water = int(command[0]) if needed_water <= water_quantity: person_name = queue.popleft() print(f"{person_name} got water") water_quantity -= needed_water else: person_name = queue.popleft() print(f"{person_name} must wait") <file_sep>/02. Tuples and Sets/LAB/04. Parking Lot.py # https://judge.softuni.bg/Contests/Practice/Index/1832#3 def parking_lot(number): cars = set() for _ in range(number): (direction, car_plate) = input().split(", ") # unpacking example if direction == "IN": cars.add(car_plate) elif direction == "OUT": if car_plate in cars: cars.remove(car_plate) return cars def print_cars(cars): if cars: [print(each) for each in cars] else: print("Parking Lot is Empty") commands = int(input()) print_cars(parking_lot(commands)) <file_sep>/10. Exam Prep/01_expression_evaluator.py # https://judge.softuni.bg/Contests/Practice/Index/2025#0 expression = input().split() temp_numbers = [] result = int(expression[0]) expression.pop(0) for char in expression: if char == '+': for each_num in temp_numbers: result += each_num temp_numbers = [] elif char == '-': for each_num in temp_numbers: result -= each_num temp_numbers = [] elif char == '*': for each_num in temp_numbers: result *= each_num temp_numbers = [] elif char == '/': for each_num in temp_numbers: result /= each_num result = int(result) temp_numbers = [] else: temp_numbers.append(int(char)) print(result) <file_sep>/05. Functions Advanced/Exercise/08. Recursion Palindrome.py # https://judge.softuni.bg/Contests/Compete/Index/1839#7 def palindrome(word, index=0): if index == len(word) // 2: return f"{word} is a palindrome" if not word[index] == word[len(word) - 1 - index]: return f"{word} is not a palindrome" return palindrome(word, index + 1) def palindrome_no_recursion(word, index=0): if word == word[::-1]: return f"{word} is a palindrome" else: return f"{word} is not a palindrome" print(palindrome("abcba", 0)) print(palindrome("peter", 0)) <file_sep>/02. Tuples and Sets/Exercise/02. Sets of Elements.py # https://judge.softuni.bg/Contests/Compete/Index/1833#1 # redo and make a return instead of print? def find_elements(a, b): first_l = [] second_l = [] for i in range(a): el = int(input()) first_l.append(el) for i in range(b): el = int(input()) second_l.append(el) first_set = set(first_l) second_set = set(second_l) for each in first_set: if each in second_set: print(each) user_input = input().split(" ") find_elements(int(user_input[0]), int(user_input[1])) <file_sep>/04. Comprehension/Exercise/01. Word Filter.py # https://judge.softuni.bg/Contests/Compete/Index/1837#0 print("\n".join([word for word in input().split() if len(word) % 2 == 0])) # no comprehension words = input().split() for each_word in words: if len(each_word) % 2 == 0: print(each_word) <file_sep>/04. Comprehension/Exercise/05. Diagonals.py # https://judge.softuni.bg/Contests/Compete/Index/1837#4 def first_diagonal_sum(matrix): diagonal_sum = 0 index = 0 for each_row in matrix: diagonal_sum += int(each_row[index]) index += 1 return diagonal_sum def first_diagonal_elements(matrix): index = 0 elements = [] for each_row in matrix: elements.append(each_row[index]) index += 1 return elements def sec_diagonal_sum(matrix): diagonal_sum = 0 index = len(matrix[0]) - 1 for each_row in matrix: diagonal_sum += int(each_row[index]) index -= 1 return diagonal_sum def sec_diagonal_elements(matrix): index = len(matrix[0]) - 1 elements = [] for each_row in matrix: elements.append(each_row[index]) index -= 1 return elements # comprehension size = int(input()) matrix = [input().split(", ") for _ in range(size)] print(f"First diagonal: {', '.join(first_diagonal_elements(matrix))}. Sum: {first_diagonal_sum(matrix)}") print(f"Second diagonal: {', '.join(sec_diagonal_elements(matrix))}. Sum: {sec_diagonal_sum(matrix)}") # no comprehension matrix = [] size = int(input()) for _ in range(size): matrix.append(input().split(", ")) print(f"First diagonal: {', '.join(first_diagonal_elements(matrix))}. Sum: {first_diagonal_sum(matrix)}") print(f"Second diagonal: {', '.join(sec_diagonal_elements(matrix))}. Sum: {sec_diagonal_sum(matrix)}") <file_sep>/03. Multidimensional lists/LAB/01. Sum Matrix Elements.py # https://judge.softuni.bg/Contests/Practice/Index/1834#0 # amount of columns is not needed, but it's given as input def build_matrix(rows, columns): matrix = [] for _ in range(int(rows)): row = [int(x) for x in input().split(", ")] matrix.append(row) return matrix def find_sum(matrix): matrix_sum = 0 for each_row in matrix: matrix_sum += sum(each_row) return matrix_sum def print_result(matrix, matrix_sum): print(matrix_sum) print(matrix) (rows, columns) = [int(x) for x in input().split(", ")] matrix = build_matrix(rows, columns) element_sum = find_sum(matrix) print_result(matrix, element_sum) <file_sep>/06. File Handling/LAB/04. File Delete.py # Task 4 from os import remove file_path = "W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\demos\\my_first_file.txt" try: remove(file_path) except FileNotFoundError: print(f'File already deleted!') <file_sep>/04. Comprehension/Exercise/07. Flatten Lists.py # https://judge.softuni.bg/Contests/Compete/Index/1837#6 result = [el for el in [each.split() for each in input().split("|")]][::-1] for each_row in result: for element in each_row: print(element, end=" ") # no comprehension result = [] string = input().split("|") for each in string: row = each.split() result.append(row) for each_row in result[::-1]: for element in each_row: print(element, end=" ") <file_sep>/11. Exam/02_snake.py # https://judge.softuni.bg/Contests/Compete/Index/2456#1 # 100/100 points # TODO spaghetti code, to refactor the task def in_field(tuple): if 0 <= tuple[0] < len(field) and 0 <= tuple[1] < len(field): return True field_size = int(input()) field = [] burrow_position = [] for _ in range(field_size): row = input() field.append(row) if 'S' in row: snake_position = (field.index(row), row.index('S')) if 'B' in row: burrow_position.append((field.index(row), row.index('B'))) food_eaten = 0 cell_position = snake_position while True: command = input() if command == "right": # move to new position cell_position = (snake_position[0], snake_position[1] + 1) row = cell_position[0] col = cell_position[1] if in_field(cell_position): if field[row][col] == '*': food_eaten += 1 if field[row][col] == 'B': # print('true') # delete old S on field field[row] = field[row][:col - 1] + '.' + field[row][col:] # delete burrow entrance on field field[row] = field[row][:col] + '.' + field[row][col + 1:] # delete burrow entry in list and update snake position with other burrow del burrow_position[burrow_position.index(cell_position)] snake_position = burrow_position[0] # draw S on field field[snake_position[0]] = field[snake_position[0]][:snake_position[1]] + 'S' + field[snake_position[0]][snake_position[1] + 1:] # print(field[snake_position[0]]) else: # delete old snake position field[row] = field[row][:col - 1] + '.' + field[row][col:] # draw S to new position field[row] = field[row][:col] + 'S' + field[row][col + 1:] snake_position = (row, col) if food_eaten == 10: print("You won! You fed the snake.") break else: field[row] = field[row][:col - 1] + '.' + field[row][col:] print("Game over!") break elif command == "left": # move to new position cell_position = (snake_position[0], snake_position[1] - 1) row = cell_position[0] col = cell_position[1] if in_field(cell_position): if field[row][col] == '*': food_eaten += 1 if field[row][col] == 'B': ### # print('true') # delete old S on field field[row] = field[row][:col + 1] + '.' + field[row][col + 2:] # delete burrow entrance on field field[row] = field[row][:col] + '.' + field[row][col + 1:] # delete burrow entry in list and update snake position with other burrow del burrow_position[burrow_position.index(cell_position)] snake_position = burrow_position[0] # draw S on field field[snake_position[0]] = field[snake_position[0]][:snake_position[1]] + 'S' + field[snake_position[0]][snake_position[1] + 1:] # print(field[snake_position[0]]) else: # delete old snake position and draw new one field[row] = field[row][:col + 1] + '.' + field[row][col + 2:] field[row] = field[row][:col] + 'S' + field[row][col + 1:] snake_position = (row, col) if food_eaten == 10: print("You won! You fed the snake.") break else: field[row] = field[row][:col + 1] + '.' + field[row][col + 2:] print("Game over!") break pass elif command == "up": cell_position = (snake_position[0] - 1, snake_position[1]) row = cell_position[0] col = cell_position[1] ####### if in_field(cell_position): if field[row][col] == '*': food_eaten += 1 if field[row][col] == 'B': # print('true') # delete old S on field field[row + 1] = field[row + 1][:col] + '.' + field[row + 1][col + 1:] # delete burrow entrance on field field[row] = field[row][:col] + '.' + field[row][col + 1:] # delete burrow entry in list and update snake position with other burrow del burrow_position[burrow_position.index(cell_position)] snake_position = burrow_position[0] # draw S on field field[snake_position[0]] = field[snake_position[0]][:snake_position[1]] + 'S' + field[snake_position[0]][snake_position[1] + 1:] # print(field[snake_position[0]]) else: # delete old snake position and draw new one field[row + 1] = field[row + 1][:col] + '.' + field[row + 1][col + 1:] field[row] = field[row][:col] + 'S' + field[row][col + 1:] snake_position = (row, col) if food_eaten == 10: print("You won! You fed the snake.") break else: field[row + 1] = field[row + 1][:col] + '.' + field[row + 1][col + 1:] print("Game over!") break pass elif command == "down": cell_position = (snake_position[0] + 1, snake_position[1]) row = cell_position[0] col = cell_position[1] if in_field(cell_position): if field[row][col] == '*': food_eaten += 1 if field[row][col] == 'B': # print('true') # delete old S on field field[row - 1] = field[row - 1][:col] + '.' + field[row - 1][col + 1:] # delete burrow entrance on field field[row] = field[row][:col] + '.' + field[row][col + 1:] # delete burrow entry in list and update snake position with other burrow del burrow_position[burrow_position.index(cell_position)] snake_position = burrow_position[0] # draw S on field field[snake_position[0]] = field[snake_position[0]][:snake_position[1]] + 'S' + field[ snake_position[0]][ snake_position[1] + 1:] # print(field[snake_position[0]]) else: # delete old snake position and draw new one field[row - 1] = field[row - 1][:col] + '.' + field[row - 1][col + 1:] field[row] = field[row][:col] + 'S' + field[row][col + 1:] snake_position = (row, col) if food_eaten == 10: print("You won! You fed the snake.") break else: field[row - 1] = field[row - 1][:col] + '.' + field[row - 1][col + 1:] print("Game over!") break else: break print(f"Food eaten: {food_eaten}") for each in field: print(each) <file_sep>/01. Lists as Stacks and Queues/Excercise/02. Max and Min Element.py # https://judge.softuni.bg/Contests/Compete/Index/1831#1 def query_func(n): stack = [] for _ in range(n): command_input = input().split(" ") command = int(command_input[0]) if command == 1: stack.append(int(command_input[1])) elif command == 2 and stack: # check if stack is empty before pop() stack.pop() elif command == 3 and stack: # check if stack is empty before using min()/max() print(max(stack)) elif command == 4 and stack: print(min(stack)) return ", ".join([str(el) for el in reversed(stack)]) num = int(input()) print(query_func(num)) <file_sep>/05. Functions Advanced/LAB/01. Absolute values.py # https://judge.softuni.bg/Contests/Practice/Index/1838#0 def to_abs(values): return [abs(x) for x in values] print(to_abs(map(float, input().split()))) <file_sep>/02. Tuples and Sets/LAB/02. Average Student Grade.py # https://judge.softuni.bg/Contests/Practice/Index/1832#1 def grade_average(grades): grade_dict = {} for _ in range(grades): user_input = input().split(" ") student = user_input[0] grade = user_input[1] if student not in grade_dict.keys(): grade_dict[student] = [float(grade)] else: grade_dict[student].append(float(grade)) return grade_dict def print_grades(grade_dict): for (student, grade) in grade_dict.items(): avg_grade = sum(grade) / len(grade) grades_string = ' '.join(f'{x:.2f}' for x in grade) print(f"{student} -> {grades_string} (avg: {avg_grade:.2f})") grades = int(input()) print_grades(grade_average(grades)) <file_sep>/06. File Handling/LAB/05. Word Count.py # Task 5 words_path = 'W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\08-File-Handling-Lab-Resources\\Words Count\\words.txt' text_path = 'W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\08-File-Handling-Lab-Resources\\Words Count\\text.txt' def extract_words(file_path): with open(file_path, 'r') as words_file: words_list = words_file.readline().split(" ") return words_list def count_words_in_text(words, text): words_dict = {word: 0 for word in words} with open(text, 'r') as text_file: while True: line = text_file.readline().lower() if line == '': break else: for each_word in words: if each_word in line: words_dict[each_word] += 1 return words_dict def print_formatted_dict(dict): sorted_dict = sorted(dict.items(), key= lambda pair: (-pair[1], pair[0])) [print(f"{word} - {count}") for word, count in sorted_dict] words = extract_words(words_path) words_dict = count_words_in_text(words, text_path) print_formatted_dict(words_dict) <file_sep>/02. Tuples and Sets/LAB/05. SoftUni Party.py # https://judge.softuni.bg/Contests/Practice/Index/1832#4 def missing_guests(reservations): guests = set() for _ in range(reservations): guests.add(input()) command = input() while not command == "END": guests.remove(command) command = input() return guests def print_missing_guests(guest_set): print(len(guest_set)) guest_list = [each for each in guest_set] guest_list.sort() [print(guest) for guest in guest_list] # if it was necessary to first print the ones with letters, and then the ones with digits: # [print(guest) for guest in guest_set if not guest[0].isdigit()] # first print the ones starting with letter # [print(guest) for guest in guest_set if guest[0].isdigit()] # then print the ones starting with digit reservations = int(input()) print_missing_guests(missing_guests(reservations)) <file_sep>/01. Lists as Stacks and Queues/Excercise/01. Reverse Numbers with a Stack.py # https://judge.softuni.bg/Contests/Compete/Index/1831#0 def reverse_func(stack): result = [] while stack: result.append(stack.pop()) return " ".join(result) num_list = input().split(" ") print(reverse_func(num_list)) <file_sep>/05. Functions Advanced/Exercise/01. Negative vs Positive.py # https://judge.softuni.bg/Contests/Compete/Index/1839#0 def numbers(values): positive_sum = sum([x for x in values if x >= 0]) negative_sum = sum([x for x in values if x < 0]) print(negative_sum) print(positive_sum) if abs(negative_sum) > positive_sum: return "The negatives are stronger than the positives" else: return "The positives are stronger than the negatives" values_list = [int(x) for x in input().split()] print(numbers(values_list)) <file_sep>/02. Tuples and Sets/Exercise/01. Unique Usernames.py # https://judge.softuni.bg/Contests/Compete/Index/1833#0 # redo and make a return instead of print? def unique_un(n): usernames = [] for i in range(n): username = input() usernames.append(username) for each in set(usernames): print(each) unique_un(int(input())) <file_sep>/05. Functions Advanced/LAB/07. Operate.py # https://judge.softuni.bg/Contests/Practice/Index/1838#6 def operate(operator, *args): if operator == "+": return add(*args) elif operator == "-": return subtract(*args) elif operator == "*": return multiply(*args) elif operator == "/": return divide(*args) def add(*args): return sum(args) def subtract(*args): result = 0 for arg in args: result -= arg return result def multiply(*args): if len(args) == 0: return 0 else: result = 1 for arg in args: result *= arg return result def divide(*args): if len(args) == 0: return 0 else: result = 1 for arg in args: result /= arg return result print(operate("+", 1, 2, 0)) print(operate("*")) print(operate("-", 1, 2, 4)) print(operate("/", 1)) <file_sep>/04. Comprehension/Exercise/02. Words Lengths.py # https://judge.softuni.bg/Contests/Compete/Index/1837#1 # list comprehension result_list = [f"{each} -> {len(each)}" for each in input().split(", ")] print(", ".join(result_list)) # dictionary comprehension input_elements = {x: len(x) for x in input().split(", ")} result_list = [f"{key} -> {len(value)}" for key, value in input_elements.items()] print(", ".join(result_list)) # no comprehension words = input().split(", ") result = [] for each in words: each = f"{each} -> {len(each)}" result.append(each) print(", ".join(result)) <file_sep>/02. Tuples and Sets/LAB/01. Count Same Values.py # https://judge.softuni.bg/Contests/Practice/Index/1832#0 def count_values(user_values): values_count = {} for value in user_values: if value not in values_count: values_count[value] = 0 values_count[value] += 1 return values_count def print_values(values_dict): for (value, count) in values_dict.items(): print(f"{float(value)} - {count} times") user_values = input().split(" ") print_values(count_values(user_values)) <file_sep>/02. Tuples and Sets/Exercise/05. Phonebook.py # https://judge.softuni.bg/Contests/Compete/Index/1833#4 # redo and use new material def phonebook(): phone_dict = {} while True: user_input = input() if len(user_input) > 1: data = user_input.split("-") phone_dict[data[0]] = data[1] else: queries = int(user_input) break for i in range(queries): query_name = input() if query_name in phone_dict.keys(): print(f"{query_name} -> {phone_dict[query_name]}") else: print(f"Contact {query_name} does not exist.") phonebook() <file_sep>/03. Multidimensional lists/LAB/02. Sum Matrix Columns.py # https://judge.softuni.bg/Contests/Practice/Index/1834#1 # amount of columns is not needed, but it's given as input def build_matrix(rows_amount, columns): matrix = [] for _ in range(rows_amount): row = [int(x) for x in input().split(" ")] matrix.append(row) return matrix def find_sum(matrix): for i in range(len(matrix[0])): column_sum = 0 for each in matrix: column_sum += each[i] print(column_sum) # Alternative solution: def find_sum2(matrix): columns_sum = [0] * columns_count for row in range(rows_count): for column in range(columns_count): columns_sum[column] += matrix[row][column] # Print result: [print(each_sum) for each_sum in columns_sum] (rows_count, columns_count) = [int(x) for x in input().split(", ")] find_sum(build_matrix(rows_count, columns_count)) # find_sum2(build_matrix(rows_count, columns_count)) <file_sep>/02. Tuples and Sets/Exercise/04. Count Symbols.py # https://judge.softuni.bg/Contests/Compete/Index/1833#3 # redo and find a smarter way to sort the set def symbol_count(string): elements = [] unique_list = [] for each in string: elements.append(each) # remove duplicates unique = set(elements) # sort elements for each in unique: unique_list.append(each) unique_list.sort() for each in unique_list: print(f"{each}: {elements.count(each)} time/s") string = input() symbol_count(string) <file_sep>/04. Comprehension/Exercise/04. Number Classification.py # https://judge.softuni.bg/Contests/Compete/Index/1837#3 numbers = [int(x) for x in input().split(", ")] positive = [str(x) for x in numbers if x >= 0] negative = [str(x) for x in numbers if x < 0] even = [str(x) for x in numbers if x % 2 == 0] odd = [str(x) for x in numbers if not x % 2 == 0] print(f"Positive: {', '.join(positive)}") print(f"Negative: {', '.join(negative)}") print(f"Even: {', '.join(even)}") print(f"Odd: {', '.join(odd)}") # no comprehension numbers = [int(x) for x in input().split(", ")] positive = [] negative = [] even = [] odd = [] for each in numbers: if each >= 0: positive.append(each) if each < 0: negative.append(each) if each % 2 == 0: even.append(each) if not each % 2 == 0: odd.append(each) print(f"Positive: {', '.join([str(x) for x in positive])}") print(f"Negative: {', '.join([str(x) for x in negative])}") print(f"Even: {', '.join([str(x) for x in even])}") print(f"Odd: {', '.join([str(x) for x in odd])}") <file_sep>/01. Lists as Stacks and Queues/LAB/01. Reverse Strings.py # https://judge.softuni.bg/Contests/Practice/Index/1830#0 def reverse_func(string): stack = list(string) result = "" while stack: char = stack.pop() result += char return result text = input() print(reverse_func(text)) <file_sep>/06. File Handling/Exercise/01. Even Lines.py # Task 1 file_path = 'W:\\Documents\\@Python\\SoftUni\\python_advanced\\06_file_handling\\08-File-Handling-Lab-Resources\\Words Count\\text.txt' def replace_symbols(text): symbols = ["-", ",", ".", "!", "?"] for each_character in text: for each_symbol in symbols: if each_character == each_symbol: char_index = text.index(each_character) text = text[:char_index] + '@' + text[char_index + 1:] return text index = 0 with open(file_path, 'r') as file: even_lines_text = [] while True: line = file.readline().rstrip() if line == '': break if index % 2 == 0: # do symbol swapping filtered_line = replace_symbols(line) even_lines_text.append(filtered_line) index += 1 print(even_lines_text) def reverse_words(words_list): result = [] for each in words_list: line = each.split(" ") line.reverse() result.append(line) return result def print_output(reversed_list): for each_el in reversed_list: print(end="") for each_word in each_el: print(each_word, end=" ") print_output(reverse_words(even_lines_text)) <file_sep>/05. Functions Advanced/Exercise/05. Function Executor.py # https://judge.softuni.bg/Contests/Compete/Index/1839#4 def sum_numbers(num1, num2): return num1 + num2 def multiply_numbers(num1, num2): return num1 * num2 def func_executor(*args): result = [] for tuples in args: function = tuples[0] arguments = tuples[1] result.append(function(*arguments)) return result print(func_executor((sum_numbers, (1, 2)), (multiply_numbers, (2, 4)))) <file_sep>/05. Functions Advanced/Exercise/06. Keyword Arguments Length.py # https://judge.softuni.bg/Contests/Compete/Index/1839#5 def kwargs_length(**kwargs): return len(kwargs) dictionary = {'name': 'Peter', 'age': 25} print(kwargs_length(**dictionary)) <file_sep>/04. Comprehension/LAB/04. Flattening Matrix.py # https://judge.softuni.bg/Contests/Practice/Index/1836#3 sublists_amount = int(input()) # matrix = [input().split(", ") for _ in range(sublists_amount)] matrix = [] for _ in range(sublists_amount): matrix.append(input().split(", ")) # flattened_matrix = [num for each_list in matrix for num in each_list] flattened_matrix = [] for each_list in matrix: flattened_matrix += [int(num) for num in each_list] print(flattened_matrix) <file_sep>/01. Lists as Stacks and Queues/Excercise/03. Fast Food.py # https://judge.softuni.bg/Contests/Compete/Index/1831#2 from collections import deque def check_food(food_quantity): orders_left = [] queue = deque([int(x) for x in input().split(" ")]) biggest_order = max(queue) print(biggest_order) while queue: order = queue.popleft() if order <= food_quantity: food_quantity -= order else: orders_left.append(str(order)) if len(orders_left) == 0: return "Orders complete" else: return f"Orders left: {' '.join(orders_left)}" quantity = int(input()) print(check_food(quantity)) <file_sep>/05. Functions Advanced/LAB/03. Even Numbers.py # https://judge.softuni.bg/Contests/Practice/Index/1838#2 def find_even_n(values): return [x for x in values if x % 2 == 0] print(find_even_n(map(int, input().split()))) <file_sep>/01. Lists as Stacks and Queues/Excercise/05. Truck Tour.py # https://judge.softuni.bg/Contests/Compete/Index/1831#4 from collections import deque def pump_func(n): pumps = deque() original_pumps = [] # used for recursion, always revert to original deque if it fails on 1st,2nd.. etc. iteration fuel = 0 for _ in range(n): tokens = [int(x) for x in input().split(" ")] pumps.append(tokens) original_pumps.append(tokens) for i in range(n): pumps.rotate(-i) current = pumps.popleft() while pumps: # loop through petrol pumps fuel += current[0] if fuel >= current[1]: # if trip is successful remove the pump fuel -= current[1] current = pumps.popleft() else: # if trip fails revert to original deque and 0 fuel and start over fuel = 0 pumps = deque(original_pumps[:]) break if not pumps: # if the while loop ended and deque is empty trip is successful return i petrol_pumps = int(input()) print(pump_func(petrol_pumps)) <file_sep>/05. Functions Advanced/LAB/02. Rounding.py # https://judge.softuni.bg/Contests/Practice/Index/1838#1 def to_round(values): return [round(x) for x in values] print(to_round(map(float, input().split())))
6067795fb42d80d5da60f3944904f0b6c36aef54
[ "Python" ]
62
Python
tony-andreev94/Python-Advanced
bcbc6c686f6428008833f47efff1ea3fd892a520
7b45f9f549fc4c7983fdd118b517bc401ff4e1cd
refs/heads/master
<file_sep>import numpy as np import pandas as pd from tqdm import tqdm from Python.player import Player class GamePlay: """ Parameters: - population: multiple `Player`s who will play the game - game: (Class `Game`) payoff matrix which determines the rules of the game - num_pairing: number of times the population is paired up to play - num_rounds: number of iterations one pair plays the game How many times is a single game played: num_generation x num_pairing x num_rounds General vocab: - Game: two players play the game once - Iterated game: a game played for `num_rounds` rounds - Iteration: whole population plays the iterated game `num_pairing` times - Generations: after an Iteration, the population reproduces and the next generation starts the next iteration """ def __init__(self, population, game, num_pairing=5, num_rounds=100): self.population = population self.game = game self.game_history = pd.DataFrame() self.num_pairing = num_pairing self.num_rounds = num_rounds def play_game_for_multiple_pairings(self, ith_generation): for ith_pairing in tqdm(range(self.num_pairing)): self.play_multiple_rounds_in_pairs( ith_generation, ith_pairing, self.num_rounds) def play_multiple_rounds_in_pairs(self, ith_generation, ith_pairing, num_rounds): for ith_pair, pair in enumerate(self.pair_up_population()): self.play_multiple_rounds( *pair, ith_generation, ith_pairing, ith_pair, num_rounds) def play_multiple_rounds(self, player1, player2, ith_generation, ith_pairing, ith_pair, num_rounds): for i in range(num_rounds): self.play_round(player1, player2, ith_generation, ith_pairing, ith_pair, i) def play_round(self, player1, player2, ith_generation, ith_pairing, ith_pair, ith_round): player1_action = player1.get_current_action(player2.get_last_action()) player2_action = player2.get_current_action(player1.get_last_action()) player1_payoff = self.get_row_players_payoffs( player1_action, player2_action) player2_payoff = self.get_row_players_payoffs( player2_action, player1_action) player1.add_payoff_to_history(player1_payoff) player2.add_payoff_to_history(player2_payoff) self.add_round_to_game_history( id(player1), ith_generation, ith_pairing, ith_pair, ith_round, player1.strategy, player1_action, player1_payoff, id(player2) ) self.add_round_to_game_history( id(player2), ith_generation, ith_pairing, ith_pair, ith_round, player2.strategy, player2_action, player2_payoff, id(player1) ) def get_row_players_payoffs(self, player1_action, player2_action): return int(self.game.payoffTable[player1_action, player2_action]) def add_round_to_game_history(self, player_id, ith_generation, ith_pairing, ith_pair, ith_round, strat, action, payoff, opponents_id): self.game_history = self.game_history.append( { 'player_id': player_id, 'ith_generation': ith_generation, 'ith_pairing': ith_pairing, 'ith_pair': ith_pair, 'ith_round': ith_round, 'strategy': strat, 'action': action, 'payoff': payoff, 'opponents_id': opponents_id }, ignore_index=True ) def pair_up_population(self): np.random.shuffle(self.population) return list(zip(self.population[::2], self.population[1::2])) def calc_relative_strat_success_for_generation(self, ith_generation=None): if ith_generation is not None: ith_generation_game_history = self.game_history[ self.game_history['ith_generation'] == ith_generation ].copy() else: ith_generation_game_history = self.game_history.copy() payoff_total = ith_generation_game_history[['payoff']].sum()[0] ith_generation_game_history['tuple_strat'] = \ ith_generation_game_history['strategy'].apply(self._list_to_tuple) stratPayoff = ith_generation_game_history[ ['ith_generation', 'player_id', 'payoff', 'tuple_strat'] ].groupby(['ith_generation', 'player_id', 'tuple_strat']).sum( ).reset_index() stratPayoff['relativePayoff'] = \ stratPayoff[['payoff']] / payoff_total stratPayoff['strategy'] = \ stratPayoff['tuple_strat'].apply(self._tuple_to_list) return stratPayoff def reproduce_population(self, ith_generation): relative_strat_success = \ self.calc_relative_strat_success_for_generation(ith_generation) population_size = len(relative_strat_success.index) new_population_srategies = np.random.choice( a=relative_strat_success['strategy'].values, p=relative_strat_success['relativePayoff'].values, size=population_size ) self.population = [Player(strat) for strat in new_population_srategies] def mutate_population_with_prob(self, p): for player in self.population: if np.random.uniform() <= p: player.randomly_mutate_strategy() def _tuple_to_list(self, t): return list(map(self._tuple_to_list, t)) if isinstance(t, tuple) else t def _list_to_tuple(self, l): return tuple(map(self._list_to_tuple, l)) if isinstance(l, list) else l <file_sep># Plan and Questions ## Plan ### 1. [done] Randomly assigned pairs from population ### 2. [done] Modify simple strategies to automatons ### 3. Implement mutation ## Questions & Todos ### 1. How to handle: if player plays round then her history should be updated ### 2. GameHistory: figure out metrics to measure and adapt game history to it ### 3. Add private methdos (_)? ### 4. Use @properties, @classmethods and @staticmethods ### 5. Add logging<file_sep>.PHONY: help test clean main ipython .DEFAULT: help help: @echo "make test" @echo " clean" @echo " run tests" @echo "make clean" @echo " clean up .pyc files" @echo "make main" @echo " clean" @echo " run main.py" @echo "make ipython" @echo " open ipython3" test: clean @pipenv run python -m unittest discover -s tests $(TESTARGS) clean: @find . -name '*.pyc' -delete main: clean @pipenv run python main.py ipython: @pipenv run ipython3<file_sep>[[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] numpy = "*" pipfile = "*" pandas = "*" tqdm = "*" Pygments = ">=2.7.4" jinja2 = ">=2.11.3" bleach = ">=3.3.0" notebook = ">=6.4.1" [dev-packages] ipython = "*" mock = "*" ipdb = "*" pylint = "*" autopep8 = "*" rope = "*" jupyter = "*" ipykernel = "*" pep8 = "*" [requires] python_version = "3.8" <file_sep>import unittest import numpy as np from mock import patch from Python.game_play import GamePlay from Python.game import Game from Python.player import Player class TestGamePlay(unittest.TestCase): def setUp(self): self.pd = Game(np.array([[2, 0], [4, 1]])) self.players = [Player([[0, 0, 0]]), Player([[1, 0, 0]])] self.subject = GamePlay(population=self.players, game=self.pd) @patch('Python.player.Player.add_payoff_to_history') def test_playRound_callsadd_payoff_to_historyTwice(self, mock): self.subject.play_round(self.players[0], self.players[1], ith_generation=None, ith_pairing=None, ith_pair=None, ith_round=None) self.assertEqual(mock.call_count, 2) @patch('Python.game_play.GamePlay.add_round_to_game_history') def test_playRound_callsaddRoundToGameHistoryWithCorrectParams(self, mock): ith_generation = None ith_pairing = None ith_pair = None ith_round = None self.subject.play_round(*self.players, ith_generation=ith_generation, ith_pairing=ith_pairing, ith_pair=ith_pair, ith_round=ith_round) p1_strat = self.players[0].strategy p2_strat = self.players[1].strategy p1_action = self.players[0].strategy[0][0] p2_action = self.players[1].strategy[0][0] p1_payoff = self.subject.get_row_players_payoffs(p1_action, p2_action) p2_payoff = self.subject.get_row_players_payoffs(p2_action, p1_action) self.assertEqual(mock.call_args_list[0][0][0], id(self.players[0])) self.assertEqual(mock.call_args_list[0][0][1], ith_generation) self.assertEqual(mock.call_args_list[0][0][2], ith_pairing) self.assertEqual(mock.call_args_list[0][0][3], ith_pair) self.assertEqual(mock.call_args_list[0][0][4], ith_round) self.assertEqual(mock.call_args_list[0][0][5], p1_strat) self.assertEqual(mock.call_args_list[0][0][6], p1_action) self.assertEqual(mock.call_args_list[0][0][7], p1_payoff) self.assertEqual(mock.call_args_list[0][0][8], id(self.players[1])) self.assertEqual(mock.call_args_list[1][0][0], id(self.players[1])) self.assertEqual(mock.call_args_list[1][0][1], ith_generation) self.assertEqual(mock.call_args_list[1][0][2], ith_pairing) self.assertEqual(mock.call_args_list[1][0][3], ith_pair) self.assertEqual(mock.call_args_list[1][0][4], ith_round) self.assertEqual(mock.call_args_list[1][0][5], p2_strat) self.assertEqual(mock.call_args_list[1][0][6], p2_action) self.assertEqual(mock.call_args_list[1][0][7], p2_payoff) self.assertEqual(mock.call_args_list[1][0][8], id(self.players[0])) def test_getPlayerPayoffs_returnsProperPdPayoffs(self): self.assertEqual(self.subject.get_row_players_payoffs(0, 1), 0) self.assertEqual(self.subject.get_row_players_payoffs(1, 1), 1) self.assertEqual(self.subject.get_row_players_payoffs(0, 0), 2) def test_pairUpPopulation_returnsHalfLengthOfPlayers_givenEvenPlayer(self): self.assertEqual( len(self.subject.pair_up_population()), len(self.subject.population) / 2 ) def test_pairUpPop_returnsHalfLengthOfPlyrsMinusHalf_givenOddPlayers(self): players = [Player([0, 0, 0]) for i in range(7)] gameplay = GamePlay(players, self.pd) self.assertEqual( len(gameplay.pair_up_population()), len(gameplay.population) / 2 - 0.5 ) def test_pairUpWholePopulation_returnsListOfTuplesWithTwoPlayerEach(self): for pair in self.subject.pair_up_population(): self.assertIsInstance(pair, tuple) self.assertIsInstance(pair[0], Player) self.assertIsInstance(pair[1], Player) self.assertEqual(len(pair), 2) @patch('numpy.random.shuffle') def test_pairUpPopulation_callsShuffleOnPlayers(self, mock): self.subject.pair_up_population() self.assertEqual( mock.call_args_list[0][0][0], self.subject.population ) <file_sep>from Python.player import Player myPlayer = Player([[0, 0, 0]]) for i in range(10): print(i) myPlayer.randomly_mutate_strategy() print(myPlayer.strategy) <file_sep>import numpy as np class Player: ''' A player is basically a strategy. A strategy is a finite state automaton where nodes are actions and transitions point to nodes. Transitions are reactions to the opponent strategy's last action. An example strategy is Tit-for-tat: you start with 'cooperation' and then do what your opponent did last round. It's represented like so: [[0, 0, 1], [1, 0, 1]] The first string in each sublist is the action, the second element in the sublists is the transition which tells you to which state (node/sublist) to go when the opponent cooperated. 0 means go to the 0th node, i.e. stay at the current node if you are already there. The very first action is determined by the first element of the first node. ''' def __init__(self, strategy): self.strategy = strategy self.payoff_history = [] self.state_index_history = [] def get_current_action(self, opponents_last_action): if self.get_last_state_index() is None: self.update_state_index_history_with(0) return self.strategy[0][0] last_state = self.get_last_state() current_state_index = last_state[opponents_last_action + 1] current_action = self.strategy[current_state_index][0] self.update_state_index_history_with(current_state_index) return current_action def get_last_action(self): if self.get_last_state() is None: return self.strategy[0][0] else: return self.get_last_state()[0] def get_last_state_index(self): if not self.state_index_history: return None else: return self.state_index_history[-1] def get_last_state(self): if self.get_last_state_index() is None: return None else: return self.strategy[self.get_last_state_index()] def update_state_index_history_with(self, state_index): self.state_index_history.append(state_index) def add_payoff_to_history(self, payoff): self.payoff_history.append(payoff) def get_average_payoff(self): return np.mean(self.payoff_history) def randomly_mutate_strategy(self, verbose=False): random_mutation = np.random.choice([ self.remove_state, self.add_new_state, self.rewire_random_transition, self.change_random_state_action ]) if verbose: print(random_mutation.__name__) try: random_mutation() except Exception as Error: if verbose: print(Error) self.randomly_mutate_strategy() return self.strategy def change_random_state_action(self): random_state_index = np.random.randint(len(self.strategy)) self.strategy[random_state_index][0] = \ self.strategy[random_state_index][0] * -1 + 1 def rewire_random_transition(self): if len(self.strategy) == 1: raise Exception( f'Cannot rewire single state strategy ({self.strategy})' ) state_indexes = list(range(len(self.strategy))) random_state_index = np.random.choice(state_indexes) random_transition_index = np.random.choice([1, 2]) available_new_state_indexes = list(set(state_indexes) - set( [self.strategy[random_state_index][random_transition_index]]) ) new_random_state_index = np.random.choice(available_new_state_indexes) self.strategy[random_state_index][random_transition_index] = \ new_random_state_index def add_new_state(self): self._construct_and_append_new_state() self._connect_rnd_not_last_state_with_last_state() def _construct_and_append_new_state(self): new_action = np.random.choice([0, 1]) new_transitions = np.random.choice(len(self.strategy) + 1, size=2) self.strategy.append([new_action] + list(new_transitions)) def _connect_rnd_not_last_state_with_last_state(self): rnd_but_not_last_state_index = np.random.choice(len(self.strategy) - 1) rnd_transition_index = np.random.choice([1, 2]) self.strategy[rnd_but_not_last_state_index][rnd_transition_index] = \ len(self.strategy) - 1 def remove_state(self): if len(self.strategy) == 1: raise Exception( f'Cannot remove state from single state strategy: ' f'{self.strategy}') random_state_index = np.random.choice(range(len(self.strategy))) self.strategy.pop(random_state_index) self._rewire_transitions_pointing_to_removed_state() def _rewire_transitions_pointing_to_removed_state(self): available_states = range(len(self.strategy)) for state_index, state in enumerate(self.strategy): for transition_index, transition in enumerate(state[1:]): if transition not in available_states: new_random_state_index = np.random.choice(available_states) self.strategy[state_index][transition_index + 1] = \ new_random_state_index def __str__(self): return ("Player [{}] " "Average payoff: {}").format( self.strategy, self.get_average_payoff()) <file_sep>from Python.player import Player from Python.game import Game from Python.game_play import GamePlay import numpy as np if __name__ == "__main__": np.random.seed(999) pd = Game(np.array([[2, 0], [4, 1]])) players = [Player([[1, 0, 0]]) for _ in range(30)] num_generations = 5 num_pairing = 5 num_rounds = 20 probability_of_mutation = 0.5 gamePlay = GamePlay(players, pd, num_pairing, num_rounds) for ith_generation in range(num_generations): gamePlay.play_game_for_multiple_pairings(ith_generation) gamePlay.reproduce_population(ith_generation) gamePlay.mutate_population_with_prob(p=probability_of_mutation) gen_history = gamePlay.game_history[ gamePlay.game_history['ith_generation'] == ith_generation] print( f'{ith_generation + 1}. generation avg payoff: ' f'{gen_history["action"].mean()}' ) relativeStratSuccess = gamePlay.calc_relative_strat_success_for_generation( ) relativeStratSuccess.to_csv( f'output/num_gen_{num_generations}_' f'num_pairing_{num_pairing}_' f'num_rounds_{num_rounds}_' f'mute_prob_{probability_of_mutation}.csv', index=False ) <file_sep>class Game: ''' A Game is the payoff matrix of a game. E.g. for prisoner's dilemma it's C D C[2, 0] D[4, 1] The payoffs are from the row player's point of view, where first action is 'cooperate' and second is 'defect' ''' def __init__(self, payoffTable): self.payoffTable = payoffTable <file_sep>import unittest from mock import patch import numpy as np from Python.player import Player class TestPlayer(unittest.TestCase): def setUp(self): self.simplePlayer = Player([[0, 0, 0]]) self.titfortat_strategy = [[0, 0, 1], [1, 0, 1]] self.tftPlayer = Player(self.titfortat_strategy) def test_get_average_payoff_returns1_givenPayoffHistory1(self): self.simplePlayer.add_payoff_to_history(1) self.assertEqual(self.simplePlayer.get_average_payoff(), 1) def test_get_average_payoff_returns1_givenMultiplePayoffs(self): self.simplePlayer.add_payoff_to_history(1) self.simplePlayer.add_payoff_to_history(1) self.assertEqual(self.simplePlayer.get_average_payoff(), 1) def test_get_current_action_rtrnsFirstNodesAction_woStateIndexHistry(self): actual_action = self.simplePlayer.get_current_action( opponents_last_action=None) self.assertEqual(0, actual_action) def test_get_current_action_returnsCorrectActions_givenParams(self): actual_first_action = self.tftPlayer.get_current_action( opponents_last_action=None) self.assertEqual(0, actual_first_action) self.tftPlayer.update_state_index_history_with(actual_first_action) actual_second_action = self.tftPlayer.get_current_action( opponents_last_action=1) self.assertEqual(1, actual_second_action) @patch('Python.player.Player.update_state_index_history_with') def test_get_current_action_UpdtsStateIndexHistoryWith_noHist(self, mock): self.tftPlayer.get_current_action(opponents_last_action=None) self.assertEqual(1, mock.call_count) @patch('Python.player.Player.update_state_index_history_with') def test_get_current_action_UpdatesStateIndexHistoryWith_wHist(self, mock): self.tftPlayer.state_index_history.append(0) self.tftPlayer.get_current_action(opponents_last_action=0) self.assertEqual(1, mock.call_count) @patch('Python.player.Player.update_state_index_history_with') def test_get_current_action_crctlyClsUpdtStateIdxHistry_woHist(self, mock): self.tftPlayer.get_current_action( opponents_last_action=0) self.assertEqual(mock.call_args_list[0][0][0], 0) @patch('Python.player.Player.update_state_index_history_with') def test_get_current_action_corrctlyCallsUpdtStateIndexHistory(self, mock): self.tftPlayer.state_index_history.append(0) current_action = self.tftPlayer.get_current_action( opponents_last_action=0) self.assertEqual(mock.call_args_list[0][0][0], current_action) def test_get_last_state_index_returnsNone_givenEmptyStateHistory(self): self.assertEqual(None, self.simplePlayer.get_last_state_index()) def test_get_last_state_index_returns1_givenStateHistoryEndingIn1(self): self.simplePlayer.update_state_index_history_with(0) self.simplePlayer.update_state_index_history_with(1) self.assertEqual(1, self.simplePlayer.get_last_state_index()) def test_get_last_state_rtrn2ndState_given1asLastStateIndexHistory(self): self.tftPlayer.update_state_index_history_with(1) self.assertEqual( self.titfortat_strategy[1], self.tftPlayer.get_last_state() ) def test_get_last_state_returnsNone_givenEmptyStateHistory(self): self.assertEqual(None, self.tftPlayer.get_last_state()) def test_get_last_action_rtrnsDefaultActn_givenEmptyStateIndxHistory(self): self.assertEqual(0, self.simplePlayer.get_last_action()) def test_get_last_action_rtrnsCorrectly_givenNonEmptyStateIndxHstry(self): self.tftPlayer.update_state_index_history_with(1) self.assertEqual(1, self.tftPlayer.get_last_action()) def test_change_random_state_action_changesStateAction(self): self.simplePlayer.change_random_state_action() self.assertEqual(1, self.simplePlayer.strategy[0][0]) @patch('numpy.random.randint') def test_change_random_state_action_changesStateAction2(self, mock): mock.return_value = 1 self.tftPlayer.change_random_state_action() self.assertEqual(0, self.tftPlayer.strategy[0][0]) @patch('numpy.random.choice') def test_rewire_random_transition_givenExtendedTFT(self, mock): mock.side_effect = [1, 1, 1] self.tftPlayer.strategy.append([1, 2, 2]) self.tftPlayer.rewire_random_transition() self.assertEqual(1, self.tftPlayer.strategy[1][1]) def test_rewire_random_transition_returnsError_givenOneState(self): with self.assertRaises(Exception): self.simplePlayer.rewire_random_transition() def test_add_new_state_addsOneNewStateToStrategy(self): old_strategy_len = len(self.simplePlayer.strategy) self.simplePlayer.add_new_state() self.assertEqual(old_strategy_len + 1, len(self.simplePlayer.strategy)) def test_add_new_state_addsStateWith3Elements(self): self.simplePlayer.add_new_state() self.assertEqual(3, len(self.simplePlayer.strategy[-1])) @patch('Python.player.Player._connect_rnd_not_last_state_with_last_state') @patch('numpy.random.choice') def test_add_new_state_addsStateWith0or1AsFirstElement(self, rndChcMck, _): self.simplePlayer.add_new_state() self.assertEqual(rndChcMck.call_args_list[0][0][0], [0, 1]) @patch('Python.player.Player._connect_rnd_not_last_state_with_last_state') @patch('numpy.random.choice') def test_add_new_state_new_st_points_to_any_other_node(self, rndChcMck, _): self.tftPlayer.add_new_state() max_node_index = len(self.tftPlayer.strategy) self.assertEqual(rndChcMck.call_args_list[1][0][0], max_node_index) def test_add_new_state_hasAtLeastOneOtherStatePointingToIt(self): self.tftPlayer.add_new_state() new_state_index = len(self.tftPlayer.strategy) - 1 transitions = [] for state in self.tftPlayer.strategy[:-1]: for transition in state[1:]: transitions.append(transition) self.assertTrue(new_state_index in transitions) def test_remove_state_removesOneState(self): old_strategy_len = len(self.tftPlayer.strategy) self.tftPlayer.remove_state() self.assertEqual(old_strategy_len - 1, len(self.tftPlayer.strategy)) @patch('numpy.random.choice') def test_remove_state_choiceCalledWithCorrectParam(self, mock): old_strategy_length = len(self.tftPlayer.strategy) self.tftPlayer.remove_state() self.assertEqual( range(old_strategy_length), mock.call_args_list[0][0][0] ) def test_remove_state_remainingTransitsPointToExistingStates(self): np.random.seed(99) self.tftPlayer.remove_state() available_states = range(len(self.tftPlayer.strategy)) for state in self.tftPlayer.strategy: for transition in state[1:]: self.assertTrue(transition in available_states) def test_remove_state_raisesException_ifCalledOnSingleStateStrategy(self): with self.assertRaises(Exception): self.simplePlayer.remove_state() @ patch('Python.player.np.random.choice') @ patch('Python.player.Player.add_new_state') def test_rndmlyMutateStrat_mutatesIfFrstFindsErr(self, NwStateMck, rndMck): rndMck.side_effect = [ self.simplePlayer.remove_state, self.simplePlayer.add_new_state ] NwStateMck.__name__ = "newState_mock" self.simplePlayer.randomly_mutate_strategy() NwStateMck.assert_called_once()
636409ec54c9c28ef9b0775cdb7b2fe2745b7d19
[ "Markdown", "TOML", "Python", "Makefile" ]
10
Python
LePeti/evolutionary-game-theory
85035670d6f5f3725229e291c637406bea482646
db63932c94aa78e27e7b6891be721737d44e872d
refs/heads/main
<repo_name>RakeshCharpe/Face-Mask-Detection-Attendance-System<file_sep>/facemask/train.py from keras.preprocessing.image import ImageDataGenerator from json import decoder import numpy as np import keras import keras.backend as k from keras.layers import Conv2D, MaxPooling2D, SpatialDropout2D, Flatten, Dropout, Dense from keras.models import Sequential, load_model from keras.optimizers import Adam from keras.preprocessing import image # BUILDING MODEL TO CLASSIFY BETWEEN MASK AND NO MASK model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3))) model.add(MaxPooling2D()) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D()) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(100, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory( 'train', target_size=(150, 150), batch_size=16, class_mode='binary') test_set = test_datagen.flow_from_directory( 'test', target_size=(150, 150), batch_size=16, class_mode='binary') model_saved = model.fit_generator( training_set, epochs=10, validation_data=test_set, ) model.save('mymodel.h5', model_saved) <file_sep>/windows/admin_login.py import tkinter as tk from tkinter import Entry, messagebox from windows.admin_panel import admin_panel # ---------------ADMIN CREDENTIALS---------------- global admin_password global admin_username admin_username = "admin" admin_password = "<PASSWORD>" class administrator: def check(self): entered_password = self.entry_password.get() entered_username = self.entry_username.get() if entered_password == admin_password and admin_username == entered_username: messagebox.showinfo("SUCCESS", "LOGGING IN SUCCESSFUL") self.window.destroy() object2 = admin_panel() object2.admin() else: messagebox.showerror("ERROR", "CHECK CREDENTIALS") def admin_panel(self): self.window = tk.Tk() self.window.geometry("550x350") self.window.title("Admin Login") self.window.configure(background="turquoise") lab10 = tk.Label(self.window, text="", bg="turquoise", fg="dark slate gray", font=("times", 30, 'bold')) lab11 = tk.Label(self.window, text="Sign in", bg="turquoise", fg="dark slate gray", font=("Simplified Arabic fixed", 20, 'bold')) lab12 = tk.Label(self.window, text="", bg="turquoise", fg="dark slate gray", font=( "Simplified arabic fixed", 20, 'bold')) lab13 = tk.Label(self.window, text="", bg="turquoise", fg="dark slate gray", font=("times", 20, 'bold')) self.lbl_username = tk.Label( self.window, text="Enter Username: ", font=("Simplified Arabic fixed", 10, 'bold'), width=20, bg="turquoise", fg="Black", height=2 ) self.lbl_password = tk.Label( self.window, text="Enter Password: ", font=("Simplified Arabic fixed", 10, 'bold'), width=20, bg="turquoise", fg="Black", height=2 ) self.btn_login = tk.Button( self.window, text="LOGIN", font=("times", 10, 'bold'), width=42, height=3, bg="old lace", command=self.check, ) self.entry_username = tk.Entry( self.window, text="", bg="old lace", width=50, ) self.entry_password = tk.Entry( self.window, bg="old lace", text="", width=50, ) lab10.grid(row=2, column=0) lab11.grid(row=3, columnspan=2, column=0) lab12.grid(row=4, column=0) self.lbl_username.grid(row=6, column=0) self.lbl_password.grid(row=7, column=0) self.entry_username.grid(row=6, column=1) self.entry_password.grid(row=7, column=1) lab13.grid(row=8, column=0) self.btn_login.grid(row=10, columnspan=2, column=1) self.window.mainloop() <file_sep>/facemask/facemask.py from attendance.attendance import attendance from json import decoder import numpy as np import keras import keras.backend as k from keras.layers import Conv2D, MaxPooling2D, SpatialDropout2D, Flatten, Dropout, Dense from keras.models import Sequential, load_model from keras.optimizers import Adam from keras.preprocessing import image import cv2 import datetime class mask(object): def detect_mask(self): flag = 1 while flag: self.mymodel = load_model('facemask/mymodel.h5') self.cap = cv2.VideoCapture(0) self.face_cascade = cv2.CascadeClassifier( 'facemask/haarcascade_frontalface_default.xml') count_test = 0 while self.cap.isOpened(): _, img = self.cap.read() face = self.face_cascade.detectMultiScale( img, scaleFactor=1.1, minNeighbors=4) #count_test = 0 # print(count_test) for(x, y, w, h) in face: face_img = img[y:y+h, x:x+w] cv2.imwrite('temp.jpg', face_img) test_image = image.load_img( 'temp.jpg', target_size=(150, 150, 3)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) pred = self.mymodel.predict_classes(test_image)[0][0] if pred == 1: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 3) cv2.putText(img, 'INVALID MASK', ((x+w)//2, y+h+20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3) else: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3) cv2.putText(img, 'VALID MASK', ((x+w)//2, y+h+20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3) count_test += 1 datet = str(datetime.datetime.now()) cv2.putText(img, datet, (400, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) cv2.imshow('FaceMask', img) # print(count_test) if count_test == 20: print(True) self.cap.release() cv2.destroyAllWindows() attendance().mark() count_test = 0 if cv2.waitKey(1) == ord('q'): self.cap.release() cv2.destroyAllWindows() flag = 0 break <file_sep>/attendance/attendance.py import csv import datetime from os import name from barcode.barcode import barcode_read as read_code from admin_database import database import pandas as pd import sqlite3 as db class attendance(object): def __init__(self): self.file = open("attendance/data.csv") self.con = db.connect('databases//users_info.db') self.curr = self.con.cursor() def mark(self): found = 0 self.code = read_code().reader() print("MARKING") df = pd.read_csv("attendance/data.csv") if datetime.datetime.now().strftime("%x") in df.columns: pass else: x = datetime.datetime.now() df[x.strftime("%x")] = "absent" df.to_csv("attendance/data.csv", index=False) for codefind in df.barcode: if str(codefind) == self.code: df.loc[int(self.code)-1, datetime.datetime.now().strftime("%x")] = "present" df.to_csv("attendance/data.csv", index=False) found = 1 break if not found: print("NOT FOUND") self.curr.execute( "SELECT * FROM USERS where id=" + (str(self.code))) rows = self.curr.fetchall() print(rows[0][0]) if int(rows[0][0]) == int(self.code): # print(len(df)) df.loc[len(df), "barcode"] = self.code df.loc[len(df)-1, "name"] = rows[0][1] df["barcode"] = df["barcode"].astype(int) df.to_csv("attendance/data.csv", index=False) print(len(df.columns)) def show(self): print("SHOWN") <file_sep>/windows/open_panel.py import tkinter as tk from tkinter import messagebox from windows.admin_login import administrator from facemask.facemask import mask class opening_panel(object): def administrator(self): object1 = administrator() object1.admin_panel() def activate(self): print("ACTIVATED") mask().detect_mask() def on_closing(self): if messagebox.askokcancel("Quit", "Do you want to quit?"): self.window.destroy() def open_panel(self): self.window = tk.Tk() self.window.configure(background="turquoise") # background color self.window.protocol("WM_DELETE_WINDOW", self.on_closing) self.window.geometry("700x533") self.window.title("Face Mask Detection And Attendance System") # labels added lab5 = tk.Label(self.window, text="", bg="turquoise", fg="dark slate gray", font=("times", 36, 'bold')) lab1 = tk.Label(self.window, text="Face Mask Detection", bg="turquoise", fg="dark slate gray", font=("times", 36, 'bold')) lab2 = tk.Label(self.window, text="&", bg="turquoise", fg="dark slate gray", font=("times", 36, 'bold')) lab3 = tk.Label(self.window, text="Attendance System", bg="turquoise", fg="dark slate gray", font=("times", 36, 'bold')) lab4 = tk.Label(self.window, text="", bg="turquoise", fg="dark slate gray", font=("times", 36, 'bold')) self.btn_admin = tk.Button( self.window, text="Administrator", font=("simplified arabic fixed", 15, 'bold'), # font width=60, height=4, bg="old lace", # bg color command=self.administrator ) self.btn_activate = tk.Button( self.window, text="Activate System", font=("simplified arabic fixed", 15, 'bold'), # fonts width=60, height=4, bg="old lace", # bg col command=self.activate ) lab5.grid(row=1, column=2) lab1.grid(row=2, column=2) lab2.grid(row=3, column=2) lab3.grid(row=4, column=2) lab4.grid(row=5, column=2) self.btn_admin.grid(row=7, column=2) self.btn_activate.grid(row=8, column=2) self.window.mainloop() <file_sep>/main.py from windows.open_panel import opening_panel if __name__ == "__main__": task = opening_panel() task.open_panel() <file_sep>/barcode/barcode.py import cv2 import pyzbar.pyzbar as pyzbar class barcode_read(object): def reader(self): flag = 1 cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_PLAIN while flag: _, frame = cap.read() decodedObjects = pyzbar.decode(frame) for obj in decodedObjects: string = obj.data cv2.putText(frame, str(obj.data), (50, 50), font, 2, (255, 0, 0), 3) flag = flag-1 cap.release() cv2.destroyAllWindows() return str(string)[2:-1] cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) if key == 27: break <file_sep>/windows/admin_panel.py import tkinter as tk from tkinter import Entry, messagebox from windows.database_windows import database_methods class admin_panel(object): def delete(self): self.handle.delete_window() def add(self): self.handle.add_window() def view(self): self.handle.view_window() def attendance(self): self.handle.attend_window() def admin(self): self.handle = database_methods() self.admin_window = tk.Tk() self.admin_window.configure(background="turquoise") # background color self.admin_window.geometry("370x400") self.admin_window.title("Database") lab20 = tk.Label(self.admin_window, text="", bg="turquoise", fg="dark slate gray", font=("times", 15, 'bold')) lab21 = tk.Label(self.admin_window, text="Select an option", bg="turquoise", fg="dark slate gray", font=("Simplified Arabic fixed", 15, 'bold')) lab22 = tk.Label(self.admin_window, text="", bg="turquoise", fg="dark slate gray", font=("times", 20, 'bold')) self.btn_add = tk.Button( self.admin_window, text="Add Student", font=("times", 10, 'bold'), height=4, width=50, bg="old lace", command=self.add, ) self.btn_view = tk.Button( self.admin_window, text="View Students", font=("times", 10, 'bold'), height=4, width=50, bg="old lace", command=self.view, ) self.btn_delete = tk.Button( self.admin_window, text="Delete A Student", bg="old lace", font=("times", 10, 'bold'), width=50, height=4, command=self.delete, ) self.btn_attendance = tk.Button( self.admin_window, text="View Attendance", bg="old lace", font=("times", 10, 'bold'), width=50, height=4, command=self.attendance, ) lab20.grid(row=1, column=0) lab21.grid(row=2, columnspan=2, column=0) lab22.grid(row=3, column=0) self.btn_add.grid(row=5, column=1) self.btn_delete.grid(row=6, column=1) self.btn_view.grid(row=7, column=1) self.btn_attendance.grid(row=8, column=1) self.admin_window.mainloop() <file_sep>/admin_database.py import sqlite3 as db import os from sqlite3 import Error import datetime import sqlite3 import tkinter as tk from tkinter import messagebox class database: def __init__(self): self.con = db.connect('databases//users_info.db') self.curr = self.con.cursor() def add_user(self, id, name, year, dept, barcode): command = "INSERT INTO users VALUES('"+str(id)+"','" + \ name+"','"+str(year)+"','"+dept+"','"+barcode+"','0')" try: self.curr.execute(command) self.con.commit() messagebox.showinfo("SUCCESS", "USER ADDED") except sqlite3.Error as er: messagebox.showerror("Error", "Couldnt add the user "+str(er)) def delete_user(self, id): try: self.curr.execute("DELETE FROM users WHERE id=" + str(id)) self.con.commit() messagebox.showinfo("SUCCESS", "USER DELETED") except: messagebox.showerror("Error", "Failed to delete user") def view_users(self): try: self.curr.execute("SELECT * FROM users") rows = self.curr.fetchall() return rows except: messagebox.showerror("Error While Fetching Table") <file_sep>/windows/database_windows.py import tkinter as tk from tkinter import messagebox from admin_database import database as db from tkinter import * import subprocess from subprocess import Popen import os class database_methods(object): def view_command(self): self.list.delete(0, END) self.srows = db() rows = self.srows.view_users() for row in rows: self.list.insert(END, row) def delete_command(self): try: id = int(self.entry_id.get()) handle = db() handle.delete_user(id) except: messagebox.showerror("Error", "COULDNT DELETE USER") # --------------------------Windows---------------------------- def add_window(self): self.window_add = tk.Tk() self.window_add.geometry("500x400") self.window_add.title("Add A User") self.window_add.configure(background="turquoise") lab01 = tk.Label(self.window_add, text="", bg="turquoise", fg="dark slate gray", font=("times", 30, 'bold')) lab02 = tk.Label(self.window_add, text="Add User", bg="turquoise", fg="dark slate gray", font=("times", 30, 'bold')) lab03 = tk.Label(self.window_add, text="", bg="turquoise", fg="dark slate gray", font=("times", 30, 'bold')) self.lbl_id1 = tk.Label(self.window_add, text="Name: ", font=( "times", 10, 'bold'), bg="turquoise", fg="Black", height=2, width=20,) self.entry_id1 = tk.Entry(self.window_add, width=45,) self.lbl_id2 = tk.Label(self.window_add, text="Year: ", font=( "times", 10, 'bold'), bg="turquoise", fg="Black", height=2, width=20,) self.entry_id2 = tk.Entry(self.window_add, width=45,) self.lbl_id3 = tk.Label(self.window_add, text="Department: ", font=( "times", 10, 'bold'), bg="turquoise", fg="Black", height=2, width=20,) self.entry_id3 = tk.Entry(self.window_add, width=45,) lab04 = tk.Label(self.window_add, text="", bg="turquoise", fg="dark slate gray", font=("times", 30, 'bold')) self.btn_add = tk.Button(self.window_add, text="Add Student", font=( "times", 10, 'bold'), bg="old lace", height=3, width=42, command=self.window_add) lab01.grid(row=0, column=0) lab02.grid(row=1, column=1, columnspan=7) lab03.grid(row=3, column=0) self.lbl_id1.grid(row=5, column=1) self.entry_id1.grid(row=5, column=2) self.lbl_id2.grid(row=7, column=1) self.entry_id2.grid(row=7, column=2) self.lbl_id3.grid(row=9, column=1) self.entry_id3.grid(row=9, column=2) lab04.grid(row=10, column=3) self.btn_add.grid(row=11, column=1, columnspan=5) self.window_add.mainloop() def delete_window(self): self.window_delete = tk.Tk() self.window_delete.geometry("400x250") self.window_delete.configure(background="turquoise") self.window_delete.title("Delete A User") lab01 = tk.Label(self.window_delete, text="", bg="turquoise", fg="dark slate gray", font=("times", 15, 'bold')) lab02 = tk.Label(self.window_delete, text="Delete a user", bg="turquoise", fg="dark slate gray", font=("simplified arabic fixed", 15, 'bold')) lab03 = tk.Label(self.window_delete, text="", bg="turquoise", fg="dark slate gray", font=("times", 15, 'bold')) lab04 = tk.Label(self.window_delete, text="", bg="turquoise", fg="dark slate gray", font=("times", 15, 'bold')) self.lbl_id = tk.Label( self.window_delete, text="Enter ID to be Deleted: ", font=("times", 10, 'bold'), bg="turquoise", fg="Black", height=2, width=20, ) self.entry_id = tk.Entry(self.window_delete, width=30,) self.btn_delete = tk.Button( self.window_delete, text="DELETE", font=("times", 10, 'bold'), bg="old lace", height=2, width=25, command=self.delete_command, ) lab01.grid(row=1, column=1) lab02.grid(row=2, columnspan=2, column=1) lab03.grid(row=3, column=1) self.lbl_id.grid(row=5, column=1) self.entry_id.grid(row=5, column=2) lab04.grid(row=6, column=1) self.btn_delete.grid(row=7, column=2, columnspan=2) self.window_delete.mainloop() def view_window(self): self.window_view = tk.Tk() self.window_view.geometry("500x400") self.window_view.title("View All Users") self.list = tk.Listbox(self.window_view, height=25, width=65) self.scroller = tk.Scrollbar(self.window_view) self.btn_update = tk.Button( self.window_view, text="Update", height=1, width=20, command=self.view_command, ) self.btn_update.grid(row=30, column=0, columnspan=2) self.scroller.grid(row=2, column=2, rowspan=6) self.list.grid(row=2, column=0, rowspan=6, columnspan=2) self.list.configure(yscrollcommand=self.scroller.set) self.scroller.configure(command=self.list.yview) self.window_view.mainloop() def attend_window(self): os.system("cd attendance & data.csv") <file_sep>/README.md # Face Mask Detection And Attendance System It is a basic attendance system based on GUI and marks attendance only if the mask is detected and uses SQLITE database. It is under development. <br> ## Setup ``` bash $ git clone https://github.com/include-us/Face-Mask-Detection-Attendance-System.git $ cd Face-Mask-Detection-Attendance-System $ pip install -r requirements.txt IF YOU HAVE CUDA CORE BASED GPU $ conda install numba & conda install cudatoolkit $ python main.py ``` ### FILE STRUCTURE . ├── attendance # Attendance related files and storage in csv format ├── barcode # Barcode related program files ├── databases # Central database of users ├── facemask # Facemask related program package with cascades and tests ├── windows # GUI WINDOWS to access for low level user ├── admin-database.py ├── LICENSE ├── main.py ├── README.md └── requirements.txt ### CONTRIBUTERS 1. <NAME> 2. <NAME> 3. <NAME> 4. <NAME>
79d9a616d6dfec1afaf32f03018dfda5e5e7f53b
[ "Markdown", "Python" ]
11
Python
RakeshCharpe/Face-Mask-Detection-Attendance-System
ca3152414db8959ee97c5989dd499a23c11e1bba
d34653c27ba9591d83c01ff455380594a5f1fc07
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Models\Category; use App\Models\Exam; use Illuminate\Http\Request; class ExamController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $examList = Exam::query(); $categories = Category::query(); if ($request->category) { $examList = $examList->where('category_id', $request->category); } if ($request->sub_category) { $examList = $examList->where('sub_category_id', $request->sub_category); } return view('pages.exam.index')->with([ 'exam_list' => $examList->get(), 'categories' => $categories->get() ]); } /** * 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) { $request->validate([ 'name' => ['required', 'string', 'unique:exams'], 'category' => ['required'], 'sub_category' => ['required'], ]); $exam = Exam::create([ 'name' => $request->name, 'category_id' => $request->category, 'sub_category_id' => $request->sub_category, ]); session()->flash('action', ['type' => 'success', 'message' => 'Examination created']); return back(); } /** * Display the specified resource. * * @param \App\Models\Exam $exam * @return \Illuminate\Http\Response */ public function show(Exam $exam) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Exam $exam * @return \Illuminate\Http\Response */ public function edit(Exam $exam) { return view('pages.exam.edit')->with([ 'exam' => $exam, 'categories' => Category::all() ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Exam $exam * @return \Illuminate\Http\Response */ public function update(Request $request, Exam $exam) { $request->validate([ 'name' => ['required', 'string', 'unique:exams,name,' . $exam->id], 'category' => ['required'], 'sub_category' => ['required'], ]); $exam->update([ 'name' => $request->name, 'category_id' => $request->category, 'sub_category_id' => $request->sub_category, ]); session()->flash('action', ['type' => 'success', 'message' => 'Examination Updated']); return redirect()->route('exam.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\Exam $exam * @return \Illuminate\Http\Response */ public function destroy(Exam $exam) { if ($exam->delete()) { session()->flash('action', ['type' => 'success', 'message' => 'Examination Deleted']); return back(); } session()->flash('action', ['type' => 'warning', 'message' => 'Examination does not updated.']); return back(); } } <file_sep><?php namespace Database\Seeders; use App\Models\Role; use App\Models\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Admin $admin = User::create([ 'name' => 'Admin User', 'email' => '<EMAIL>', 'phone' => '01921577009', 'address' => 'Dhaka, Bangladesh', 'status' => 1, 'password' => <PASSWORD>('<PASSWORD>'), ]); $role_admin = Role::firstOrCreate(['name' => 'admin', 'description' => 'Admin role']); $admin->roles()->attach($role_admin); // Normal User $user = User::create([ 'name' => 'Normal User', 'email' => '<EMAIL>', 'phone' => '01921577008', 'address' => 'Dhaka, Bangladesh', 'status' => 1, 'password' => <PASSWORD>('<PASSWORD>'), ]); $role_user = Role::firstOrCreate(['name' => 'user', 'description' => 'Normal User role']); $user->roles()->attach($role_user); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Category; use App\Models\Exam; use App\Models\Question; use Illuminate\Http\Request; class QuestionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $questions = Question::query(); if (request('category')) { $questions->where('category_id', request('category')); } if (request('sub_category')) { $questions->where('sub_category_id', request('sub_category')); } return view('pages.question.index')->with([ 'question_list' => $questions->get(), 'categories' => Category::all() ]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $categories = Category::query(); return view('pages.question.create')->with([ 'categories' => $categories->get() ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'category_id' => 'required', 'sub_category_id' => 'required', 'question' => 'required|string|max:191', 'a' => 'required|string|max:191', 'b' => 'required|string|max:191', 'c' => 'required|string|max:191', 'd' => 'required|string|max:191', 'right_option' => 'required', 'time' => 'required|numeric', ]); $question = Question::create([ 'category_id' => $request->category_id, 'sub_category_id' => $request->sub_category_id, 'question' => $request->question, 'a' => $request->a, 'b' => $request->b, 'c' => $request->c, 'd' => $request->d, 'right_option' => $request->right_option, 'q_time' => $request->time, ]); session()->flash('action', ['type' => 'success', 'message' => 'Question Created']); return back(); } /** * Display the specified resource. * * @param \App\Models\Question $question * @return \Illuminate\Http\Response */ public function show(Question $question) { } /** * Show the form for editing the specified resource. * * @param \App\Models\Question $question * @return \Illuminate\Http\Response */ public function edit(Question $question) { return view('pages.question.edit')->with([ 'question' => $question, 'categories' => Category::all() ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Question $question * @return \Illuminate\Http\Response */ public function update(Request $request, Question $question) { $request->validate([ 'category_id' => 'required', 'sub_category_id' => 'required', 'question' => 'required|string|max:191', 'a' => 'required|string|max:191', 'b' => 'required|string|max:191', 'c' => 'required|string|max:191', 'd' => 'required|string|max:191', 'right_option' => 'required', 'time' => 'required|numeric', ]); $question->update([ 'category_id' => $request->category_id, 'sub_category_id' => $request->sub_category_id, 'question' => $request->question, 'a' => $request->a, 'b' => $request->b, 'c' => $request->c, 'd' => $request->d, 'right_option' => $request->right_option, 'q_time' => $request->time, ]); session()->flash('action', ['type' => 'success', 'message' => 'Question Updated']); return redirect()->route('question.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\Question $question * @return \Illuminate\Http\Response */ public function destroy(Question $question) { if ($question->delete()) { session()->flash('action', ['type' => 'success', 'message' => 'Question Deleted']); return back(); } session()->flash('action', ['type' => 'warning', 'message' => 'Question not delete.']); return back(); } } <file_sep><?php namespace App\Models; use App\Models\SubCategory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; class Exam extends Model { use HasFactory; protected $guarded = ['id']; /** * Get the category that owns the Exam * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function category(): BelongsTo { return $this->belongsTo(Category::class, 'category_id'); } /** * Get the sub_category that owns the Exam * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function sub_category(): BelongsTo { return $this->belongsTo(SubCategory::class, 'sub_category_id'); } /** * The questions that has many questions * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function questions(): HasMany { return $this->hasMany(Question::class, 'exam_id'); } } <file_sep><?php namespace App\Models; use App\Models\Category; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; class SubCategory extends Model { use HasFactory; protected $guarded = ['id']; /** * Get the category that owns the SubCategory * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function category(): BelongsTo { return $this->belongsTo(Category::class, 'category_id'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; class UserAnswer extends Model { use HasFactory; protected $guarded = ['id']; /** * Get the question that owns the UserAnswer * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function question(): BelongsTo { return $this->belongsTo(Question::class); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Category; use App\Models\SubCategory; use Illuminate\Http\Request; class SubCategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('pages.sub-category.index')->with([ 'categories' => Category::all(), 'sub_category_list' => SubCategory::all() ]); } /** * 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) { $request->validate([ 'name' => 'required|string|unique:sub_categories', 'category_id' => 'required' ]); $subCategory = SubCategory::create([ 'name' => $request->name, 'category_id' => $request->category_id ]); session()->flash('action', ['type' => 'success', 'message' => 'Sub Category store succcess...']); return back(); } /** * Display the specified resource. * * @param \App\Models\SubCategory $subCategory * @return \Illuminate\Http\Response */ public function show(SubCategory $subCategory) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\SubCategory $subCategory * @return \Illuminate\Http\Response */ public function edit(SubCategory $sub_category) { return view('pages.sub-category.edit')->with([ 'sub_category' => $sub_category, 'categories' => Category::all() ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\SubCategory $subCategory * @return \Illuminate\Http\Response */ public function update(Request $request, SubCategory $sub_category) { $request->validate([ 'name' => 'required|string|unique:sub_categories,name,' . $sub_category->id, 'category_id' => 'required' ]); $sub_category->update([ 'name' => $request->name, 'category_id' => $request->category_id ]); session()->flash('action', ['type' => 'success', 'message' => 'Sub Category Update succcess...']); return redirect()->route('sub-category.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\SubCategory $subCategory * @return \Illuminate\Http\Response */ public function destroy(SubCategory $sub_category) { if ($sub_category->delete()) { session()->flash('action', ['type' => 'success', 'message' => 'Sub Category delete succcess...']); return back(); } session()->flash('action', ['type' => 'warning', 'message' => 'Sub Category does not delete...']); return back(); } /** * Get sub categories by category * * @param Category $category * @return array */ public function getSubCategoryByCategory(Category $category) { $sub_list = $category->sub_categories; return response(['sub_list' => $sub_list]); } } <file_sep><?php namespace App\Models; use App\Models\Category; use App\Models\SubCategory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; class Question extends Model { use HasFactory; protected $guarded = ['id']; /** * Get the category that owns the Exam * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function category(): BelongsTo { return $this->belongsTo(Category::class, 'category_id'); } /** * Get the sub_category that owns the Exam * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function sub_category(): BelongsTo { return $this->belongsTo(SubCategory::class, 'sub_category_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Category; use App\Models\Question; use App\Models\UserAnswer; use Illuminate\Http\Request; class NormalUserController extends Controller { public function questions(Request $request) { $questions = Question::query(); if (request('category')) { $questions->where('category_id', request('category')); } if (request('sub_category')) { $questions->where('sub_category_id', request('sub_category')); } return view('user-pages.questions')->with([ 'questions' => $questions->get(), 'categories' => Category::all() ]); } public function question(Question $question) { return view('user-pages.question')->with([ 'question' => $question ]); } public function giveAnswer(Request $request, Question $question) { if (!$request->has('answer')) { session()->flash('action', ['type' => 'danger', 'message' => 'Please give a answer !']); return back(); } $answer = [ 'user_id' => auth()->id(), 'answer' => $request->answer, 'question_id' => $question->id ]; if ($request->answer == $question->right_option) { $answer['yes'] = 1; session()->flash('action', ['type' => 'success', 'message' => 'Your answer is currect']); } else { $answer['yes'] = 0; session()->flash('action', ['type' => 'warning', 'message' => 'Your answr is wrong !']); } UserAnswer::create($answer); return redirect()->route('my_answers'); } public function my_answers() { $answers = UserAnswer::query(); return view('user-pages.my_answer')->with([ 'my_answers' => $answers->where('user_id', auth()->id())->get() ]); } } <file_sep><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\CategoryController; use App\Http\Controllers\ExamController; use App\Http\Controllers\NormalUserController; use App\Http\Controllers\QuestionController; use App\Http\Controllers\SubCategoryController; // Routes Route::get('/', function () { return redirect('login'); }); Route::match(['get', 'post'], '/dashboard', function () { return view('dashboard'); })->name('admin.dashboard'); Route::view('/pages/slick', 'pages.slick'); Route::view('/pages/datatables', 'pages.datatables'); Route::view('/pages/blank', 'pages.blank'); Auth::routes(); Route::prefix('admin')->middleware('auth')->group(function () { Route::resource('category', CategoryController::class); Route::resource('sub-category', SubCategoryController::class); Route::resource('exam', ExamController::class); Route::resource('question', QuestionController::class); }); Route::prefix('user')->group(function () { Route::get('questions', [NormalUserController::class, 'questions'])->name('questions'); Route::get('quesiton/{question}', [NormalUserController::class, 'question'])->name('question'); Route::put('quesiton/answer/{question}', [NormalUserController::class, 'giveAnswer'])->name('answer'); Route::get('my/answer-list', [NormalUserController::class, 'my_answers'])->name('my_answers'); }); // ajax Route::get('get-sub-category/{category}', [SubCategoryController::class, 'getSubCategoryByCategory'])->name('get_sub_by_cat'); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
4f5daa9076ba9f5b966acca6f1c3beff313c152d
[ "PHP" ]
10
PHP
sahadatsays/mcq-exam-system
cbb23c73d7f6a3987c83a308b04eb732b89314a3
e553013ea3d53ee474d780caa5f610b7bc4a0617
refs/heads/master
<file_sep>package edu.inlab.katas; import org.junit.Test; import static org.junit.Assert.*; public class TaskTest { @Test public void testNewTask() { // Act Task task = new Task("comprar tomates"); // Assert assertEquals("comprar tomates", task.getDescription()); } @Test public void changeDescription() { // Arange Task task = new Task("<NAME>"); // Act task.setDescription("comprar 2 tomates"); // Assert assertEquals("comprar 2 tomates", task.getDescription()); } @Test public void markTaskAsDone() { // Arange Task task = new Task("<NAME>"); // Act task.setAsDone(); // Assert assertTrue(task.isDone()); } @Test public void TaskIsNotDoneByDefault() { // Act Task task = new Task("comprar tomates"); // Assert assertFalse(task.isDone()); } @Test public void setTaskUndone() { // Arrange Task task = new Task("comprar tomates"); task.setAsDone(); // Act task.setNotDone(); // Assert assertFalse(task.isDone()); } }<file_sep>package edu.inlab.katas; import org.junit.Test; import static org.junit.Assert.*; /** * Created by ester.lorente on 29/11/2017. */ public class TaskListManagerTest { @Test public void AddNewTaskList() throws Exception { //arrange TaskList tl = new TaskList(); TaskListManager manager = new TaskListManager(); //act manager.addTaskList(tl); //assert assertTrue("contains the added tasklist", manager.contains(tl)); } } <file_sep>package edu.inlab.katas; import java.util.*; public class TaskList { private ArrayList<Task> taskList; public TaskList() { this.taskList = new ArrayList<Task>(); } public int size() { return taskList.size(); } public void addTask(Task task) { taskList.add(task); } public void deleteTask(Task task) { taskList.remove(task); } public boolean contain(Task task) { return taskList.contains(task); } } <file_sep>package edu.inlab.katas; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TaskListTest { @Test public void CreateEmptyTaskList() { // Act TaskList tl = new TaskList(); // Assert assertEquals(0, tl.size()); } @Test public void AddNewTask() { // Arrange TaskList tl = new TaskList(); // Act Task task = new Task("comprar butiffara"); tl.addTask(task); // Assert assertEquals(1, tl.size()); assertTrue("Contains the added task", tl.contain(task)); } @Test public void DeleteTaskFromTasklist() throws Exception { // arrange TaskList tl = new TaskList(); Task task = new Task("comprar butiffara"); tl.addTask(task); //act int before_size = tl.size(); tl.deleteTask(task); //assert assertNotEquals("Size of list is differennt", before_size, tl.size()); assertFalse("List not contains the task", tl.contain(task)); } }
3bda39f5961ad747040922e13e0b40ebf52bbe8b
[ "Java" ]
4
Java
elorenteg/todo-list-kata-java
d50ade6135d2e6eb11cd765f5ab45ee798315047
f6de8e7811e03739311dbbbd2b0521261ad0c878
refs/heads/master
<file_sep># Assignment: Caching the Inverse of a Matrix # # Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix # rather than compute it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). # Your assignment is to write a pair of functions that cache the inverse of a matrix. # Write the following functions: # # 1.- makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse. # 2.- cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. # If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache. # # Computing the inverse of a square matrix can be done with the solve function in R. # For example, if X is a square invertible matrix, then solve(X) returns its inverse. # For this assignment, assume that the matrix supplied is always invertible. # The first function, makeCacheMatrix creates a special "matrix", which is really a list containing a function to # 1.- set the value of the matrix # 2.- get the value of the matrix # 3.- set the value of the inverse # 4.- get the value of the inverse makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinv <- function(inv) m <<- inv getinv <- function() m list(set = set, get = get, setinv = setinv, getinv = getinv) } # The following function calculates the inverse of the special "matrix" created with the above function. # However, it first checks to see if the inverse has already been calculated. If so, it gets the inverse from # the cache and skips the computation. Otherwise, it calculates the inverse of the data and sets the value of # the inverse in the cache via the solve function. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getinv() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data, ...) x$setinv(m) m }
87de096f4e01220735a49cc9798c5c7a3faeac02
[ "R" ]
1
R
ClaraCL/ProgrammingAssignment2
c1ac25827bd5b2d2ab39ab708262dab92624e779
24d4730fee6465ea8925ba6e4df3d895bdb73013
refs/heads/master
<file_sep>package com.jellebreuer.app.notes.backend; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Load; import java.util.ArrayList; import java.util.List; @Entity public class UserOnline { @Id private String email; @Load private List<Ref<NoteOnline>> notes = new ArrayList<>(); public UserOnline() { } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<NoteOnline> getNotes() { ArrayList<NoteOnline> notesList = new ArrayList<>(); for (Ref<NoteOnline> ref : this.notes) { notesList.add(ref.get()); } return notesList; } public void setNotes(List<NoteOnline> notes) { List<Ref<NoteOnline>> refs = new ArrayList<>(); for (NoteOnline note : notes) { refs.add(Ref.create(note)); } this.notes = refs; } } <file_sep>package com.jellebreuer.app.notes; import android.app.ProgressDialog; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.jellebreuer.app.notes.backend.notesApi.NotesApi; import com.jellebreuer.app.notes.backend.notesApi.model.NoteOnline; import com.jellebreuer.app.notes.backend.notesApi.model.UserOnline; import java.io.IOException; import java.util.ArrayList; public class NoteActivity extends AppCompatActivity { private EditText note; private static NotesApi myApiService = null; private String userName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); initToolbar(); note = (EditText) findViewById(R.id.txtNote); SharedPreferences settings = getSharedPreferences("Koelkast", 0); userName = settings.getString("PREF_ACCOUNT_NAME", null); } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); String mActivityTitle = getTitle().toString(); if (toolbar != null) { toolbar.setTitle(mActivityTitle); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } } private class saveNote extends AsyncTask<NoteOnline, Void, Void> { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(NoteActivity.this); pDialog.setMessage("Saving Note"); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected Void doInBackground(NoteOnline... params) { if (myApiService == null) { NotesApi.Builder builder = new NotesApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null) .setRootUrl("https://notes-98810.appspot.com/_ah/api/") .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { @Override public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException { abstractGoogleClientRequest.setDisableGZipContent(true); } }); myApiService = builder.build(); } for (NoteOnline n : params) { try { UserOnline user = myApiService.getUser(userName).execute(); NoteOnline note = myApiService.insertNote(n).execute(); ArrayList<NoteOnline> notes = (ArrayList<NoteOnline>) user.getNotes(); if(notes == null){ ArrayList<NoteOnline> notes2 = new ArrayList<>(); notes2.add(note); user.setNotes(notes2); } else { notes.add(note); user.setNotes(notes); } myApiService.updateUser(user.getEmail(), user).execute(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void v) { pDialog.dismiss(); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_note, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_add) { if(note.getText().toString().equals("")){ Toast toast = Toast.makeText(NoteActivity.this, "Please fill in all fields", Toast.LENGTH_SHORT); toast.show(); } else { NoteOnline n = new NoteOnline(); n.setNote(note.getText().toString()); new saveNote().execute(n); } } return super.onOptionsItemSelected(item); } } <file_sep>package com.jellebreuer.app.notes.backend; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; @Entity public class NoteOnline { @Id private Long id; private String note; public NoteOnline() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
f9c7d209550b34b820857ae48a0c15bfd2736098
[ "Java" ]
3
Java
tsm200/Notes
b9219b7f731e57224d2332d232ad4399a3ed3fac
706ef0ef67baedaf35ca3da528f01ebd351f6a79
refs/heads/master
<repo_name>jayhe/RunloopLearning<file_sep>/Podfile source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' #use_frameworks! target 'RunloopLearning' do pod 'Bugly' pod 'fishhook' end
7d02c88297c654274bcb52567f6fcd6581bc8d06
[ "Ruby" ]
1
Ruby
jayhe/RunloopLearning
7fc7af7975e9f979deba5ffe4781d572dae919cc
751e1bb8ef93c162279d8191127c8df847b5c924
refs/heads/main
<repo_name>jcjuliocss/testa-conexao-internet<file_sep>/testa_conexao.py import speedtest from datetime import datetime from threading import Timer def testa_conexao(): s = speedtest.Speedtest() s.get_servers() s.get_best_server() s.download() s.upload() res = s.results.dict() data_hora = datetime.now().strftime('%d/%m/%Y %H:%M') results = { 'server': res['server'], 'download': res['download'] / 1024, 'upload': res['upload'] / 1024, 'ping': res['ping'], 'data_hora': data_hora } Timer(1800, testa_conexao).start() with open('saida.txt', 'a') as file: file.writelines(str(results) + '\r\n') file.close() testa_conexao() <file_sep>/README.md # testa-conexao-internet script para testar a conexão com a internet, por padrão roda a cada 30 minutos # intalação pip install -r requirements.txt
7da672ee5cadc4568b28ced2bea3c4db5bb920c9
[ "Markdown", "Python" ]
2
Python
jcjuliocss/testa-conexao-internet
615b41fc510cfb0ee9654a475dddb5840e446acf
393e096a0f3e0084b57703dc6acc9a5c9ef04fe7
refs/heads/master
<file_sep>import environs env = environs.Env() env.read_env() TIIMA_USERNAME = env.str("TIIMA_USERNAME", "") TIIMA_PASSWORD = env.str("TIIMA_PASSWORD", "") TIIMA_COMPANY_ID = env.str("TIIMA_COMPANY_ID", "") TIIMA_API_KEY = env.str("TIIMA_API_KEY", "") <file_sep>from .tiima import Tiima <file_sep># Tiima A Python wrapper around the Visma Tiima mobile REST API ## Installation ### PIP `pip install tiima` ### Poetry `poetry add tiima` ## Usage ``` from tiima import Tiima # Usage with env vars tiima = Tiima() tiima.login() # Setting auth variables explicitly tiima = Tiima(company_id="foo", api_key="bar) tiima.login(username="<EMAIL>", password="<PASSWORD>") # Calling an API endpoint print(tiima.user()) ``` ### Configuration Authentication can be done either explcitly or by settings the following environment variables: | Variable | Description | | ----------------- | ------------------------------------ | | TIIMA_USERNAME | Users Tiima username (email) | | TIIMA_PASSWORD | Users Tiima password | | TIIMA_COMPANY_ID | Users company id (usually all caps) | | TIIMA_API_KEY | Tiima API Key | ## Disclaimer This software has no connection to Visma, nor is it in any way endorsed by Visma or any other company affiliated with the product (Visma Tiima). This project was created to make it easier for developers to use the API and for them to be able to create their own application around the API. ## License MIT <file_sep>[tool.poetry] name = "tiima" version = "0.1.0" description = "Python API Client for Visma Tiima" authors = ["<NAME> <<EMAIL>>"] license = "MIT" readme = "README.md" repository = "https://gitlab.com/python-poetry/poetry" [tool.poetry.dependencies] python = "^3.6" requests = "^2.23" beautifulsoup4 = "^4.8" environs = "^7.2" [tool.poetry.dev-dependencies] black = "=19.10b0" flake8 = "^3.7" isort = "^4.3" mypy = "^0.740.0" safety = "^1.8" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" <file_sep>import datetime from typing import Any, Dict, Optional, Union from urllib.parse import urljoin import requests from .settings import TIIMA_API_KEY, TIIMA_COMPANY_ID, TIIMA_PASSWORD, TIIMA_USERNAME class TiimaSession(requests.Session): def __init__(self, company_id: str, api_key: str,) -> None: super().__init__() self.url_base = "https://www.tiima.com/rest/api/mobile/" self._set_default_headers() self._set_default_login(company_id=company_id, api_key=api_key) def _set_default_headers(self) -> None: self.headers.update( { "X-Tiima-Language": "en", "User-Agent": "Mozilla/5.0 (Linux; Android 8.0.0;) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.119 Mobile Safari/537.36", } ) def _set_default_login(self, company_id: str, api_key: str) -> None: self.auth = (company_id, api_key) def request(self, method: str, url: str, **kwargs: Any) -> requests.Response: # type: ignore url = urljoin(self.url_base, url) return super().request(method, url, **kwargs) class Tiima: """ Usage: # Usage with env vars tiima = Tiima() tiima.login() # Setting auth variables explicitly tiima = Tiima(company_id="foo", api_key="bar) tiima.login(username="<EMAIL>", password="<PASSWORD>") # Calling an API endpoint yesterday = datetime.datetime.now() - datetime.timedelta(days=1) print(tiima.workinghours(date=yesterday)) """ def __init__( self, company_id: str = TIIMA_COMPANY_ID, api_key: str = TIIMA_API_KEY, ) -> None: self.api = TiimaSession(company_id=company_id, api_key=api_key) def login( self, username: str = TIIMA_USERNAME, password: str = <PASSWORD>, ) -> None: login_data = { "username": username, "password": <PASSWORD>, "clientVersion": "0.1", "deviceType": "Android", "deviceDescription": "OnePlus 7", } response = self.api.post("user/login", json=login_data) if response.status_code != 200: raise Exception( f"Login failed ({response.status_code}) with the credentials given for {TIIMA_USERNAME}. {response.text}" ) json_response = response.json() token = json_response.get("token", None) if not token: raise Exception("No token returned during login") self.api.headers.update({"X-Tiima-Token": token}) def __call_get( self, url: str, query_params: Optional[Dict[str, Any]] = None ) -> Any: if not query_params: query_params = {} response = self.api.get(url, params=query_params) if response.status_code != 200: raise Exception( f"Request to {url} failed with status code {response.status_code}. {response.text}" ) return response.json() def __call_post(self, url: str, data: Optional[Dict[str, Any]] = None) -> Any: if not data: data = {} response = self.api.post(url, json=data) if response.status_code != 200: raise Exception( f"Request to {url} failed with status code {response.status_code}. {response.text}" ) return response.json() def __parse_date(self, date: Union[datetime.datetime, str]) -> str: valid_date_structure = "%Y-%m-%d" if isinstance(date, str): try: datetime.datetime.strptime(date, valid_date_structure) except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") return date elif isinstance(date, datetime.datetime): return date.strftime(valid_date_structure) def reason_codes(self) -> Any: url = "reasoncodes" return self.__call_get(url) def user(self) -> Any: url = "user" return self.__call_get(url) def user_state(self) -> Any: url = "user/state" return self.__call_get(url) def user_enter(self, reason_code: int = 1) -> Any: url = "user/enter" data = {"reasonCode": reason_code} return self.__call_post(url, data=data) def user_leave(self, reason_code: int = 1) -> Any: url = "user/leave" data = {"reasonCode": reason_code} return self.__call_post(url, data=data) def user_to_lunch(self, reason_code: int = 1) -> Any: url = "user/toLunch" data = {"reasonCode": reason_code} return self.__call_post(url, data=data) def user_from_lunch(self, reason_code: int = 1) -> Any: url = "user/fromLunch" data = {"reasonCode": reason_code} return self.__call_post(url, data=data) def workinghours(self, date: Optional[Union[datetime.datetime, str]] = None) -> Any: if not date: date = datetime.datetime.now() url = "workinghours" query_params = {"date": self.__parse_date(date)} return self.__call_get(url, query_params=query_params) def calendar_plans( self, start_date: Union[datetime.datetime, str], end_date: Union[datetime.datetime, str], ) -> Any: url = "calendar/plans" query_params = { "startDate": self.__parse_date(start_date), "endDate": self.__parse_date(end_date), } return self.__call_get(url, query_params=query_params) def calendar_shifts( self, start_date: Union[datetime.datetime, str], end_date: Union[datetime.datetime, str], ) -> Any: url = "calendar/shifts" query_params = { "startDate": self.__parse_date(start_date), "endDate": self.__parse_date(end_date), } return self.__call_get(url, query_params=query_params) def bulletins(self) -> Any: url = "bulletins" return self.__call_get(url) def bulletins_mark(self, bulletin_id: str) -> Any: url = "bulletins/mark" data = {"bulletinId": bulletin_id} return self.__call_post(url, data=data)
99e8cdb7e1dcfb389f99c80ca90eb28b3731fbc7
[ "Markdown", "TOML", "Python" ]
5
Python
frwickst/tiima
a3bbccb362a406a06175b733c97deb716be73c7c
31628bfc5845a0af52c6f038d1a9ccfdcb1dc236
refs/heads/master
<file_sep>require 'json' class DataGrabber def get(file) JSON.parse(File.read("public/json/#{file}.json")) end def extract(file, keys) data = get(file) data.select {|key| keys.include? key} end end <file_sep>require 'rubygems' require 'sinatra' require '/home/ai_zakharov/www/web.rb' #require 'web.rb' root_dir = File.dirname(__FILE__) #require root_dir + '/gensou.rb' set :environment, :production set :app_file, '/home/ai_zakharov/www/web.rb' #set :root, root_dir #set :app_file, File.join(root_dir, 'web.rb') disable :run FileUtils.mkdir_p 'log' unless File.exists?('log') log = File.new("log/sinatra.log", "a") $stdout.reopen(log) $stderr.reopen(log) run Sinatra::Application <file_sep>gensou ====== Touhoumon Online<file_sep>require 'gensou' Gensou.run! <file_sep>module Game class Interface def initialize @nextGameInterface = GameInterface.new(self) # {socket: ClientInterface} @interfaces = {} end def addPlayer(socket) @interfaces[socket] = @nextGameInterface if @nextGameInterface.addPlayer(socket) # We added the second player to the game; the next player should be # added to a new game @nextGameInterface = GameInterface.new(self) end end # Called when a message is received from the client def message(socket, message) if @interfaces.include? socket @interfaces[socket].message(socket, message) else print "Got message from unknown socket #{socket}\n" end end # Send a message to the client def send(socket, message) socket = socket #EM.next_tick do socket.send(JSON.dump(message)) #end end end class GameInterface def initialize(interface) # Game::Interface @interface = interface # [Playersocket] @players = [] @player_objects = [] # {Playersocket: [DataMessage]} @log = {} # {Playersocket: GameCallback} @callback = {} # {Playersocket: GameAction -> bool} @legality = {} end # Returns true iff a new game was started def addPlayer(socket) @players << socket @log[socket] = [{"type" => "ready"}] #if @players.length >= 2 ## Set up the game #@players.each do |p| #@log[p] << { #"type" => "data", #"phase" => "select_starting_hero", #} #send_log(p) #@callback[p] = nil #@legality[p] = nil #end #return true #else send_log(socket) return false #end end def message(socket, message) # If somehow we got a message from the wrong socket, ignore it unless @players.include? socket return end case message["type"] when "chat" send_all({ "type" => "chat", "message" => message["message"] }) when "action" sleep(1) if @legality[socket].nil? or not @legal[socket].call(message) send(socket, {"type" => "illegal"}) else @callback[socket].add_action(socket, message) end when "id" @player_objects << Player.new(socket, message["id"]) #if @player_objects.length >= 2 #@game = Game.new(@player_objects) #end end #send_all({ #"type" => "data", #"my_active_hero" => message["action"], #"enemy_active_hero" => "mokou", #"phase" => "select_action" #}) end def request_player_action(sockets, callback, legality_check) sockets = [sockets].flatten sockets.each do |socket| @callback[socket] = GameCallback.new(socket, callback) @legal[socket] = legality_check send_log(@players[socket]) end end def send_log(socket) send(socket, @log[socket]) @log[socket] = [] end def send(socket, message) print "Sent message #{message}\n" @interface.send(socket, message) end end # A callback can require the input of one or both players. When all required # players have selected their action, calls the callback. # sockets :: [Playersocket] # callback :: [[Playersocket, GameAction]] -> class GameCallback def initialize(sockets, callback) @actions = [] @sockets = sockets @callback = callback end def add_action(socket, action) if @sockets.include? socket @actions << [socket, action] @sockets.delete(socket) end if @sockets.empty? callback.call(@actions) end end end class Game def initialize(interface, socket, id) @interface = interface @socket = socket @data = load_data(id) @interface.send(id, @data) end end class Player def initialize(socket, id) print "Initializing new player #{id}\n" my_stacks = JSON.parse(File.read("public/json/#{id}.json")) # We don't know what any of the enemy heroes are at the start of the game enemy_stacks = {} heroes = JSON.parse(File.read("public/json/heroes.json")) spellcards = JSON.parse(File.read("public/json/spellcards.json")) items = JSON.parse(File.read("public/json/items.json")) types = JSON.parse(File.read("public/json/types.json")) message = [{ "type" => "initial_load", "my_stacks" => my_stacks, "enemy_stacks" => enemy_stacks, "heroes" => heroes, "spellcards" => spellcards, "items" => items, "types" => types, }] socket.send(JSON.dump(message)) end end class PlayQueue end end # module Game <file_sep>css_depends = FileList["public/less/*.less"] css_targets = css_depends.collect { |c| "../deploy/#{c.gsub("less", "css")}" } haml = "views/play.haml" haml_target = "../deploy/#{haml}" task :default => [:build] do end task :heroku => :build do sh "cd ../deploy && git add * && git commit -m 'deploy' && bundle && git push heroku master" end task :ai => :build do sh "rm ../deploy/Gemfile.lock" sh "sftp -b ai.batch ai_zakharov:<EMAIL>" end task :build => [haml_target, css_targets] do end task :copy do sh "cp -rp * ../deploy" end css_depends.zip(css_targets).each do |depend, target| file target => [depend] do |t| sh "lessc #{depend} > #{target}" end end file haml_target => [haml, :copy] do # Replace references to .less with .css; remove include of less.js sh "grep -v -e 'js/less\\.js.' -e 'stylesheet/less' -e 'js/jquery\\.js' #{haml} | sed 's/\\(.*\\)\\/\\/\\/\\(.*\\)/\\1\\2/' > #{haml_target}" end <file_sep>require 'game' require 'json' require 'pp' class SocketMock @@nextSocketID = 0 def initialize @messages = [] @id = @@nextSocketID @@nextSocketID += 1 end def send(message) @messages << message end def messages @messages.collect {|m| JSON.parse(m)} end def messages_with_type(type) messages.find_all {|m| m["type"] == type} end def id @id end end def send_messages(players, messages) sockets = [] players.times do socket = SocketMock.new sockets << socket @int.addPlayer(socket) end messages.length.times do |i| @int.message(sockets[i], messages[i]) end return sockets end def dummy_callback(args) pp args end def dummy_legality(args) true end class HaveStartingMessages def matches?(target) target.messages.length.should == 1 message = target.messages[0] message["type"].should == "data" message.should include("my_stacks") message.should include("heroes") message.should include("spellcards") message.should include("items") end end def have_starting_messages HaveStartingMessages.new end class HaveStartedGameWith def initialize(opponent) @opponent = opponent end def matches?(target) target.messages.length.should == 2 message = target.messages[1] message["type"].should == "data" message["phase"].should == "begin_game" message.should include("enemy_stacks") end end def have_started_game_with HaveStartedGameWith.new end describe Game::Interface do before :each do @int = Game::Interface.new end it "Sends one chat message to one player" do sockets = send_messages(1, [{"type" => "chat", "message" => "hello"}]) sockets[0].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}]) end it "Sends one chat message to two players" do sockets = send_messages(2, [{"type" => "chat", "message" => "hello"}]) sockets[0].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}]) sockets[1].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}]) end it "Sends two chat messages to two players" do sockets = send_messages(2, [{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}]) sockets[0].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}]) sockets[1].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}]) end it "Sends three chat messages split amongst three players" do sockets = send_messages(3, [{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}, {"type" => "chat", "message" => "!!!"}]) sockets[0].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}]) sockets[1].messages_with_type("chat").should eq([{"type" => "chat", "message" => "hello"}, {"type" => "chat", "message" => "world"}]) sockets[2].messages_with_type("chat").should eq([{"type" => "chat", "message" => "!!!"}]) end it "Sends the begin game message" do sockets = send_messages(2, []) sockets[0].messages.should eq([{"type" => "data", "phase" => "select_starting_hero"}]) sockets[1].messages.should eq([{"type" => "data", "phase" => "select_starting_hero"}]) end it "Doesn't send the begin game message until ready" do sockets = send_messages(1, []) sockets[0].messages.should eq([]) end it "Doesn't send the begin game message to player 3" do sockets = send_messages(3, []) sockets[0].messages.should eq([{"type" => "data", "phase" => "select_starting_hero"}]) sockets[1].messages.should eq([{"type" => "data", "phase" => "select_starting_hero"}]) sockets[2].messages.should eq([]) end it "Calls a one-player callback" do @int.send_mesages(1, [{}]) end it "Calls a two-player callback" do end it "Rejects illegal actions" do end it "Rejects the wrong player ID" do end it "Completes a standard 2-player game start" do # Create the players p1_socket = SocketMock.new p1_id = "player1" p2_socket = SocketMock.new p2_id = "player2" @int.addPlayer(p1_socket, p1_id) p1_socket.should have_starting_messages @int.addPlayer(p2_socket, p2_id) p1_socket.should have_starting_messages p1_socket.should have_started_game_with(p2_socket) p2_socket.should have_started_game_with(p1_socket) end end <file_sep>source :rubygems gem 'sinatra' gem 'thin' gem 'haml' gem 'sinatra-websocket' #gem 'json' <file_sep>#!/bin/bash for file in `ls icon*.png`; do convert -crop 64x64 $file c_$file done rm *-1.png <file_sep># main.rb require 'rubygems' require 'haml' require 'sinatra' require 'sinatra-websocket' require 'json' require 'lib/game' # set :sockets, [] set :environment, :development #class Gensou < Sinatra::Base get '/' do haml :play end get '/get_data' do end $game_interface = Game::Interface.new get '/socket' do request.websocket do |socket| socket.onopen do $game_interface.addPlayer(socket) socket.send(JSON.dump({"type" => "ready"})) end socket.onmessage do |message| print "Got message: #{message}\n" m = JSON.parse(message) $game_interface.message(socket, m) end end end <file_sep>Starting a game: Client: Display loading screen Client -> Server: open socket Server -> Client: Acknowledge Client -> Server: Send login name Server -> Client: Send to game Server -> Interface: addPlayer(socket, id) Interface -> GameInterface: addPlayer(socket, id) GameInterface: players << socket GameInterface: player_objects << Player.new(socket, id) Player: data = database.lookup(id) Player -> GameInterface: send data to socket Client: Load player's data Client: Display player's data if this is the second player: GameInterface: send to each player "start game" GameInterface: game = Game.new(player_objects) Game -> GameInterface: request_player_action(players, start_game) Client->Server: (socket, action [starting hero]) Server->Interface: (socket, action) Interface: game_interfaces[socket].send(socket, action) Once both players have responded: GameInterface -> Game: start_game(actions) <file_sep>// Generated by CoffeeScript 1.3.3 (function() { this.util = Object(); this.util.attribute_function = function(att) { return $.fn[att] = function(val) { if (val != null) { return this.attr(att, val); } else { return this.attr(att); } }; }; this.util.hsl_to_hexcolor = function(h, s, l) { var b, g, hue, m1, m2, r; h = (h % 255) / 255; s = (s % 255) / 255; l = (l % 255) / 255; m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; m1 = l * 2 - m2; hue = function(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } else if (h * 2 < 1) { return m2; } else if (h * 3 < 2) { return m1 + (m2 - m1) * (2 / 3 - h) * 6; } else { return m1; } }; r = Math.floor(hue(h + 1 / 3) * 255); g = Math.floor(hue(h) * 255); b = Math.floor(hue(h - 1 / 3) * 255); return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }; }).call(this); <file_sep>require 'game' describe Game::Interface do it "works" do 1.should eql 1 end end <file_sep>require 'data' require 'json' require 'pp' describe DataGrabber do it "loads the player1 data" do data = get("player1") data.keys.length.should == 6 data.should include("youmu") end end
e537f72ea885041a44429ab0c61d8b3ecdd3c0ec
[ "Ruby", "Markdown", "JavaScript", "Text", "Shell" ]
14
Ruby
andrewebert/gensou
91d87493ead202bddb5415bea760d2757df55e88
534e5ec326b64d9bd03d672bf96989968e30a06c
refs/heads/master
<repo_name>Eshan-Agarwal16/machine-learning-coursera<file_sep>/machine-learning-ex4/ex4/SQ6.c #include<stdio.h> #include<conio.h> #include<string.h> void main() { int i=0,j=0,count=0; char str1[100],str2[20],str3[20]; clrscr(); printf(“Enter the text: “); gets(str1); printf(“Enter word to count: “); gets(str2); while(str1[i]!=”) { while(str1[i]!=’ ‘&&str1[i]!=”) str3[j++]=str1[i++]; str3[j]=”; j=0; if((strcmpi(str2,str3))==0) count++; if(str1[i]==”) break; else i++; } printf(“No. of words are %d”,count); getch(); }<file_sep>/machine-learning-ex4/ex4/SQ4.c #include <stdio.h> void main() { int i,j,d; d=0; char a[100],b[100]c[200]; gets(a); gets(b); n1=strlen(a); n2=strlen(b); if(n1>n2) { j=0; for(i=0;i<n1;++i) { c[i+d] = a[i]; if(j<n2) { d=d+1; c[d+j]=b[j]; d=d+1; j=j+1; } } } else { j=0; for(i=0;i<n2;++i) { if(j<n1) { c[j+d] = a[j]; j=j+1; d=d+1; } c[d+i]=b[i]; } } printf("%s\n",c ); }<file_sep>/machine-learning-ex4/ex4/SQ1c.c #include<stdio.h> void main() { int i,j; char a[100],b[100],c[200]; gets(a); gets(b); for(i=0;a[i]!='\0';++i) c[i]=a[i]; for(j=0;b[j]!='\0';++j) c[i+j]=b[j]; }<file_sep>/machine-learning-ex4/ex4/SQ1.c //1a #include <stdio.h> void main() { int i; char a[100],b[100]; gets(a); for(i=0;a[i]!='\0';++i) b[i]=a[i] }<file_sep>/machine-learning-ex4/ex4/SQ2.c #include<stdio.h> void main() { int i; char a[100]; gets(a); for(i=0;a[i]!='\0';++i) printf("%d",int(a[i])); }<file_sep>/machine-learning-ex4/ex4/SQ1b.c #include <stdio.h> void main() { int i,flag,l1,l2; flag = 1; for(i=0;a[i] != '\0';++i); l1=i; for(i=0;b[i] != '\0';++i); l2=i; char a[100],b[100]; gets(a); gets(b); if(l1==l2) for(i=0;a[i] != '\0';++i) if(a[i] != b[i]) flag = 0; else flag = 0; if(flag) printf("The strings are same"); else printf("The strings are not the same"); }<file_sep>/machine-learning-ex4/ex4/SQ1d.c #include<stdio.h> void main() { int i,temp; char a[100]; gets(a); for(i=0;a[i]!='\0';++i); int l = i-1; for(i=0;i<l/2;++i) { temp=a[i]; a[i]=a[l-1-i]; a[l-1li]=temp; } }<file_sep>/machine-learning-ex2/ex2/python1.py #ans to q1: def find_dup(a): dup = [] for x in a: if a.count(x) > 1: dup.append(x) return set(x) #ans to q2: ans = dict(zip(l1,l2)) #l1,l2 are list to be combined #ans to q3: a = input() lc,wc,lec = 1,0,0 for x in a: if x == '\n': lc = lc + 1 a = a.split(" ") wc = len(a) for x in a: lec = lec + len(x) #ans to q4: def count_w(a): a = a.split() a = {x for x in a} a = list(a) ans = {x : a.count(x) for x in a} print(ans) #ans to q5: def rem_dup(a): for x in a: if a.count(x) > 1: a.remove(x) return a #ans to q6: s = input("Enter the string :") w = input("word to be inserted:") p = int(input("position to be inserted")) s = s.split(" ") s.insert(p,w) s = " ".join(s) #ans to q7: l = [] while True: try: l.appened(input()) exc brea ans = {x:len(x) for x in l} print(ans) #ans to q8: s = input() s = [x for x in s] temp = s[0] for x in s: if x == temp: s[s.index(x)] = temp s[0] = temp print("".join(s)) #ans to Q9: s = input() print({s:len(s)}) s = [x for x in s] s1 = {x for x in s} print({x:s.count(x) for x in s1}) #ans to Q10: l = list(map(int,input("ENTER THE LIST").split(" "))) n = int(input("ENTER THE ELEMENT TO SEARCH")) for x in l: if x == n: print(f"ELEMENT {} FOUND AT POSITION {}".{n,l.index(x)}) break
a17619ddfd073f90ef7293556f265e67dd5dac0a
[ "C", "Python" ]
8
C
Eshan-Agarwal16/machine-learning-coursera
c40cddeccd12bd4eb92c98002e12674068d693e7
d1d5fd1b0ade0939a9cf9b968c3a28750b0a1105
refs/heads/main
<repo_name>tribeshouse/WioSCD30<file_sep>/src/main.cpp #include <Arduino.h> #include "SCD30.h" #include"seeed_line_chart.h" //include the library TFT_eSPI tft; #define max_size 50 //maximum size of data #define num_charts 3 //number of charts #define label_width 16 doubles data[num_charts]; //Initilising a doubles type to store data TFT_eSprite spr = TFT_eSprite(&tft); // Sprite void setup() { tft.begin(); tft.setRotation(3); spr.createSprite(TFT_HEIGHT,TFT_WIDTH); scd30.initialize(); } void loop() { spr.fillSprite(TFT_WHITE); float result[3] = {0}; float temp = 0.0; float hum = 0.0; float co2 = 0.0; if(scd30.isAvailable()) { scd30.getCarbonDioxideConcentration(result); co2 = result[0]; temp = result[1]; hum = result[2]; } if (data[0].size() == max_size) { for (uint8_t i = 0; i<num_charts; i++){ data[i].pop(); //this is used to remove the first read variable } } data[0].push(temp); //read variables and store in data data[1].push(hum); data[2].push(co2); //Settings for the line graph title auto header = text(0, 0) .value("temp/humid/co2") .align(center) .valign(vcenter) .width(tft.width()) .thickness(3); header.height(header.font_height() * 2); header.draw(); //Header height is twice the height of the font //Write data to screen int label_height = (tft.height() - header.height()*1.5) / num_charts; char str[6]; dtostrf(temp,5,1,str); auto label1 = text(tft.width()-label_width-5,header.height()); label1 .value(str) .width(label_width) .height(label_height) .align(right) .valign(vcenter) .color(TFT_RED) .draw() ; dtostrf(hum,5,1,str); auto label2 = text(tft.width()-label_width-5,header.height() + label_height * 1); label2 .value(str) .width(label_width) .height(label_height) .align(right) .valign(vcenter) .color(TFT_BLUE) .draw() ; dtostrf(co2,5,1,str); auto label3 = text(tft.width()-label_width-5,header.height() + label_height * 2); label3 .value(str) .width(label_width) .height(label_height) .align(right) .valign(vcenter) .color(TFT_PURPLE) .draw() ; //Settings for the line graph auto content1 = line_chart(20, header.height()); //(x,y) where the line graph begins content1 .height((tft.height() - header.height() * 1.5)) //actual height of the line chart .width(tft.width() - content1.x() * 2 - label_width) //actual width of the line chart .based_on(0.0) //Starting point of y-axis, must be a float .show_circle(false) //drawing a cirle at each point, default is on. .value({data[0],data[1]}) //passing through the data to line graph .color(TFT_RED,TFT_BLUE) //Setting the color for the line .draw(); //Settings for the line graph auto content2 = line_chart(20, header.height()+10); //(x,y) where the line graph begins content2 .height((tft.height() - header.height() * 1.5)) //actual height of the line chart .width(tft.width() - content1.x() * 2 - label_width) //actual width of the line chart .based_on(0.0) //Starting point of y-axis, must be a float .show_circle(false) //drawing a cirle at each point, default is on. .value({data[2]}) //passing through the data to line graph .color(TFT_PURPLE) //Setting the color for the line .draw(); spr.pushSprite(0, 0); delay(5000); }
d61ffc827f3c77b1a2da2dbf2878b19e016ac59f
[ "C++" ]
1
C++
tribeshouse/WioSCD30
9254c4d83ecab4f134c5d73bba6dc1918d1b764a
438291d3ae3368c6d71d084c74d14a3eb794fc41
refs/heads/master
<file_sep>x = 5.0 y = 30 z = 5 print x + y print x - y print y * x print y / x print x / y print x < y print x == z print x != y if x != z: print "x ni enako z" else: print "sta enaka"<file_sep>x = float(raw_input("Vstavi prvo stevilko")) y = float(raw_input("Vstavi drugo stevilko")) znak = float(raw_input("za sestevanje vpisi 1, za odstevanje vpisi 2, za mnozenje vpisi 3, za deljenje vpisi 4")) if znak == 1: print (x + y) elif znak == 2: print (x - y) elif znak == 3: print (x * y) elif znak == 4: print (x / y) else: print("Napaka")
3da1a1aedac710bd31d1f2d710e34b7614eb1bec
[ "Python" ]
2
Python
mareSLO/kalkulator
06fbdfc2e7bff4005fc028c73377de97f4081aa8
3dd67eb352aea396299599c9a7762087c601d28c
refs/heads/master
<repo_name>bipinGosain/observerpattern<file_sep>/Assets/Scenes/ObserverSphere.cs  using System; using UnityEngine; public class ObserverSphere : MonoBehaviour { Material mat; private void Start() { mat = GetComponent<MeshRenderer>().materials[0]; FindObjectOfType<SubjectRandChngClr>().changedColor += ObserverSphere_changedColor; ; } private void ObserverSphere_changedColor(object sender, EventArgs e) { mat.color = ((DerivedColor)e).changedColor; } } <file_sep>/Assets/Scenes/ObserverCylinder.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObserverCylinder : MonoBehaviour { Material mat; private void Start() { mat = GetComponent<MeshRenderer>().materials[0]; FindObjectOfType<SubjectRandChngClr>().changedColor += ObserverCylinder_changedColor; } bool changingColor = false; Color newColor; private void ObserverCylinder_changedColor(object sender, System.EventArgs e) { this.changingColor = true; this.newColor = ((DerivedColor)e).changedColor; routine = StartCoroutine(LerpColorsOverTime(10)); } Coroutine routine ; private IEnumerator LerpColorsOverTime(float time) { Color originalColor = mat.color; float inversedTime = 1 / time; for (var step = 0.0f; step < 1.0f; step += Time.deltaTime * inversedTime) { mat.color = Color.Lerp(originalColor, this.newColor, step); yield return null; } StopCoroutine(routine); } } <file_sep>/Assets/GenerateCubesAndCylinders.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateCubesAndCylinders : MonoBehaviour { [SerializeField] ObserverCylinder cylinder; [SerializeField] ObserverSphere sphere; Vector3[] spherePos, cylPos; private void Start() { spherePos = new Vector3[] { new Vector3(3, 1.5f, 5), new Vector3(0, 1.5f, 5), new Vector3(-3, 1.5f, 5) }; cylPos = new Vector3[] { new Vector3(3, .5f, 5), new Vector3(0, .5f, 5), new Vector3(-3, .5f, 5) }; for (int i = 0; i < spherePos.Length; i++) { Instantiate(sphere, spherePos[i], Quaternion.identity); Instantiate(cylinder, cylPos[i], Quaternion.identity); } } }
89cfe2be10315196960b700d71db7fb34a630a68
[ "C#" ]
3
C#
bipinGosain/observerpattern
8cb6eb87a0cdf828f013beb87564b7e99a1a9ef1
ac81958922779af13e4a5e45ba3ecb37d403b973
refs/heads/master
<repo_name>raymaen/test-express-aws<file_sep>/index.js const express = require("express"); const app = express(); const port = 3000; let sendStr = "init"; if (process.env.NODE_ENV === "production") { sendStr = "prod"; } else { sendStr = "dev"; } app.get("/", (req, res) => res.send("Hello World!" + sendStr)); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
a1bf5ed8375b0303cdc5f03da5e9ffbb59d448a2
[ "JavaScript" ]
1
JavaScript
raymaen/test-express-aws
f056e9fea2a49956cf9471304ca6c1336fc2f813
9967a6e343254e2b2c0ad4ffa099e8619d0e427e
refs/heads/main
<file_sep>const path = require('path'); const multer = require('multer'); const { MulterError } = require('multer'); var storage = multer.diskStorage({ destination: function(req, file, cb){ if(file.fieldname === "photo"){ cb(null, 'uploads/photo/') } else if(file.fieldname === "signature"){ cb(null, 'uploads/signature/') } }, filename: function(req, file, cb){ if(file.fieldname === "photo"){ let ext = path.extname(file.originalname) cb(null, Date.now() + ext) } else if (file.fieldname === "signature"){ let ext = path.extname(file.originalname) cb(null, Date.now() + ext) } } }) var upload = multer({ storage: storage, fileFilter: function(req, file, callback){ if( file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" ){ callback(null, true) } else{ console.log('only jgp/jpeg and png file supported') callback(null, false) } }, limits: { fileSize: 1024 * 1024 * 2 } }).fields( [ {name: 'photo', maxCount:1}, {name: 'signature', maxCount:1} ] ) module.exports = upload<file_sep>const mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var autoIncreament = require('mongoose-auto-increment'); var connection = mongoose.createConnection("mongodb+srv://idcl:<EMAIL>/idcldb?retryWrites=true&w=majority" , { useNewUrlParser: true, useUnifiedTopology: true}); mongoose.set('useCreateIndex', true); autoIncreament.initialize(connection); //define mongoose schema var registration = new Schema({ appmode: { type: String }, post: { type: String }, name: { type: String }, fathername: { type: String }, mothername: { type: String }, gender: { type: String }, maritalstatus: { type: String }, spousename: { type: String }, nationality: { type: String }, mothertongue: { type: String }, identitymark: { type: String }, category: { type: String }, disability: { type: String }, typesofdisability: { type: String }, otherdisability: { type: String }, jkDomicile: { type: String }, exserviceman: String, ews: String, religion: String, mobilenumber: Number, aadhar: Number, email: String, password: String, dob: String, address: String, district: String, state: String, pincode: Number, highschool: String, hboardname: String, hyear: Number, hpercentage: Number, intermediate: String, iboardname: String, iyear: Number, ipercentage: Number, graduation: String, gboardname: String, gyear: Number, gpercentage: Number, postgraduation: String, pboardname: String, pyear: Number, ppercentage: Number, examcenter: String, photo: String, signature: String, id: { type: String }, entity: { type: String }, amount: { type: Number }, currency: { type: String }, status: { type: String }, order_id: { type: String }, invoice_id: { type: String }, international: { type: Boolean }, method: { type: String }, amount_refunded: { type: Number }, refund_status: { type: String }, captured: { type: Boolean }, description: { type: String }, card_id: { type: String }, card: { id: { type: String }, entity: { type: String }, name: { type: String }, last4: { type: Date }, network: { type: String }, type: { type: String }, issuer: { type: String }, international: { type: Boolean }, emi: { type: Boolean }, sub_type: { type: String } }, bank: { type: String }, wallet: { type: String }, vpa: { type: String }, email: { type: String }, contact: { type: String }, notes: { type: Array }, fee: { type: Number }, tax: { type: Number }, error_code: { type: String }, error_description: { type: String }, error_source: { type: String }, error_step: { type: String }, error_reason: { type: String }, acquirer_data: { auth_code: { type: String } }, created_at: { type: Number } }); //Auto Increament registration.plugin(autoIncreament.plugin, { model: 'Students', field: 'RegistrationNo', startAt: 10200100, incrementBy: 3 }); // generating a hash registration.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid registration.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.password); }; var Students = mongoose.model('Students', registration); module.exports = Students; <file_sep>function validateForm() { let email = document.forms["regForm"]["email"].value; var confirmemail = document.forms["regForm"]["confirmemail"].value; if (email !== confirmemail) { alert("Email ID And Cofirm Email Id Not Matched"); return false; } let password = document.forms["regForm"]["password"].value; var confirmpassword = document.forms["regForm"]["confirmpassword"].value; if (password !== confirmpassword) { alert("Password And Cofirm Password Not Matched"); return false; } } $(document).ready(function(){ $("#exampleModalCenter").modal('show'); }); function readPhoto(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#photoView').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } function readSign(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#signatureView').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#photo").change(function(){ readPhoto(this); if(this.files[0].size > 51200){ alert("Photo Size Must less Than 50KB"); this.value = ""; } }); $("#signature").change(function(){ readSign(this); if(this.files[0].size > 20480){ alert("Signature Size Must less Than 20KB"); this.value = ""; } }); var pwd = document.getElementById('password'); var letter = document.getElementById("letter"); var capital = document.getElementById("capital"); var number = document.getElementById("number"); var length = document.getElementById("length"); // When the user clicks on the password field, show the message box pwd.onfocus = function() { document.getElementById("pwdmessage").style.display = "block"; } // When the user clicks outside of the password field, hide the message box pwd.onblur = function() { document.getElementById("pwdmessage").style.display = "none"; } // When the user starts to type something inside the password field pwd.onkeyup = function() { // Validate lowercase letters var lowerCaseLetters = /[a-z]/g; if(pwd.value.match(lowerCaseLetters)) { letter.classList.remove("pwdinvalid"); letter.classList.add("pwdvalid"); } else { letter.classList.remove("pwdvalid"); letter.classList.add("pwdinvalid"); } // Validate capital letters var upperCaseLetters = /[A-Z]/g; if(pwd.value.match(upperCaseLetters)) { capital.classList.remove("pwdinvalid"); capital.classList.add("pwdvalid"); } else { capital.classList.remove("pwdvalid"); capital.classList.add("pwdinvalid"); } // Validate numbers var numbers = /[0-9]/g; if(pwd.value.match(numbers)) { number.classList.remove("pwdinvalid"); number.classList.add("pwdvalid"); } else { number.classList.remove("pwdvalid"); number.classList.add("pwdinvalid"); } // Validate length if(pwd.value.length >= 8) { length.classList.remove("pwdinvalid"); length.classList.add("pwdvalid"); } else { length.classList.remove("pwdvalid"); length.classList.add("pwdinvalid"); } } // ================== // =====Captcha===== // ================= onload = function Captcha(){ var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9'); var i; for (i=0;i<6;i++){ var a = alpha[Math.floor(Math.random() * alpha.length)]; var b = alpha[Math.floor(Math.random() * alpha.length)]; var c = alpha[Math.floor(Math.random() * alpha.length)]; var d = alpha[Math.floor(Math.random() * alpha.length)]; var e = alpha[Math.floor(Math.random() * alpha.length)]; var f = alpha[Math.floor(Math.random() * alpha.length)]; var g = alpha[Math.floor(Math.random() * alpha.length)]; } var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g; document.getElementById("mainCaptcha").innerHTML = code document.getElementById("mainCaptcha").value = code } function CaptchaReload(){ var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9'); var i; for (i=0;i<6;i++){ var a = alpha[Math.floor(Math.random() * alpha.length)]; var b = alpha[Math.floor(Math.random() * alpha.length)]; var c = alpha[Math.floor(Math.random() * alpha.length)]; var d = alpha[Math.floor(Math.random() * alpha.length)]; var e = alpha[Math.floor(Math.random() * alpha.length)]; var f = alpha[Math.floor(Math.random() * alpha.length)]; var g = alpha[Math.floor(Math.random() * alpha.length)]; } var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g; document.getElementById("mainCaptcha").innerHTML = code document.getElementById("mainCaptcha").value = code } function ValidCaptcha(){ var string1 = removeSpaces(document.getElementById('mainCaptcha').value); var string2 = removeSpaces(document.getElementById('txtInput').value); if (string1 == string2){ return true; }else{ alert('Invalid Captch'); return false; } } function removeSpaces(string){ return string.split(' ').join(''); } <file_sep>var User = require('../models/registrationModel'); var LocalStrategy = require('passport-local').Strategy; module.exports = function (passport) { passport.serializeUser(function (user, done) { done(null, user._id); }); passport.deserializeUser(function (_id, done) { User.findById(_id, function (err, user) { done(err, user); }); }); // ========================================================================= // LOCAL SIGNUP ============================================================ // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField: 'email', passwordField: '<PASSWORD>', passReqToCallback: true // allows us to pass back the entire request to the callback }, function (req, email, password, done) { // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function () { // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'email': email }, function (err, user) { // if there are any errors, return the error if (err) return done(err); // check to see if theres already a user with that email if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { // if there is no user with that email // create the user var newUser = new User(); // set the user's local credentials newUser.email = email; newUser.password = <PASSWORD>(password); newUser.appmode = req.body.appmode; newUser.post = req.body.post; newUser.name = req.body.name; newUser.fathername = req.body.fathername; newUser.mothername = req.body.mothername; newUser.gender = req.body.gender; newUser.maritalstatus = req.body.maritalstatus; newUser.category = req.body.category; newUser.jkDomicile = req.body.jkDomicile; newUser.identitymark = req.body.identitymark; newUser.disability = req.body.disability; newUser.exserviceman = req.body.exserviceman; newUser.ews = req.body.ews; newUser.religion = req.body.religion; newUser.mothertongue = req.body.mothertongue; newUser.dob = req.body.dob; newUser.mobilenumber = req.body.mobilenumber; newUser.aadhar = req.body.aadhar; newUser.address = req.body.address; newUser.district = req.body.district; newUser.state = req.body.state; newUser.pincode = req.body.pincode; newUser.hboardname = req.body.hboardname; newUser.hyear = req.body.hyear; newUser.hpercentage = req.body.hpercentage; newUser.iboardname = req.body.iboardname; newUser.iyear = req.body.iyear; newUser.ipercentage = req.body.ipercentage; newUser.gboardname = req.body.gboardname; newUser.gyear = req.body.gyear; newUser.gpercentage = req.body.gpercentage; newUser.pboardname = req.body.pboardname; newUser.pyear = req.body.pyear; newUser.ppercentage = req.body.ppercentage; newUser.examcenter = req.body.examcenter; // save the user if(req.files){ newUser.photo = req.files.photo[0].path; newUser.signature = req.files.signature[0].path; } newUser.save(function (err) { if (err) throw err; return done(null, newUser, req.flash('signupMessage', 'You are Successfully Registered Please Login to Complete Application.')); }); } }); }); })); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use('local-signin', new LocalStrategy({ usernameField: 'email', passwordField: '<PASSWORD>', passReqToCallback: true }, function (req, email, password, done) { User.findOne({ 'email': email }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, req.flash('loginMessage', 'No user found.')); } if (!user.validPassword(password)) { return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); } return done(null, user); }); })); };
b7f30d45624f82b9a957d49d44b9ad65243b6a52
[ "JavaScript" ]
4
JavaScript
musheer7489/idcl
da8249ae7e9dc8c40f88dee51e15df57353b3df0
b665e86cd1336b01730da6ec9568c6b986c3d03d
refs/heads/master
<file_sep>Добавление дублирующей строки в список, если строка списка содержит букву "o" Если список перебирается в цикле и в него добавляются объекты, то лучше проходиться по списку в обратном порядке <file_sep>/** * Бои двух котов * @author Luminescensse * @version 1.0 */ public class Cat { public String name; public int age; public int weight; public int strength; // конструктор public Cat(String name, int age, int weight, int strength) { this.name = name; if (age > 0 && age < 15) { this.age = age; } else { throw new IllegalArgumentException("the age should be from 1 to 14"); } if (weight > 0 && weight < 7) { this.weight = weight; } else { throw new IllegalArgumentException("the weight should be from 1 to 6"); } if (strength > 0 && strength < 10) { this.strength = strength; } else { throw new IllegalArgumentException("the strength should be from 1 to 9"); } } // бой между двумя котами public boolean fight(Cat anotherCat) { if (anotherCat.age == this.age && anotherCat.strength == this.strength && anotherCat.weight == this.weight) { throw new IllegalArgumentException("At least one parameter must be different"); } if (Math.abs(anotherCat.strength - this.strength) > 1) { // проверка на силу if (anotherCat.strength < this.strength) { return true; } else { return false; } } else if (Math.abs(anotherCat.age - this.age) > 3) { // проверка на возраст if (anotherCat.age > this.age && this.age > 1) { return true; } else { return false; } } else if (Math.abs(anotherCat.weight - this.weight) > 1) { // проверка на вес if (anotherCat.weight > this.weight) { return true; } else { return false; } } else { //if (anotherCat.strength < this.strength || anotherCat.age > this.age || anotherCat.weight > this.weight) { // return true; //} else { // return false; //} int run = (int) (Math.random() * 10); if (run < 6) { return true; } else { return false; } } } public static void main(String[] args) { try { Cat cat1 = new Cat("Vaska", 9, 2, 7); Cat cat2 = new Cat("Murka", 5, 1, 6); System.out.println(cat1.fight(cat2)); System.out.println(cat2.fight(cat1)); } catch (IllegalArgumentException exception) { System.out.println(exception); } } } <file_sep>Битва котов. Метод boolean fight(Cat anotherCat) должен определять, выиграли ли мы (this) бой или нет, т.е. возвращать true, если выиграли и false - если нет. Победа зависит от веса, возраста и силы. И при определенных параметрах - случайным образом. <file_sep>Изучаем Java Учебник для начинающих программистов - http://proglang.su/java Философия Java 4-е издание Wiki-версия - http://wikijava.it-cache.net/ <file_sep>Ввести с клавиатуры число. Определить, сколько в введенном числе четных цифр, а сколько нечетных.<file_sep>import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Удаление повторов и заданных значений из Map * @author junior * @version 1.0 */ public class Solution { public static HashMap<String, String> createMap() { HashMap<String, String> map = new HashMap<>(); map.put("Иванов", "Иван"); map.put("Сидоров", "Петр"); map.put("Никитин", "Саша"); map.put("Петров", "Дима"); map.put("Земин", "Тимур"); map.put("Басыров", "Саша"); map.put("Хомин", "Руслан"); map.put("Лапин", "Федя"); map.put("Митин", "Саша"); map.put("Семин", "Саша"); return map; } // Удаляем из Map повторяющиеся значения public static void removeTheFirstNameDuplicates(HashMap<String, String> map) { HashMap<String, String> mapcopy = new HashMap<>(map); for (HashMap.Entry pair: mapcopy.entrySet()) { if (Collections.frequency(mapcopy.values(), pair.getValue()) > 1) { map.remove(pair.getKey()); } } System.out.println(map); } // удаляем из Map заданное значение public static void removeItemFromMapByValue(HashMap<String, String> map, String value) { HashMap<String, String> copy = new HashMap<String, String>(map); for (Map.Entry<String, String> pair : copy.entrySet()) { if (pair.getValue().equals(value)) map.remove(pair.getKey()); } } public static void main(String[] args) { removeTheFirstNameDuplicates(createMap()); } }<file_sep>удаление повторов и заданных значений из Map
330cf9df22f4c36dff453112a0f759a38b4717c3
[ "Markdown", "Java", "Text" ]
7
Text
Luminescensse/Java
56788b68e776b6ee30158d9ddac01bbb45ad7567
412d6e3a5313d11fcd68cdbb244584a8867f16c0
refs/heads/main
<repo_name>gabebw/save-your-vines<file_sep>/did-it-for-the-vine.sh #!/bin/sh # Usage: # # ./did-it-for-the-vine.sh VINE_USERNAME VINE_PASSWORD # # You can also run it as # # ./did-it-for-the-vine.sh # # and it will prompt for your username/password. # # After entering your username once, it won't ask again. set -eo pipefail set_vine_username_and_password(){ if [ -z "$1" ] || [ -z "$2" ]; then if [ -f .vine-credentials ]; then vine_username=$(head -1 .vine-credentials) vine_password=$(tail -1 .vine-credentials) else read -rp "What is your Vine username? " vine_username read -rp "What is your Vine password? " vine_password fi else vine_username=$1 vine_password=$2 fi } set_vine_username_and_password "$@" echo "$vine_username" > .vine-credentials echo "$vine_password" >> .vine-credentials # likes-vines.rb reads likes.json, so we can't write to it or it'll end up empty # Fun fact: situations like this are exactly why `sponge` exists. It's available # here: https://joeyh.name/code/moreutils/ # I won't use it though, because I want this to work out of the box. if ./liked-vines.rb "$vine_username" "$vine_password" > newlikes.json; then mv newlikes.json likes.json else rm newlikes.json exit 1 fi ./download-and-make-blog-posts.rb likes.json <file_sep>/docs/Gemfile source "https://rubygems.org" ruby RUBY_VERSION gem "jekyll", "3.3.1" # This is the default theme for new Jekyll sites. You may change this to anything you like. gem "minima", "~> 2.0" # If you have any plugins, put them here! group :jekyll_plugins do gem "github-pages" end <file_sep>/download-and-make-blog-posts.rb #!/usr/bin/env ruby require "fileutils" require "json" require "open-uri" require "time" JEKYLL_DIRECTORY = "./docs" VINES_DIRECTORY = "#{JEKYLL_DIRECTORY}/vines" def presence(s, fallback) if s == "" || s.nil? fallback else s end end def normalize_title(title) title.gsub("/", "%2F") end def download_and_make_blog_post(json) vine_id = File.basename(json[:vine_url]) directory = "#{VINES_DIRECTORY}/#{vine_id}" description = presence(json[:description], "[No title]") title = "#{description} by #{json[:username]}" puts "Downloading and creating blog post for #{json[:vine_url]} (#{title})" FileUtils.mkdir_p(directory) created_at = Time.parse(json[:created_at]) filename = "#{directory}/#{vine_id}" mp4_src = "/#{File.basename(VINES_DIRECTORY)}/#{vine_id}/#{vine_id}.mp4" webm_src = "/#{File.basename(VINES_DIRECTORY)}/#{vine_id}/#{vine_id}.webm" year = created_at.strftime("%Y") month = created_at.strftime("%m") day = created_at.strftime("%d") post_filename = "#{JEKYLL_DIRECTORY}/_posts/#{year}-#{month}-#{day}-#{normalize_title(title)}.html" unless File.exist?("#{filename}.mp4") File.open("#{filename}.mp4", "wb") do |mp4_file| open(json[:mp4], "rb") { |f| mp4_file.write(f.read) } end end if json[:webm] unless File.exist?("#{filename}.webm") File.open("#{filename}.webm", "wb") do |webm_file| open(json[:webm], "rb") { |f| webm_file.write(f.read) } end end end File.open(post_filename, "w") do |f| f.write(blog_post_contents(json, title, created_at, mp4_src, webm_src)) end end def blog_post_contents(json, title, created_at, mp4_src, webm_src) <<EOF --- title: > #{title} date: "#{created_at.strftime("%Y-%m-%d %H:%M:%S %z")}" layout: post --- #{video_tag(json, mp4_src, webm_src)} <p><a href="#{json[:vine_url]}">Original Vine</a> by #{json[:username]}</p> EOF end def video_tag(json, mp4_src, webm_src) tag = '<video loop controls autoplay width="540" height="540">' tag += %{\n <source type="video/mp4" src="{{ site.baseurl }}#{mp4_src}" />} if json[:webm] tag += %{\n <source type="video/webm" src="{{ site.baseurl }}#{webm_src}" />} end tag += "\n</video>" tag end JSON.parse(File.read(ARGV[0]), symbolize_names: true).each do |json| begin download_and_make_blog_post(json) rescue Exception => e p json puts e puts e.backtrace vine_id = File.basename(json[:vine_url]) directory = "#{VINES_DIRECTORY}/#{vine_id}" FileUtils.rm_rf(directory) exit 1 end end <file_sep>/README.md # Save Your Liked Vines This script will: * Download all of your favorite Vines (_not_ Vines you've uploaded) * Make a Jekyll blog * Create a Jekyll post for each Vine, with its date set to the Vine's upload date Then you can publish it to GitHub Pages! ## Let's do it First, fork this repo. Then clone it locally and run: ./did-it-for-the-vine.sh It will prompt you for your Vine username and password then download your vines and make a blog post for each one. If you need to stop it or anything goes wrong, you can safely run the script again. It will pick up where it left off. ## After the script finishes 1. You'll probably want to edit `docs/_config.yml` to change your Twitter name, etc. I recommend changing `title`, `email`, `description`, `twitter_username`, and `github_username`. You can totally skip this step though! 1. If you renamed the repo to something other than `save-your-vines`, then change `baseurl` in `docs/_config.yml` to your new repo name, otherwise the links won't work on GitHub. If you didn't rename the repo, skip this step. 1. Commit your changes to Git. 1. Push to GitHub, which will take at least 10 minutes. 1. Visit your repo's settings page and scroll down to the "GitHub Pages" section. Select "master branch /docs folder" as the source and save. ![](https://cloud.githubusercontent.com/assets/257678/21215014/4badb86e-c253-11e6-9ee8-ae7a00b2965d.png) 1. Wait a minute or two then reload the page. In the "GitHub Pages" section you'll see a green message with a link to your new blog. ![](https://cloud.githubusercontent.com/assets/257678/21215388/c86a17ce-c255-11e6-9a46-ef5439d62ee1.png) 1. You're done! ## Adding new lines If you've liked some Vines since you last ran the script, run the script again and it will create posts for only those new Vines: ./did-it-for-the-vine.sh You can run it as often as you want! And best of all, it won't keep asking for your password. <file_sep>/liked-vines.rb #!/usr/bin/env ruby require "json" require "net/https" require "uri" def parse(data) JSON.parse(data, symbolize_names: true) end def POST(url, data) uri = URI.parse(url) response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| request = Net::HTTP::Post.new(uri) request.set_form_data(data) # The default User-Agent for Net::HTTP is "Ruby". That crashes Vine's # server(!) and causes a 500 error. request["User-Agent"] = "Almost anything else" http.request(request) end parse(response.body) end def GET(url, session_id, data={}) uri = URI.parse(url) uri.query = URI.encode_www_form(data) response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| request = Net::HTTP::Get.new(uri) request["User-Agent"] = "Almost anything else" request["vine-session-id"] = session_id http.request(request) end parse(response.body) end def sign_in(username, password) json = POST( "https://api.vineapp.com/users/authenticate", "username" => username, "password" => <PASSWORD>, ) if json[:error] != "" STDERR.puts "Your username or password is wrong; please double-check and run this script again" File.unlink(".vine-credentials") exit 1 end json[:data][:key] end def get_likes(session_id, max_pages, page_number = 1) STDERR.puts "Getting likes (page #{page_number})" url = "https://api.vineapp.com/timelines/users/me/likes" json = GET(url, session_id, page: page_number) likes = json[:data][:records].map do |record| { created_at: record[:created], description: record[:description], mp4: record[:videoUrl], mp4_backup: record[:videoDashUrl], username: record[:username], vine_url: record[:permalinkUrl], webm: record[:videoWebmUrl], } end if json[:data][:nextPage] && page_number < max_pages likes += get_likes(session_id, max_pages, page_number + 1) end likes end vine_username = ARGV[0].chomp vine_password = ARGV[1].chomp session_id = sign_in(vine_username, vine_password) if File.exist?("likes.json") # We're adding new likes, not getting all of them, so just get the first few # pages existing = parse(File.read("likes.json")) new = get_likes(session_id, 5) all_likes = (existing + new).uniq { |json| json[:vine_url] } else all_likes = get_likes(session_id, 1000) end puts JSON.pretty_generate(all_likes)
c4c1ae6515dd80808f9e7c0ac80359731b3fd65c
[ "Markdown", "Ruby", "Shell" ]
5
Shell
gabebw/save-your-vines
485c91a18311d6770992c45f887bb3e77b83e5ed
471fe968c1037f9b90654eb81f66ce216f5fb2aa
refs/heads/master
<file_sep>using System; namespace ConsoleAppSerializeDemo { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); //FileDemo.Serialization(); //FileDemo.Deserialization(); //FileDemo.SerializationPersons(); FileDemo.DesirializationPerson(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ConsoleAppSerializeDemo { [Serializable] public class Person { public string Navn { get; set; } public string Adresse { get; set; } public Person(string navn, string adresse) { this.Navn = navn; this.Adresse = adresse; } public Person() { } public override string ToString() { return $"navn:{Navn} adresse: {Adresse}"; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace ConsoleAppSerializeDemo { public class FileDemo { public static void Serialization() { Person p = new Person("Martin", "Roskilde"); IFormatter formatter = new BinaryFormatter(); Stream stream = null; stream = new FileStream("C:/filedemo/person.bin", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, p); if (stream != null) stream.Close(); } public static void Deserialization() { IFormatter formatter = new BinaryFormatter(); Stream stream = null; stream = new FileStream("C:/filedemo/person.bin", FileMode.Open, FileAccess.Read, FileShare.Read); Person p1 = new Person(); p1 = (Person)formatter.Deserialize(stream); Console.WriteLine(p1.ToString()); if (stream != null) stream.Close(); } public static void SerializationPersons() { Person p1 = new Person("<NAME>", "Andeby"); Person p2 = new Person("Martin", "Roskilde"); Person p3 = new Person("Charlotte", "Vordingborg"); List<Person> personer = new List<Person>(); personer.Add(p1); personer.Add(p2); personer.Add(p3); IFormatter formatter = new BinaryFormatter(); Stream stream = null; stream = new FileStream("C:/filedemo/personliste.bin", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, personer); if (stream != null) stream.Close(); } public static void DesirializationPerson() { IFormatter formatter = new BinaryFormatter(); Stream stream = null; stream = new FileStream("C:/filedemo/personliste.bin", FileMode.Open, FileAccess.Read, FileShare.Read); List<Person> listepersoner = new List<Person>(); listepersoner = (List<Person>)formatter.Deserialize(stream); if (stream != null) stream.Close(); foreach (var person in listepersoner) { Console.WriteLine(person); } } } }
f0ae9c0c0fd09bad9d406ca4ec36bf35dec7357f
[ "C#" ]
3
C#
MartinKierkegaard/ConsoleAppSerializeDemo
15209d7ea9ea2e3037a5f3a226c42e4483cc8967
1b91776581d095a077de3c49662ce4aedc165154
refs/heads/master
<repo_name>akshayysharma/ReactFormValidation<file_sep>/src/App.js import React, { Component } from "react"; import "./App.css"; const initialState = { fname: "", version: "", lname: "", enterDate: "", email: "", password: "", matchPassword: "", fnameError: "", versionError: "" } class App extends Component { state = initialState changeHandler = e => { this.setState({ [e.target.name]: e.target.value }) } submitForm = e => { e.preventDefault(); const showValidation = this.validation(); if (showValidation) { this.setState(initialState) } }; validation = () => { let fnameError = "" let versionError = "" let lnameError = "" let emailError = "" let dateError = "" let time = new Date() let passwordError = "" let matchPasswordError = "" if (!this.state.fname) { //console.log("fname called"); fnameError = "First Name can't be blank" } if (!this.state.version.match(/^(\d+\.)?(\d+\.)?(\*|\d+)$/g)) { //console.log("called"); versionError = "version number not matched" } if (this.state.lname.length < 4) { lnameError = "Last Name should be greater than 4 character"; } if (!this.state.email.includes("@")) { emailError = "invalid email" } let convertedDate = time.getFullYear() + "-" + ("0" + (time.getMonth() + 1)).slice(-2) + "-" + ("0" + (time.getDate() + 1)).slice(-2) if(this.state.enterDate.toString() < convertedDate) dateError = "Date should be upcoming" if (!(this.state.password.match(/[a-z]/g) && this.state.password.match(/[A-Z]/g) && this.state.password.match(/[0-9]/g) && this.state.password.match(/[^a-zA-Z\d]/g) && this.state.password.length >= 8)) passwordError = "Password must contain atleast one digit, one lowercase, oneUppercase and one special character"; if (this.state.matchPassword !== this.state.password) matchPasswordError = "Password does not match" this.setState({ emailError, fnameError, versionError, lnameError, passwordError, dateError, matchPasswordError }) if(emailError || fnameError || versionError || lnameError || passwordError || dateError || matchPasswordError)return false else return true } render() { return ( <div> <form onSubmit={this.submitForm}> <div> <label>First name : </label> <input type="text" name="fname" value={this.state.fname} onChange={this.changeHandler} /> <div className="error">{this.state.fnameError}</div> </div> <br /> <div> <label>Last name : </label> <input type="text" name="lname" value={this.state.lname} onChange={this.changeHandler} /> <div className="error">{this.state.lnameError}</div> </div> <br /> <div> <label>Date : </label> <input type="date" name="enterDate" value={this.state.enterDate} onChange={this.changeHandler} /> <div className="error">{this.state.dateError}</div> </div> <br /> <div> <label>Version : </label> <input type="text" name="version" value={this.state.version} onChange={this.changeHandler} /> <div className="error">{this.state.versionError}</div> </div> <br /> <div> <label>Email : </label> <input type="text" name="email" value={this.state.email} onChange={this.changeHandler} /> <div className="error">{this.state.emailError}</div> </div> <br /> <div> <label>Password : </label> <input type="text" name="password" value={this.state.password} onChange={this.changeHandler} /> <div className="error">{this.state.passwordError}</div> </div> <br /> <div> <label>Match Password : </label> <input type="text" name="matchPassword" value={this.state.matchPassword} onChange={this.changeHandler} /> <div className="error">{this.state.matchPasswordError}</div> </div> <br /> <button>Submit</button> </form> </div> ); } } export default App;
52e4f4f05225d1ea56d66740260923f9ec141528
[ "JavaScript" ]
1
JavaScript
akshayysharma/ReactFormValidation
511ac0a11ecf599fcd9a36177fef69a3db807858
b49bf1a429af83429b918bcd51fdcfd2146ac8b7
refs/heads/master
<file_sep>import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Users to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # Identity extract compartments ############################################ ############################################ # connect to database ############################################ connection = None try: print("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") ############################################ # Getting Emails ############################################ print("Getting Emails...") sql = "select EXTRACTED_EMAIL, LISTAGG(DISPLAY_NAME, ', ') from V_ADBNOTIFICATION where flag = 1 and free_tier = 'False' GROUP BY EXTRACTED_EMAIL" cursor.execute(sql) l_flaggedadbs = cursor.fetchall() l_flaggedadbs_n = [] for c in range(len(l_flaggedadbs)): l_flaggedadbs_n.append(l_flaggedadbs[c][0]) ############################################ # Send Emails ############################################ print("Sending Emails...") for i in range(len(l_flaggedadbs)): cursor.callproc('adb_mails', [l_flaggedadbs[i][0], 'Private ADB', 'Hello ' + str(l_flaggedadbs[i][0].split('.')[0].title()) + ',\n\nYour private compartment has been flagged, because you still have an existing ADB. Please delete your ADBs and use the SharedADBs in the SharedPaas compartment. If your ADBs are absolutely needed, please talk to your regional admin or manager and make sure that no tag with AutoStopStart.AutoStopping: NO exists so that the autostop script applies. \n\nADBs: '+ str(l_flaggedadbs[i][1]) + '\n\n Sincerly, the admins.']) cursor.callproc('pushed') cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # print completed ############################################ print("\nCompleted at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) ########################################################################## # Execute Main Process ########################################################################## main_process()<file_sep>#!/usr/bin/env python3 ########################################################################## # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. # # usage2adw.py # # @author: <NAME> # # Supports Python 3 and above # # coding: utf-8 ########################################################################## # OCI Usage to ADWC: # # Required OCI user part of UsageDownloadGroup with below permission: # define tenancy usage-report as ocid1.tenancy.oc1..aaaaaaaaned4fkpkisbwjlr56u7cj63lf3wffbilvqknstgtvzub7vhqkggq # endorse group UsageDownloadGroup to read objects in tenancy usage-report # Allow group UsageDownloadGroup to inspect compartments in tenancy # Allow group UsageDownloadGroup to inspect tenancies in tenancy # # config file should contain: # [TENANT_NAME] # user = user_ocid # fingerprint = fingerprint of the api ssh key # key_file = the path to the private key # tenancy = tenancy ocid # region = region # ########################################################################## # Database user: # create user usage identified by PaSsw0rd2#_#; # grant connect, resource, dwrole, unlimited tablespace to usage; ########################################################################## # # Modules Included: # - oci.object_storage.ObjectStorageClient # - oci.identity.IdentityClient # # APIs Used: # - IdentityClient.list_compartments - Policy COMPARTMENT_INSPECT # - IdentityClient.get_tenancy - Policy TENANCY_INSPECT # - IdentityClient.list_region_subscriptions - Policy TENANCY_INSPECT # - ObjectStorageClient.list_objects - Policy OBJECT_INSPECT # - ObjectStorageClient.get_object - Policy OBJECT_READ # # Meter API for Public Rate: # - https://itra.oraclecloud.com/itas/.anon/myservices/api/v1/products?partNumber=XX # ########################################################################## # Tables used: # - OCI_USAGE - Raw data of the usage reports # - OCI_USAGE_STATS - Summary Stats of the Usage Report for quick query if only filtered by tenant and date # - OCI_USAGE_TAG_KEYS - Tag keys of the usage reports # - OCI_COST - Raw data of the cost reports # - OCI_COST_STATS - Summary Stats of the Cost Report for quick query if only filtered by tenant and date # - OCI_COST_TAG_KEYS - Tag keys of the cost reports # - OCI_COST_REFERENCE - Reference table of the cost filter keys - SERVICE, REGION, COMPARTMENT, PRODUCT, SUBSCRIPTION # - OCI_PRICE_LIST - Hold the price list and the cost per product ########################################################################## import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle import requests import logging filename = '/home/opc/oci_usage/logs/logfile_usage2adw_' + str(datetime.datetime.utcnow()) logging.basicConfig(level=logging.DEBUG, filename=filename, filemode="a+", format="%(asctime)-15s %(levelname)-8s %(message)s") version = "20.05.18" usage_report_namespace = "bling" work_report_dir = os.curdir + "/work_report_dir" os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") # create the work dir if not exist if not os.path.exists(work_report_dir): os.mkdir(work_report_dir) ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Get Column from Array ########################################################################## def get_column_value_from_array(column, array): if column in array: return array[column] else: return "" ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # Load compartments ########################################################################## def identity_read_compartments(identity, tenancy): compartments = [] print("Loading Compartments...") logging.info("Loading Compartments...") try: # read all compartments to variable all_compartments = [] try: all_compartments = oci.pagination.list_call_get_all_results( identity.list_compartments, tenancy.id, compartment_id_in_subtree=True ).data except oci.exceptions.ServiceError: raise ################################################### # Build Compartments - return nested compartment list ################################################### def build_compartments_nested(identity_client, cid, path): try: compartment_list = [item for item in all_compartments if str(item.compartment_id) == str(cid)] if path != "": path = path + " / " for c in compartment_list: if c.lifecycle_state == oci.identity.models.Compartment.LIFECYCLE_STATE_ACTIVE: cvalue = {'id': str(c.id), 'name': str(c.name), 'path': path + str(c.name)} compartments.append(cvalue) build_compartments_nested(identity_client, c.id, cvalue['path']) except Exception as error: raise Exception("Error in build_compartments_nested: " + str(error.args)) ################################################### # Add root compartment ################################################### value = {'id': str(tenancy.id), 'name': str(tenancy.name) + " (root)", 'path': "/ " + str(tenancy.name) + " (root)"} compartments.append(value) # Build the compartments build_compartments_nested(identity, str(tenancy.id), "") # sort the compartment sorted_compartments = sorted(compartments, key=lambda k: k['path']) print(" Total " + str(len(sorted_compartments)) + " compartments loaded.") logging.info(" Total " + str(len(sorted_compartments)) + " compartments loaded.") return sorted_compartments except oci.exceptions.RequestException: raise except Exception as e: raise Exception("Error in identity_read_compartments: " + str(e.args)) ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') parser.add_argument('--version', action='version', version='%(prog)s ' + version) result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # Check Table Structure for usage ########################################################################## def check_database_table_structure_usage(connection): try: # open cursor cursor = connection.cursor() # check if OCI_USAGE table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_USAGE'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_USAGE was not exist, creating") logging.info(" Table OCI_USAGE was not exist, creating") sql = "create table OCI_USAGE (" sql += " TENANT_NAME VARCHAR2(100)," sql += " FILE_ID VARCHAR2(30)," sql += " USAGE_INTERVAL_START DATE," sql += " USAGE_INTERVAL_END DATE," sql += " PRD_SERVICE VARCHAR2(100)," sql += " PRD_RESOURCE VARCHAR2(100)," sql += " PRD_COMPARTMENT_ID VARCHAR2(100)," sql += " PRD_COMPARTMENT_NAME VARCHAR2(100)," sql += " PRD_COMPARTMENT_PATH VARCHAR2(1000)," sql += " PRD_REGION VARCHAR2(100)," sql += " PRD_AVAILABILITY_DOMAIN VARCHAR2(100)," sql += " USG_RESOURCE_ID VARCHAR2(1000)," sql += " USG_BILLED_QUANTITY NUMBER," sql += " USG_CONSUMED_QUANTITY NUMBER," sql += " USG_CONSUMED_UNITS VARCHAR2(100)," sql += " USG_CONSUMED_MEASURE VARCHAR2(100)," sql += " IS_CORRECTION VARCHAR2(10)," sql += " TAGS_DATA VARCHAR2(4000)" sql += ") COMPRESS" cursor.execute(sql) print(" Table OCI_USAGE created") else: print(" Table OCI_USAGE exist") logging.info(" Table OCI_USAGE exist") # check if TAGS_DATA columns exist in OCI_USAGE table, if not create sql = "select count(*) from user_tab_columns where table_name = 'OCI_USAGE' and column_name='TAGS_DATA'" cursor.execute(sql) val, = cursor.fetchone() # if columns not exist, create them if val == 0: print(" Column TAGS_DATA does not exist in the table OCI_USAGE, adding...") sql = "alter table OCI_USAGE add (TAGS_DATA VARCHAR2(4000))" cursor.execute(sql) # check if OCI_USAGE_TAG_KEYS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_USAGE_TAG_KEYS'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_USAGE_TAG_KEYS was not exist, creating") sql = "CREATE TABLE OCI_USAGE_TAG_KEYS (TENANT_NAME VARCHAR2(100), TAG_KEY VARCHAR2(100), " sql += "CONSTRAINT OCI_USAGE_TAG_KEYS_PK PRIMARY KEY(TENANT_NAME,TAG_KEY)" sql += ")" cursor.execute(sql) print(" Table OCI_USAGE_TAG_KEYS created") else: print(" Table OCI_USAGE_TAG_KEYS exist") # check if OCI_USAGE_STATS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_USAGE_STATS'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_USAGE_STATS was not exist, creating") sql = "CREATE TABLE OCI_USAGE_STATS ( " sql += " TENANT_NAME VARCHAR2(100)," sql += " FILE_ID VARCHAR2(30)," sql += " USAGE_INTERVAL_START DATE," sql += " NUM_ROWS NUMBER," sql += " UPDATE_DATE DATE," sql += " AGENT_VERSION VARCHAR2(30)," sql += " CONSTRAINT OCI_USAGE_STATS_PK PRIMARY KEY (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START)" sql += ")" cursor.execute(sql) print(" Table OCI_USAGE_STATS created") update_usage_stats(connection) else: print(" Table OCI_USAGE_STATS exist") logging.info(" Table OCI_USAGE_STATS exist") # close cursor cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_structure_usage() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_structure_usage() - " + str(e)) ########################################################################## # Check Index Structure Usage to be created after the first load ########################################################################## def check_database_index_structure_usage(connection): try: # open cursor cursor = connection.cursor() # check if index OCI_USAGE_1IX exist in OCI_USAGE table, if not create sql = "select count(*) from user_indexes where table_name = 'OCI_USAGE' and index_name='OCI_USAGE_1IX'" cursor.execute(sql) val, = cursor.fetchone() # if index not exist, create it if val == 0: print("\nChecking Index for OCI_USAGE") print(" Index OCI_USAGE_1IX does not exist for table OCI_USAGE, adding...") sql = "CREATE INDEX OCI_USAGE_1IX ON OCI_USAGE(TENANT_NAME,USAGE_INTERVAL_START)" cursor.execute(sql) print(" Index created.") # close cursor cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_index_structure_usage() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_index_structure_usage() - " + str(e)) ########################################################################## # Check Index Structure Usage to be created after the first load ########################################################################## def check_database_index_structure_cost(connection): try: # open cursor cursor = connection.cursor() # check if index OCI_USAGE_1IX exist in OCI_USAGE table, if not create sql = "select count(*) from user_indexes where table_name = 'OCI_COST' and index_name='OCI_COST_1IX'" cursor.execute(sql) val, = cursor.fetchone() # if index not exist, create it if val == 0: print("\nChecking Index for OCI_COST") print(" Index OCI_COST_1IX does not exist for table OCI_COST, adding...") sql = "CREATE INDEX OCI_COST_1IX ON OCI_COST(TENANT_NAME,USAGE_INTERVAL_START)" cursor.execute(sql) print(" Index created.") # close cursor cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_index_structure_cost() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_index_structure_cost() - " + str(e)) ########################################################################## # update_cost_stats ########################################################################## def update_cost_stats(connection): try: # open cursor cursor = connection.cursor() print("\nMerging statistics into OCI_COST_STATS...") logging.info("Merging statistics into OCI_COST_STATS...") # run merge to oci_update_stats sql = "merge into OCI_COST_STATS a " sql += "using " sql += "( " sql += " select " sql += " tenant_name, " sql += " file_id, " sql += " USAGE_INTERVAL_START, " sql += " sum(COST_MY_COST) COST_MY_COST, " sql += " sum(COST_MY_COST_OVERAGE) COST_MY_COST_OVERAGE, " sql += " min(COST_CURRENCY_CODE) COST_CURRENCY_CODE, " sql += " count(*) NUM_ROWS " sql += " from " sql += " oci_cost " sql += " group by " sql += " tenant_name, " sql += " file_id, " sql += " USAGE_INTERVAL_START " sql += ") b " sql += "on (a.tenant_name=b.tenant_name and a.file_id=b.file_id and a.USAGE_INTERVAL_START=b.USAGE_INTERVAL_START) " sql += "when matched then update set a.num_rows=b.num_rows, a.COST_MY_COST=b.COST_MY_COST, a.UPDATE_DATE=sysdate, a.AGENT_VERSION=:version," sql += " a.COST_MY_COST_OVERAGE=b.COST_MY_COST_OVERAGE, a.COST_CURRENCY_CODE=b.COST_CURRENCY_CODE " sql += "where a.num_rows <> b.num_rows " sql += "when not matched then insert (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START,NUM_ROWS,COST_MY_COST,UPDATE_DATE,AGENT_VERSION,COST_MY_COST_OVERAGE,COST_CURRENCY_CODE) " sql += " values (b.TENANT_NAME,b.FILE_ID,b.USAGE_INTERVAL_START,b.NUM_ROWS,b.COST_MY_COST,sysdate,:version,b.COST_MY_COST_OVERAGE,b.COST_CURRENCY_CODE) " cursor.execute(sql, {"version": version}) connection.commit() print(" Merge Completed, " + str(cursor.rowcount) + " rows merged") logging.info(" Merge Completed, " + str(cursor.rowcount) + " rows merged") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at update_cost_stats() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at update_cost_stats() - " + str(e)) ########################################################################## # update_price_list ########################################################################## def update_price_list(connection): try: # open cursor cursor = connection.cursor() print("\nMerging statistics into OCI_PRICE_LIST...") logging.info("Merging statistics into OCI_PRICE_LIST...") # run merge to oci_update_stats sql = "MERGE INTO OCI_PRICE_LIST A " sql += "USING " sql += "( " sql += " SELECT " sql += " TENANT_NAME, " sql += " COST_PRODUCT_SKU, " sql += " PRD_DESCRIPTION, " sql += " COST_CURRENCY_CODE, " sql += " COST_UNIT_PRICE " sql += " FROM " sql += " ( " sql += " SELECT " sql += " TENANT_NAME, " sql += " COST_PRODUCT_SKU, " sql += " PRD_DESCRIPTION, " sql += " COST_CURRENCY_CODE, " sql += " COST_UNIT_PRICE, " sql += " ROW_NUMBER() OVER (PARTITION BY TENANT_NAME, COST_PRODUCT_SKU ORDER BY USAGE_INTERVAL_START DESC, COST_UNIT_PRICE DESC) RN " sql += " FROM OCI_COST A " sql += " ) " sql += " WHERE RN = 1 " sql += " ORDER BY 1,2 " sql += ") B " sql += "ON (A.TENANT_NAME = B.TENANT_NAME AND A.COST_PRODUCT_SKU = B.COST_PRODUCT_SKU) " sql += "WHEN MATCHED THEN UPDATE SET A.PRD_DESCRIPTION=B.PRD_DESCRIPTION, A.COST_CURRENCY_CODE=B.COST_CURRENCY_CODE, A.COST_UNIT_PRICE=B.COST_UNIT_PRICE, COST_LAST_UPDATE = SYSDATE " sql += "WHEN NOT MATCHED THEN INSERT (TENANT_NAME,COST_PRODUCT_SKU,PRD_DESCRIPTION,COST_CURRENCY_CODE,COST_UNIT_PRICE,COST_LAST_UPDATE) " sql += " VALUES (B.TENANT_NAME,B.COST_PRODUCT_SKU,B.PRD_DESCRIPTION,B.COST_CURRENCY_CODE,B.COST_UNIT_PRICE,SYSDATE)" cursor.execute(sql) connection.commit() print(" Merge Completed, " + str(cursor.rowcount) + " rows merged") logging.info(" Merge Completed, " + str(cursor.rowcount) + " rows merged") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at update_price_list() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at update_price_list() - " + str(e)) ########################################################################## # update_cost_reference ########################################################################## def update_cost_reference(connection): try: # open cursor cursor = connection.cursor() print("\nMerging statistics into OCI_COST_REFERENCE...") logging.info("Merging statistics into OCI_COST_REFERENCE...") # run merge to oci_update_stats sql = "merge into OCI_COST_REFERENCE a " sql += "using " sql += "( " sql += " select TENANT_NAME, REF_TYPE, REF_NAME " sql += " from " sql += " ( " sql += " select distinct TENANT_NAME, 'PRD_SERVICE' as REF_TYPE, PRD_SERVICE as REF_NAME from OCI_COST " sql += " union all " sql += " select distinct TENANT_NAME, 'PRD_COMPARTMENT_PATH' as REF_TYPE, " sql += " case when prd_compartment_path like '%/%' then substr(prd_compartment_path,1,instr(prd_compartment_path,' /')-1) " sql += " else prd_compartment_path end as REF_NAME " sql += " from OCI_COST " sql += " union all " sql += " select distinct TENANT_NAME, 'PRD_COMPARTMENT_NAME' as REF_TYPE, PRD_COMPARTMENT_NAME as ref_name from OCI_COST " sql += " union all " sql += " select distinct TENANT_NAME, 'PRD_REGION' as REF_TYPE, PRD_REGION as ref_name from OCI_COST " sql += " union all " sql += " select distinct TENANT_NAME, 'COST_SUBSCRIPTION_ID' as REF_TYPE, to_char(COST_SUBSCRIPTION_ID) as ref_name from OCI_COST " sql += " union all " sql += " select distinct TENANT_NAME, 'COST_PRODUCT_SKU' as REF_TYPE, COST_PRODUCT_SKU || ' '||min(PRD_DESCRIPTION) as ref_name from OCI_COST " sql += " group by TENANT_NAME, COST_PRODUCT_SKU " sql += " ) where ref_name is not null " sql += ") b " sql += "on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE and a.REF_NAME=b.REF_NAME) " sql += "when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME) " sql += "values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)" cursor.execute(sql) connection.commit() print(" Merge Completed, " + str(cursor.rowcount) + " rows merged") logging.info(" Merge Completed, " + str(cursor.rowcount) + " rows merged") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at update_cost_reference() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at update_cost_reference() - " + str(e)) ########################################################################## # update_public_rates ########################################################################## def update_public_rates(connection, tenant_name): try: # open cursor num_rows = 0 cursor = connection.cursor() api_url = "https://itra.oraclecloud.com/itas/.anon/myservices/api/v1/products?partNumber=" print("\nMerging Public Rates into OCI_RATE_CARD...") logging.info("Merging Public Rates into OCI_RATE_CARD...") # retrieve the SKUS to query sql = "select COST_PRODUCT_SKU, COST_CURRENCY_CODE from OCI_PRICE_LIST where tenant_name=:tenant_name" cursor.execute(sql, {"tenant_name": tenant_name}) rows = cursor.fetchall() if rows: for row in rows: rate_description = "" rate_paygo_price = None rate_monthly_flex_price = None # Call API to fetch the data cost_produdt_sku = str(row[0]) country_code = str(row[1]) resp = requests.get(api_url + cost_produdt_sku, headers={'X-Oracle-Accept-CurrencyCode': country_code}) if not resp: continue for item in resp.json()['items']: rate_description = item["displayName"] for price in item['prices']: if price['model'] == 'PAY_AS_YOU_GO': rate_paygo_price = price['value'] elif price['model'] == 'MONTHLY_COMMIT': rate_monthly_flex_price = price['value'] # update database sql = "update OCI_PRICE_LIST set " sql += "RATE_DESCRIPTION=:rate_description, " sql += "RATE_PAYGO_PRICE=:rate_paygo, " sql += "RATE_MONTHLY_FLEX_PRICE=:rate_monthly, " sql += "RATE_UPDATE_DATE=sysdate " sql += "where TENANT_NAME=:tenant_name and COST_PRODUCT_SKU=:cost_produdt_sku " sql_variables = { "rate_description": rate_description, "rate_paygo": rate_paygo_price, "rate_monthly": rate_monthly_flex_price, "tenant_name": tenant_name, "cost_produdt_sku": cost_produdt_sku } cursor.execute(sql, sql_variables) num_rows += 1 # Commit connection.commit() print(" Update Completed, " + str(num_rows) + " rows updated.") logging.info(" Update Completed, " + str(num_rows) + " rows updated.") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at update_public_rates() - " + str(e) + "\n") raise SystemExit except requests.exceptions.ConnectionError as e: print("\nError connecting to billing metering API at update_public_rates() - " + str(e)) except Exception as e: raise Exception("\nError manipulating database at update_public_rates() - " + str(e)) ########################################################################## # update_usage_stats ########################################################################## def update_usage_stats(connection): try: # open cursor cursor = connection.cursor() print("\nMerging statistics into OCI_USAGE_STATS...") logging.info("\nMerging statistics into OCI_USAGE_STATS...") # run merge to oci_update_stats sql = "merge into OCI_USAGE_STATS a " sql += "using " sql += "( " sql += " select " sql += " tenant_name, " sql += " file_id, " sql += " USAGE_INTERVAL_START, " sql += " count(*) NUM_ROWS " sql += " from " sql += " oci_usage " sql += " group by " sql += " tenant_name, " sql += " file_id, " sql += " USAGE_INTERVAL_START " sql += ") b " sql += "on (a.tenant_name=b.tenant_name and a.file_id=b.file_id and a.USAGE_INTERVAL_START=b.USAGE_INTERVAL_START) " sql += "when matched then update set a.num_rows=b.num_rows, a.UPDATE_DATE=sysdate, a.AGENT_VERSION=:version " sql += "where a.num_rows <> b.num_rows " sql += "when not matched then insert (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START,NUM_ROWS,UPDATE_DATE,AGENT_VERSION) " sql += " values (b.TENANT_NAME,b.FILE_ID,b.USAGE_INTERVAL_START,b.NUM_ROWS,sysdate,:version) " cursor.execute(sql, {"version": version}) connection.commit() print(" Merge Completed, " + str(cursor.rowcount) + " rows merged") logging.info(" Merge Completed, " + str(cursor.rowcount) + " rows merged") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at update_usage_stats() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at update_usage_stats() - " + str(e)) ########################################################################## # Check Table Structure Cost ########################################################################## def check_database_table_structure_cost(connection): try: # open cursor cursor = connection.cursor() # check if OCI_COST table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_COST'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_COST was not exist, creating") sql = "create table OCI_COST (" sql += " TENANT_NAME VARCHAR2(100)," sql += " FILE_ID VARCHAR2(30)," sql += " USAGE_INTERVAL_START DATE," sql += " USAGE_INTERVAL_END DATE," sql += " PRD_SERVICE VARCHAR2(100)," sql += " PRD_RESOURCE VARCHAR2(100)," sql += " PRD_COMPARTMENT_ID VARCHAR2(100)," sql += " PRD_COMPARTMENT_NAME VARCHAR2(100)," sql += " PRD_COMPARTMENT_PATH VARCHAR2(1000)," sql += " PRD_REGION VARCHAR2(100)," sql += " PRD_AVAILABILITY_DOMAIN VARCHAR2(100)," sql += " USG_RESOURCE_ID VARCHAR2(1000)," sql += " USG_BILLED_QUANTITY NUMBER," sql += " USG_BILLED_QUANTITY_OVERAGE NUMBER," sql += " COST_SUBSCRIPTION_ID NUMBER," sql += " COST_PRODUCT_SKU VARCHAR2(10)," sql += " PRD_DESCRIPTION VARCHAR2(1000)," sql += " COST_UNIT_PRICE NUMBER," sql += " COST_UNIT_PRICE_OVERAGE NUMBER," sql += " COST_MY_COST NUMBER," sql += " COST_MY_COST_OVERAGE NUMBER," sql += " COST_CURRENCY_CODE VARCHAR2(10)," sql += " COST_BILLING_UNIT VARCHAR2(1000)," sql += " COST_OVERAGE_FLAG VARCHAR2(10)," sql += " IS_CORRECTION VARCHAR2(10)," sql += " TAGS_DATA VARCHAR2(4000)" sql += ") COMPRESS" cursor.execute(sql) print(" Table OCI_COST created") else: print(" Table OCI_COST exist") logging.info(" Table OCI_COST exist") # check if OCI_COST_TAG_KEYS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_COST_TAG_KEYS'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_COST_TAG_KEYS was not exist, creating") sql = "CREATE TABLE OCI_COST_TAG_KEYS (TENANT_NAME VARCHAR2(100), TAG_KEY VARCHAR2(100), " sql += "CONSTRAINT OCI_COST_TAG_KEYS_PK PRIMARY KEY(TENANT_NAME,TAG_KEY)" sql += ")" cursor.execute(sql) print(" Table OCI_COST_TAG_KEYS created") else: print(" Table OCI_COST_TAG_KEYS exist") logging.info(" Table OCI_COST_TAG_KEYS exist") # check if OCI_COST_STATS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_COST_STATS'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_COST_STATS was not exist, creating") logging.info(" Table OCI_COST_STATS was not exist, creating") sql = "CREATE TABLE OCI_COST_STATS ( " sql += " TENANT_NAME VARCHAR2(100)," sql += " FILE_ID VARCHAR2(30)," sql += " USAGE_INTERVAL_START DATE," sql += " NUM_ROWS NUMBER," sql += " COST_MY_COST NUMBER," sql += " COST_MY_COST_OVERAGE NUMBER," sql += " COST_CURRENCY_CODE VARCHAR2(30)," sql += " UPDATE_DATE DATE," sql += " AGENT_VERSION VARCHAR2(30)," sql += " CONSTRAINT OCI_COST_STATS_PK PRIMARY KEY (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START)" sql += ")" cursor.execute(sql) print(" Table OCI_COST_STATS created") update_cost_stats(connection) else: print(" Table OCI_COST_STATS exist") logging.info(" Table OCI_COST_STATS exist") # check if COST_MY_COST_OVERAGE columns exist in OCI_COST_STATS table, if not create sql = "select count(*) from user_tab_columns where table_name = 'OCI_COST_STATS' and column_name='COST_MY_COST_OVERAGE'" cursor.execute(sql) val, = cursor.fetchone() # if columns not exist, create them if val == 0: print(" Column COST_MY_COST_OVERAGE does not exist in the table OCI_COST_STATS, adding...") sql = "alter table OCI_COST_STATS add (COST_MY_COST_OVERAGE NUMBER, COST_CURRENCY_CODE VARCHAR2(10))" cursor.execute(sql) update_cost_stats(connection) # check if OCI_COST_REFERENCE table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_COST_REFERENCE'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_COST_REFERENCE was not exist, creating") sql = "CREATE TABLE OCI_COST_REFERENCE (" sql += " TENANT_NAME VARCHAR2(100)," sql += " REF_TYPE VARCHAR2(100)," sql += " REF_NAME VARCHAR2(1000)," sql += " CONSTRAINT OCI_REFERENCE_PK PRIMARY KEY (TENANT_NAME,REF_TYPE,REF_NAME) " sql += ") " cursor.execute(sql) print(" Table OCI_COST_REFERENCE created") update_cost_reference(connection) else: print(" Table OCI_COST_REFERENCE exist") logging.info(" Table OCI_COST_REFERENCE exist") # close cursor cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_structure_cost() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_structure_cost() - " + str(e)) ########################################################################## # Check Table Structure Price List ########################################################################## def check_database_table_structure_price_list(connection, tenant_name): try: # open cursor cursor = connection.cursor() # check if OCI_PRICE_LIST table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_PRICE_LIST'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print(" Table OCI_PRICE_LIST was not exist, creating") sql = "create table OCI_PRICE_LIST (" sql += " TENANT_NAME VARCHAR2(100)," sql += " COST_PRODUCT_SKU VARCHAR2(10)," sql += " PRD_DESCRIPTION VARCHAR2(1000)," sql += " COST_CURRENCY_CODE VARCHAR2(10)," sql += " COST_UNIT_PRICE NUMBER," sql += " COST_LAST_UPDATE DATE," sql += " RATE_DESCRIPTION VARCHAR2(1000)," sql += " RATE_PAYGO_PRICE NUMBER," sql += " RATE_MONTHLY_FLEX_PRICE NUMBER," sql += " RATE_UPDATE_DATE DATE," sql += " CONSTRAINT OCI_PRICE_LIST_PK PRIMARY KEY (TENANT_NAME,COST_PRODUCT_SKU) " sql += ") " cursor.execute(sql) print(" Table OCI_PRICE_LIST created") update_price_list(connection) update_public_rates(connection, tenant_name) else: print(" Table OCI_PRICE_LIST exist") logging.info(" Table OCI_PRICE_LIST exist") cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_price_list() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_price_list() - " + str(e)) ######################################################################### # Load Cost File ########################################################################## def load_cost_file(connection, object_storage, object_file, max_file_id, cmd, tenancy, compartments): num = 0 try: o = object_file # keep tag keys per file tags_keys = [] # get file name filename = o.name.rsplit('/', 1)[-1] file_id = filename[:-7] file_time = str(o.time_created)[0:16] # if file already loaded, skip (check if < max_file_id if str(max_file_id) != "None": if file_id <= str(max_file_id): return num # if file id enabled, check if cmd.fileid: if file_id != cmd.fileid: return num # check file date if cmd.filedate: if file_time <= cmd.filedate: return num path_filename = work_report_dir + '/' + filename print(" Processing file " + o.name + " - " + str(o.size) + " bytes, " + file_time) logging.info(" Processing file " + o.name + " - " + str(o.size) + " bytes, " + file_time) # download file object_details = object_storage.get_object(usage_report_namespace, str(tenancy.id), o.name) with open(path_filename, 'wb') as f: for chunk in object_details.data.raw.stream(1024 * 1024, decode_content=False): f.write(chunk) # Read file to variable with gzip.open(path_filename, 'rt') as file_in: csv_reader = csv.DictReader(file_in) data = [] for row in csv_reader: # find compartment path compartment_path = "" for c in compartments: if c['id'] == row['product/compartmentId']: compartment_path = c['path'] # Handle Tags up to 4000 chars with # seperator tags_data = "" for (key, value) in row.items(): if 'tags' in key and len(value) > 0: # remove # and = from the tags keys and value keyadj = str(key).replace("tags/", "").replace("#", "").replace("=", "") valueadj = str(value).replace("#", "").replace("=", "") # check if length < 4000 to avoid overflow database column if len(tags_data) + len(keyadj) + len(valueadj) + 2 < 4000: tags_data += ("#" if tags_data == "" else "") + keyadj + "=" + valueadj + "#" # add tag key to tag_keys array if keyadj not in tags_keys: tags_keys.append(keyadj) # Assign each column to variable to avoid error if column missing from the file lineItem_intervalUsageStart = get_column_value_from_array('lineItem/intervalUsageStart', row) lineItem_intervalUsageEnd = get_column_value_from_array('lineItem/intervalUsageEnd', row) product_service = get_column_value_from_array('product/service', row) product_compartmentId = get_column_value_from_array('product/compartmentId', row) product_compartmentName = get_column_value_from_array('product/compartmentName', row) product_region = get_column_value_from_array('product/region', row) product_availabilityDomain = get_column_value_from_array('product/availabilityDomain', row) product_resourceId = get_column_value_from_array('product/resourceId', row) usage_billedQuantity = get_column_value_from_array('usage/billedQuantity', row) usage_billedQuantityOverage = get_column_value_from_array('usage/billedQuantityOverage', row) cost_subscriptionId = get_column_value_from_array('cost/subscriptionId', row) cost_productSku = get_column_value_from_array('cost/productSku', row) product_Description = get_column_value_from_array('product/Description', row) cost_unitPrice = get_column_value_from_array('cost/unitPrice', row) cost_unitPriceOverage = get_column_value_from_array('cost/unitPriceOverage', row) cost_myCost = get_column_value_from_array('cost/myCost', row) cost_myCostOverage = get_column_value_from_array('cost/myCostOverage', row) cost_currencyCode = get_column_value_from_array('cost/currencyCode', row) cost_billingUnitReadable = get_column_value_from_array('cost/billingUnitReadable', row) cost_overageFlag = get_column_value_from_array('cost/overageFlag', row) lineItem_isCorrection = get_column_value_from_array('lineItem/isCorrection', row) # Fix OCI Data for missing product description if cost_productSku == "B88285" and product_Description == "": product_Description = "Object Storage Classic" cost_billingUnitReadable = "Gigabyte Storage Capacity per Month" elif cost_productSku == "B88272" and product_Description == "": product_Description = "Compute Classic - Unassociated Static IP" cost_billingUnitReadable = "IPs" elif cost_productSku == "B88166" and product_Description == "": product_Description = "Oracle Identity Cloud - Standard" cost_billingUnitReadable = "Active User per Hour" elif cost_productSku == "B88167" and product_Description == "": product_Description = "Oracle Identity Cloud - Basic" cost_billingUnitReadable = "Active User per Hour" elif cost_productSku == "B88168" and product_Description == "": product_Description = "Oracle Identity Cloud - Basic - Consumer User" cost_billingUnitReadable = "Active User per Hour" elif cost_productSku == "B88274" and product_Description == "": product_Description = "Block Storage Classic" cost_billingUnitReadable = "Gigabyte Storage Capacity per Month" elif cost_productSku == "B89164" and product_Description == "": product_Description = "Oracle Security Monitoring and Compliance Edition" cost_billingUnitReadable = "100 Entities Per Hour" elif cost_productSku == "B88269" and product_Description == "": product_Description = "Compute Classic" cost_billingUnitReadable = "OCPU Per Hour " elif cost_productSku == "B88269" and product_Description == "": product_Description = "Compute Classic" cost_billingUnitReadable = "OCPU Per Hour" elif cost_productSku == "B88275" and product_Description == "": product_Description = "Block Storage Classic - High I/O" cost_billingUnitReadable = "Gigabyte Storage Per Month" elif cost_productSku == "B88283" and product_Description == "": product_Description = "Object Storage Classic - GET and all other Requests" cost_billingUnitReadable = "10,000 Requests Per Month" elif cost_productSku == "B88284" and product_Description == "": product_Description = "Object Storage Classic - PUT, COPY, POST or LIST Requests" cost_billingUnitReadable = "10,000 Requests Per Month" # create array row_data = ( str(tenancy.name), file_id, lineItem_intervalUsageStart[0:10] + " " + lineItem_intervalUsageStart[11:16], lineItem_intervalUsageEnd[0:10] + " " + lineItem_intervalUsageEnd[11:16], product_service, product_compartmentId, product_compartmentName, compartment_path, product_region, product_availabilityDomain, product_resourceId, usage_billedQuantity, usage_billedQuantityOverage, cost_subscriptionId, cost_productSku, product_Description, cost_unitPrice, cost_unitPriceOverage, cost_myCost, cost_myCostOverage, cost_currencyCode, cost_billingUnitReadable, cost_overageFlag, lineItem_isCorrection, tags_data ) data.append(row_data) # insert bulk to database cursor = cx_Oracle.Cursor(connection) sql = "INSERT INTO OCI_COST (" sql += "TENANT_NAME," sql += "FILE_ID," sql += "USAGE_INTERVAL_START, " sql += "USAGE_INTERVAL_END, " sql += "PRD_SERVICE, " # 6 sql += "PRD_COMPARTMENT_ID, " sql += "PRD_COMPARTMENT_NAME, " sql += "PRD_COMPARTMENT_PATH, " sql += "PRD_REGION, " sql += "PRD_AVAILABILITY_DOMAIN, " # 11 sql += "USG_RESOURCE_ID, " sql += "USG_BILLED_QUANTITY, " sql += "USG_BILLED_QUANTITY_OVERAGE, " sql += "COST_SUBSCRIPTION_ID, " sql += "COST_PRODUCT_SKU, " # 16 sql += "PRD_DESCRIPTION, " sql += "COST_UNIT_PRICE, " sql += "COST_UNIT_PRICE_OVERAGE, " sql += "COST_MY_COST, " sql += "COST_MY_COST_OVERAGE, " # 21 sql += "COST_CURRENCY_CODE, " sql += "COST_BILLING_UNIT, " sql += "COST_OVERAGE_FLAG," sql += "IS_CORRECTION, " sql += "TAGS_DATA " sql += ") VALUES (" sql += ":1, :2, to_date(:3,'YYYY-MM-DD HH24:MI'), to_date(:4,'YYYY-MM-DD HH24:MI'), :5, " sql += ":6, :7, :8, :9, :10, " sql += ":11, to_number(:12), to_number(:13) ,:14, :15, " sql += ":16, to_number(:17), to_number(:18), to_number(:19), to_number(:20), " sql += ":21, :22, :23, :24, :25" sql += ") " cursor.prepare(sql) cursor.executemany(None, data) connection.commit() cursor.close() print(" Completed file " + o.name + " - " + str(len(data)) + " Rows Inserted") logging.info(" Completed file " + o.name + " - " + str(len(data)) + " Rows Inserted") num += 1 # remove file os.remove(path_filename) ####################################### # insert bulk tags to the database ####################################### data = [] for tag in tags_keys: row_data = (str(tenancy.name), tag, str(tenancy.name), tag) data.append(row_data) if data: cursor = cx_Oracle.Cursor(connection) sql = "INSERT INTO OCI_COST_TAG_KEYS (TENANT_NAME , TAG_KEY) " sql += "SELECT :1, :2 FROM DUAL " sql += "WHERE NOT EXISTS (SELECT 1 FROM OCI_COST_TAG_KEYS B WHERE B.TENANT_NAME = :3 AND B.TAG_KEY = :4)" cursor.prepare(sql) cursor.executemany(None, data) connection.commit() cursor.close() print(" Total " + str(len(data)) + " Tags Merged.") logging.info(" Total " + str(len(data)) + " Tags Merged.") return num except cx_Oracle.DatabaseError as e: print("\nload_cost_file() - Error manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: print("\nload_cost_file() - Error Download Usage and insert to database - " + str(e)) raise SystemExit ######################################################################### # Load Usage File ########################################################################## def load_usage_file(connection, object_storage, object_file, max_file_id, cmd, tenancy, compartments): num = 0 try: o = object_file # keep tag keys per file tags_keys = [] # get file name filename = o.name.rsplit('/', 1)[-1] file_id = filename[:-7] file_time = str(o.time_created)[0:16] # if file already loaded, skip (check if < max_usage_file_id) if str(max_file_id) != "None": if file_id <= str(max_file_id): return num # if file id enabled, check if cmd.fileid: if file_id != cmd.file_id: return num # check file date if cmd.filedate: if file_time <= cmd.filedate: return num path_filename = work_report_dir + '/' + filename print(" Processing file " + o.name + " - " + str(o.size) + " bytes, " + file_time) logging.info(" Processing file " + o.name + " - " + str(o.size) + " bytes, " + file_time) # download file object_details = object_storage.get_object(usage_report_namespace, str(tenancy.id), o.name) with open(path_filename, 'wb') as f: for chunk in object_details.data.raw.stream(1024 * 1024, decode_content=False): f.write(chunk) # Read file to variable with gzip.open(path_filename, 'rt') as file_in: csv_reader = csv.DictReader(file_in) data = [] for row in csv_reader: # find compartment path compartment_path = "" for c in compartments: if c['id'] == row['product/compartmentId']: compartment_path = c['path'] # Handle Tags up to 4000 chars with # seperator tags_data = "" for (key, value) in row.items(): if 'tags' in key and len(value) > 0: # remove # and = from the tags keys and value keyadj = str(key).replace("tags/", "").replace("#", "").replace("=", "") valueadj = str(value).replace("#", "").replace("=", "") # check if length < 4000 to avoid overflow database column if len(tags_data) + len(keyadj) + len(valueadj) + 2 < 4000: tags_data += ("#" if tags_data == "" else "") + keyadj + "=" + valueadj + "#" # add tag key to tag_keys array if keyadj not in tags_keys: tags_keys.append(keyadj) # Assign each column to variable to avoid error if column missing from the file lineItem_intervalUsageStart = get_column_value_from_array('lineItem/intervalUsageStart', row) lineItem_intervalUsageEnd = get_column_value_from_array('lineItem/intervalUsageEnd', row) product_service = get_column_value_from_array('product/service', row) product_resource = get_column_value_from_array('product/resource', row) product_compartmentId = get_column_value_from_array('product/compartmentId', row) product_compartmentName = get_column_value_from_array('product/compartmentName', row) product_region = get_column_value_from_array('product/region', row) product_availabilityDomain = get_column_value_from_array('product/availabilityDomain', row) product_resourceId = get_column_value_from_array('product/resourceId', row) usage_billedQuantity = get_column_value_from_array('usage/billedQuantity', row) usage_consumedQuantity = get_column_value_from_array('usage/consumedQuantity', row) usage_consumedQuantityUnits = get_column_value_from_array('usage/consumedQuantityUnits', row) usage_consumedQuantityMeasure = get_column_value_from_array('usage/consumedQuantityMeasure', row) lineItem_isCorrection = get_column_value_from_array('lineItem/isCorrection', row) # create array for bulk insert row_data = ( str(tenancy.name), file_id, lineItem_intervalUsageStart[0:10] + " " + lineItem_intervalUsageStart[11:16], lineItem_intervalUsageEnd[0:10] + " " + lineItem_intervalUsageEnd[11:16], product_service, product_resource, product_compartmentId, product_compartmentName, compartment_path, product_region, product_availabilityDomain, product_resourceId, usage_billedQuantity, usage_consumedQuantity, usage_consumedQuantityUnits, usage_consumedQuantityMeasure, lineItem_isCorrection, tags_data ) data.append(row_data) # insert bulk to database cursor = cx_Oracle.Cursor(connection) sql = "INSERT INTO OCI_USAGE (TENANT_NAME , FILE_ID, USAGE_INTERVAL_START, USAGE_INTERVAL_END, PRD_SERVICE, PRD_RESOURCE, " sql += "PRD_COMPARTMENT_ID, PRD_COMPARTMENT_NAME, PRD_COMPARTMENT_PATH, PRD_REGION, PRD_AVAILABILITY_DOMAIN, USG_RESOURCE_ID, " sql += "USG_BILLED_QUANTITY, USG_CONSUMED_QUANTITY, USG_CONSUMED_UNITS, USG_CONSUMED_MEASURE, IS_CORRECTION, TAGS_DATA " sql += ") VALUES (" sql += ":1, :2, to_date(:3,'YYYY-MM-DD HH24:MI'), to_date(:4,'YYYY-MM-DD HH24:MI'), :5, :6, " sql += ":7, :8, :9, :10, :11, :12, " sql += "to_number(:13), to_number(:14), :15, :16, :17 ,:18 " sql += ") " cursor.prepare(sql) cursor.executemany(None, data) connection.commit() cursor.close() print(" Completed file " + o.name + " - " + str(len(data)) + " Rows Inserted") logging.info(" Completed file " + o.name + " - " + str(len(data)) + " Rows Inserted") num += 1 # remove file os.remove(path_filename) ####################################### # insert bulk tags to the database ####################################### data = [] for tag in tags_keys: row_data = (str(tenancy.name), tag, str(tenancy.name), tag) data.append(row_data) if data: cursor = cx_Oracle.Cursor(connection) sql = "INSERT INTO OCI_USAGE_TAG_KEYS (TENANT_NAME , TAG_KEY) " sql += "SELECT :1, :2 FROM DUAL " sql += "WHERE NOT EXISTS (SELECT 1 FROM OCI_USAGE_TAG_KEYS B WHERE B.TENANT_NAME = :3 AND B.TAG_KEY = :4)" cursor.prepare(sql) cursor.executemany(None, data) connection.commit() cursor.close() print(" Total " + str(len(data)) + " Tags Merged.") logging.info(" Total " + str(len(data)) + " Tags Merged.") return num except cx_Oracle.DatabaseError as e: print("\nload_usage_file() - Error manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: print("\nload_usage_file() - Error Download Usage and insert to database - " + str(e)) raise SystemExit ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Usage Load to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) logging.info("Running Usage Load to ADW") logging.info("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) logging.info("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # Identity extract compartments ############################################ compartments = [] tenancy = None try: print("\nConnecting to Identity Service...") logging.info("Connecting to Identity Service...") identity = oci.identity.IdentityClient(config, signer=signer) if cmd.proxy: identity.base_client.session.proxies = {'https': cmd.proxy} tenancy = identity.get_tenancy(config["tenancy"]).data tenancy_home_region = "" # find home region full name subscribed_regions = identity.list_region_subscriptions(tenancy.id).data for reg in subscribed_regions: if reg.is_home_region: tenancy_home_region = str(reg.region_name) print(" Tenant Name : " + str(tenancy.name)) print(" Tenant Id : " + tenancy.id) print(" App Version : " + version) print(" Home Region : " + tenancy_home_region) print("") logging.info(" Tenant Name : " + str(tenancy.name)) logging.info(" Tenant Id : " + tenancy.id) logging.info(" App Version : " + version) logging.info(" Home Region : " + tenancy_home_region) logging.info("") # set signer home region signer.region = tenancy_home_region config['region'] = tenancy_home_region # Extract compartments compartments = identity_read_compartments(identity, tenancy) except Exception as e: print("\nError extracting compartments section - " + str(e) + "\n") raise SystemExit ############################################ # connect to database ############################################ max_usage_file_id = "" max_cost_file_id = "" connection = None try: print("\nConnecting to database " + cmd.dname) logging.info("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") logging.info(" Connected") # Check tables structure print("\nChecking Database Structure...") logging.info("\nChecking Database Structure...") check_database_table_structure_usage(connection) check_database_table_structure_cost(connection) check_database_table_structure_price_list(connection, tenancy.name) ############################### # fetch max file id processed # for usage and cost ############################### print("\nChecking Last Loaded File...") logging.info("Checking Last Loaded File...") sql = "select nvl(max(file_id),'0') as file_id from OCI_USAGE where to_char(TENANT_NAME)=:tenant_name" cursor.execute(sql, {"tenant_name": str(tenancy.name)}) max_usage_file_id, = cursor.fetchone() sql = "select nvl(max(file_id),'0') as file_id from OCI_COST where to_char(TENANT_NAME)=:tenant_name" cursor.execute(sql, {"tenant_name": str(tenancy.name)}) max_cost_file_id, = cursor.fetchone() print(" Max Usage File Id Processed = " + str(max_usage_file_id)) print(" Max Cost File Id Processed = " + str(max_cost_file_id)) logging.info(" Max Usage File Id Processed = " + str(max_usage_file_id)) logging.info(" Max Cost File Id Processed = " + str(max_cost_file_id)) cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # Download Usage, cost and insert to database ############################################ try: print("\nConnecting to Object Storage Service...") logging.info("\nConnecting to Object Storage Service...") object_storage = oci.object_storage.ObjectStorageClient(config, signer=signer) if cmd.proxy: object_storage.base_client.session.proxies = {'https': cmd.proxy} print(" Connected") logging.info(" Connected") ############################# # Handle Report Usage ############################# print("\nHandling Usage Report...") logging.info("Handling Usage Report...") usage_num = 0 objects = object_storage.list_objects(usage_report_namespace, str(tenancy.id), fields="timeCreated,size", limit=999, prefix="reports/usage-csv/", start="reports/usage-csv/" + max_usage_file_id).data for object_file in objects.objects: usage_num += load_usage_file(connection, object_storage, object_file, max_usage_file_id, cmd, tenancy, compartments) print("\n Total " + str(usage_num) + " Usage Files Loaded") logging.info("Total " + str(usage_num) + " Usage Files Loaded") ############################# # Handle Cost Usage ############################# print("\nHandling Cost Report...") cost_num = 0 objects = object_storage.list_objects(usage_report_namespace, str(tenancy.id), fields="timeCreated,size", limit=999, prefix="reports/cost-csv/", start="reports/cost-csv/" + max_cost_file_id).data for object_file in objects.objects: cost_num += load_cost_file(connection, object_storage, object_file, max_cost_file_id, cmd, tenancy, compartments) print("\n Total " + str(cost_num) + " Cost Files Loaded") logging.info(" Total " + str(cost_num) + " Cost Files Loaded") # Handle Index structure if not exist check_database_index_structure_usage(connection) check_database_index_structure_cost(connection) # Update oci_usage_stats and oci_cost_stats if there were files if usage_num > 0: update_usage_stats(connection) if cost_num > 0: update_cost_stats(connection) update_cost_reference(connection) update_price_list(connection) update_public_rates(connection, tenancy.name) # Close Connection connection.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") except Exception as e: print("\nError Download Usage and insert to database - " + str(e)) ############################################ # print completed ############################################ print("\nCompleted at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) logging.info("Completed at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) ########################################################################## # Execute Main Process ########################################################################## main_process() <file_sep>import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle import time import pytz os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") naive= datetime.datetime.now() timezone = pytz.timezone("Europe/Berlin") aware1 = naive.astimezone(timezone) current_time = str(aware1.strftime("%Y-%m-%d %H:%M:%S")) ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # def check table ds_nbs ########################################################################## def check_database_table_structure_ds_nbs(connection): try: # open cursor cursor = connection.cursor() # check if OCI_COMPARTMENTS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_DS_NBS'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print("Table OCI_DS_NBS was not exist, creating") sql = "create table OCI_DS_NBS (" sql += " DISPLAY_NAME VARCHAR2(200)," sql += " COMPARTMENT_ID VARCHAR2(200)," sql += " ID VARCHAR2(200)," sql += " LIFECYCLE_STATE VARCHAR2(300)," sql += " NOTEBOOKSESSION_CONFIG_DETAILS VARCHAR2(500)," sql += " NOTEBOOKSESSION_URL VARCHAR2(500)," sql += " PROJECT_ID VARCHAR2(200)," sql += " TIME_CREATED VARCHAR2(100)," sql += " DEFINED_TAGS VARCHAR2(500)," sql += " FREEFORM_TAGS VARCHAR2(500)," sql += " OCI_REGION VARCHAR2(100)" #sql += " CONSTRAINT primary_key PRIMARY KEY (OCID)" sql += ") COMPRESS" cursor.execute(sql) print("Table OCI_DS_NBS created") cursor.close() else: print("Table OCI_DS_NBS exist") except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_structure_usage() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_structure_usage() - " + str(e)) ########################################################################## # Update DATA SCIENCE SESSION Function ########################################################################## def update_oci_ds_nbs(connection,notebooklist): cursor = connection.cursor() sql = "delete from OCI_DS_NBS" cursor.execute(sql) sql = "begin commit; end;" cursor.execute(sql) print("OCI_DS_NBS Deleted") ###### sql = "INSERT INTO OCI_DS_NBS (" sql += " DISPLAY_NAME ," sql += " COMPARTMENT_ID ," sql += " ID ," sql += " LIFECYCLE_STATE ," sql += " NOTEBOOKSESSION_CONFIG_DETAILS ," sql += " NOTEBOOKSESSION_URL ," sql += " PROJECT_ID ," sql += " TIME_CREATED ," sql += " DEFINED_TAGS ," sql += " FREEFORM_TAGS ," sql += " OCI_REGION " sql += ") VALUES (" sql += ":1, :2, :3, :4, :5, " sql += ":6, :7, :8, :9, :10, " sql += ":11" sql += ") " cursor.prepare(sql) cursor.executemany(None, notebooklist) connection.commit() cursor.close() print("DATA SCIENCE NOTEBOOKS Updated") ########################################################################## # Insert Update Time ########################################################################## def update_time(connection, current_time): cursor = connection.cursor() report = 'DATASCIENCE_NOTEBOOKS' time_updated = current_time ###### sql = """insert into OCI_UPDATE_TIME (REPORT, TIME_UPDATED) values (:report, :time_updated)""" cursor.execute(sql, [report, time_updated]) connection.commit() cursor.close() print("TIME Updated") ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Users to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # connect to database ############################################ connection = None try: print("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") # Check tables structure print("\nChecking Database Structure...") check_database_table_structure_ds_nbs(connection) except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # Getting Compartments from Database ############################################ # open cursor cursor = connection.cursor() print("Getting Compartments from Database") # check if OCI_COMPARTMENTS table exist, if not create sql = "select OCID from oci_compartments where LIFECYCLE_STATE = 'ACTIVE'" cursor.execute(sql) l_ocid = cursor.fetchall() l_ocid_n = [] for c in range(len(l_ocid)): l_ocid_n.append(l_ocid[c][0]) ############################################ # API extract ADBs ############################################ try: print("\nConnecting to DS Client...") datascienceclient = oci.data_science.DataScienceClient(config, signer=signer) if cmd.proxy: datascienceclient.base_client.session.proxies = {'https': cmd.proxy} print("Getting Data Science Notebooks") notebooklist = [] for region in [#'ap-sydney-1', #'ap-tokyo-1', 'us-phoenix-1', 'us-ashburn-1', 'eu-frankfurt-1', 'uk-london-1', 'eu-amsterdam-1', #'ca-toronto-1', #'sa-saopaulo-1' ]: config['region'] = region datascienceclient = oci.data_science.DataScienceClient(config, signer=signer) print('Check for...',config['region']) for a in range(len(l_ocid_n)): notebooks = datascienceclient.list_notebook_sessions(compartment_id = l_ocid_n[a]) if len(notebooks.data) != 0: for i in range(len(notebooks.data)): row_data = ( notebooks.data[i].display_name, notebooks.data[i].compartment_id, notebooks.data[i].id, notebooks.data[i].lifecycle_state, str(notebooks.data[i].notebook_session_configuration_details), notebooks.data[i].notebook_session_url, notebooks.data[i].project_id, notebooks.data[i].time_created.isoformat(), str(notebooks.data[i].defined_tags), str(notebooks.data[i].freeform_tags), region ) print('Listed...', notebooks.data[i].display_name) notebooklist.append(row_data) except Exception as e: print("\nError extracting ADBs - " + str(e) + "\n") raise SystemExit ############################################ # Update ADBs ############################################ update_oci_ds_nbs(connection,notebooklist) cursor.close() ############################################ # print completed ############################################ print("\nCompleted at " + current_time) update_time(connection, current_time) ########################################################################## # Execute Main Process ########################################################################## main_process() <file_sep>import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle import time os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # def check table adbs ########################################################################## def check_database_table_structure_updatetime(connection): try: # open cursor cursor = connection.cursor() # check if OCI_COMPARTMENTS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_UPDATE_TIME'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print("Table OCI_UPDATE_TIME was not exist, creating") sql = "create table OCI_UPDATE_TIME (" sql += " REPORT VARCHAR2(200)," sql += " TIME_UPDATED VARCHAR2(500)" #sql += " CONSTRAINT primary_key PRIMARY KEY (OCID)" sql += ") COMPRESS" cursor.execute(sql) print("Table OCI_UPDATE_TIME created") else: print("Table OCI_UPDATE_TIME exist") except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_structure_usage() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_structure_usage() - " + str(e)) ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Users to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # connect to database ############################################ connection = None try: print("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") ############################################ # Create Update Time table ############################################ check_database_table_structure_updatetime(connection) cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # print completed ############################################ print("\nCompleted at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) ########################################################################## # Execute Main Process ########################################################################## main_process()<file_sep>import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle import time import pytz os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") naive= datetime.datetime.now() timezone = pytz.timezone("Europe/Berlin") aware1 = naive.astimezone(timezone) current_time = str(aware1.strftime("%Y-%m-%d %H:%M:%S")) ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # def check table ds_nbs ########################################################################## def check_database_table_structure_compute(connection): try: # open cursor cursor = connection.cursor() # check if OCI_COMPARTMENTS table exist, if not create sql = "select count(*) from user_tables where table_name = 'OCI_COMPUTE'" cursor.execute(sql) val, = cursor.fetchone() # if table not exist, create it if val == 0: print("Table OCI_COMPUTE was not exist, creating") sql = "create table OCI_COMPUTE (" sql += " AVAILABILITY_DOMAIN VARCHAR2(200)," sql += " COMPARTMENT_ID VARCHAR2(200)," sql += " DEDICATED_VM_HOST_ID VARCHAR2(200)," sql += " DEFINED_TAGS VARCHAR2(500)," sql += " DISPLAY_NAME VARCHAR2(200)," sql += " EXTENDED_METADATA VARCHAR2(500)," sql += " FAULT_DOMAIN VARCHAR2(200)," sql += " FREEFORM_TAGS VARCHAR2(500)," sql += " ID VARCHAR2(200)," sql += " IMAGE_ID VARCHAR2(200)," sql += " IPXE_SCRIPT VARCHAR2(200)," sql += " LAUNCH_MODE VARCHAR2(200)," sql += " LAUNCH_MODE_OPTIONS VARCHAR2(200)," sql += " LIFECYCLE_STATE VARCHAR2(200)," sql += " METADATA VARCHAR2(200)," sql += " REGION VARCHAR2(200)," sql += " SHAPE VARCHAR2(200)," sql += " SHAPE_CONFIG VARCHAR2(200)," sql += " SOURCE_DETAILS VARCHAR2(200)," sql += " SYSTEM_TAGS VARCHAR2(200)," sql += " TIME_CREATED VARCHAR2(200)," sql += " TIME_MAINTENANCE_REBOOT_DUE VARCHAR2(200)," sql += " OCI_REGION VARCHAR2(100)" #sql += " CONSTRAINT primary_key PRIMARY KEY (OCID)" sql += ") COMPRESS" cursor.execute(sql) print("Table OCI_COMPUTE created") cursor.close() else: print("Table OCI_COMPUTE exist") except cx_Oracle.DatabaseError as e: print("\nError manipulating database at check_database_table_structure_usage() - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database at check_database_table_structure_usage() - " + str(e)) ########################################################################## # Update DATA SCIENCE SESSION Function ########################################################################## def update_oci_compute(connection,computelist): #update cursor = connection.cursor() sql = "delete from OCI_COMPUTE" cursor.execute(sql) sql = "begin commit; end;" cursor.execute(sql) print("OCI_COMPUTE Deleted") ###### sql = "INSERT INTO OCI_COMPUTE (" sql += " AVAILABILITY_DOMAIN ," sql += " COMPARTMENT_ID ," sql += " DEDICATED_VM_HOST_ID ," sql += " DEFINED_TAGS , " sql += " DISPLAY_NAME ," sql += " EXTENDED_METADATA ," sql += " FAULT_DOMAIN ," sql += " FREEFORM_TAGS ," sql += " ID ," sql += " IMAGE_ID , " sql += " IPXE_SCRIPT ," sql += " LAUNCH_MODE ," sql += " LAUNCH_MODE_OPTIONS ," sql += " LIFECYCLE_STATE ," sql += " METADATA ," sql += " REGION ," sql += " SHAPE ," sql += " SHAPE_CONFIG ," sql += " SOURCE_DETAILS ," sql += " SYSTEM_TAGS ," sql += " TIME_CREATED ," sql += " TIME_MAINTENANCE_REBOOT_DUE ," sql += " OCI_REGION " sql += ") VALUES (" sql += " :1, :2, :3, :4, :5," sql += ":6, :7, :8, :9, :10 ," sql += ":11, :12, :13, :14, :15, :16, :17, :18, :19 , :20, :21, :22, :23" sql += ") " cursor.prepare(sql) cursor.executemany(None, computelist) connection.commit() print("COMPUTE Updated") ########################################################################## # Insert Update Time ########################################################################## def update_time(connection, current_time): cursor = connection.cursor() report = 'COMPUTE' time_updated = current_time ###### sql = """insert into OCI_UPDATE_TIME (REPORT, TIME_UPDATED) values (:report, :time_updated)""" cursor.execute(sql, [report, time_updated]) connection.commit() cursor.close() print("TIME Updated") ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Users to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # connect to database ############################################ connection = None try: print("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") # Check tables structure print("\nChecking Database Structure...") check_database_table_structure_compute(connection) except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # Getting Compartments from Database ############################################ # open cursor cursor = connection.cursor() print("Getting Compartments from Database") # check if OCI_COMPARTMENTS table exist, if not create sql = "select OCID from oci_compartments where LIFECYCLE_STATE = 'ACTIVE'" cursor.execute(sql) l_ocid = cursor.fetchall() l_ocid_n = [] for c in range(len(l_ocid)): l_ocid_n.append(l_ocid[c][0]) ############################################ # API extract ADBs ############################################ try: print("\nConnecting to Compute Client...") computeclient = oci.core.ComputeClient(config, signer=signer) if cmd.proxy: datascienceclient.base_client.session.proxies = {'https': cmd.proxy} print("Getting Compute Instances") computelist = [] for region in [#'ap-sydney-1', #'ap-tokyo-1', #'us-phoenix-1', #'us-ashburn-1', 'eu-frankfurt-1', 'uk-london-1', #'eu-amsterdam-1', #'ca-toronto-1', #'sa-saopaulo-1' ]:#oci.regions.REGIONS: config['region'] = region computeclient = oci.core.ComputeClient(config, signer=signer) #time.sleep(60) print('Check for...',config['region']) for a in range(len(l_ocid_n)): instances = computeclient.list_instances(compartment_id = l_ocid_n[a]) if len(instances.data) != 0: for i in range(len(instances.data)): row_data = ( instances.data[i].availability_domain, instances.data[i].compartment_id, instances.data[i].dedicated_vm_host_id, str(instances.data[i].defined_tags), instances.data[i].display_name, str(instances.data[i].extended_metadata), instances.data[i].fault_domain, str(instances.data[i].freeform_tags), instances.data[i].id, instances.data[i].image_id, 'null',#instances.data[i].ipxe_script, instances.data[i].launch_mode, 'null',#str(instances.data[i].launch_options), instances.data[i].lifecycle_state, 'null',#instances.data[i].metadata, instances.data[i].region, str(instances.data[i].shape), 'null',#instances.data[i].shape_config, 'null',#str(instances.data[i].source_details), str(instances.data[i].system_tags), instances.data[i].time_created.isoformat(), 'null',#instances.data[i].time_maintenance_reboot_due, region ) print('\tListed...', instances.data[i].display_name) computelist.append(row_data) except Exception as e: print("\nError extracting Compute - " + str(e) + "\n") raise SystemExit ############################################ # Update ADBs ############################################ update_oci_compute(connection,computelist) cursor.close() ############################################ # print completed ############################################ print("\nCompleted at " + current_time) update_time(connection, current_time) ########################################################################## # Execute Main Process ########################################################################## main_process()<file_sep>import sys import argparse import datetime import oci import gzip import os import csv import cx_Oracle os.putenv("TNS_ADMIN", "/home/opc/wallet/Wallet_ADWshared") ########################################################################## # Print header centered ########################################################################## def print_header(name, category): options = {0: 90, 1: 60, 2: 30} chars = int(options[category]) print("") print('#' * chars) print("#" + name.center(chars - 2, " ") + "#") print('#' * chars) ########################################################################## # Create signer ########################################################################## def create_signer(cmd): # assign default values config_file = oci.config.DEFAULT_LOCATION config_section = oci.config.DEFAULT_PROFILE if cmd.config: if cmd.config.name: config_file = cmd.config.name if cmd.profile: config_section = cmd.profile if cmd.instance_principals: try: signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner() config = {'region': signer.region, 'tenancy': signer.tenancy_id} return config, signer except Exception: print_header("Error obtaining instance principals certificate, aborting", 0) raise SystemExit else: config = oci.config.from_file(config_file, config_section) signer = oci.signer.Signer( tenancy=config["tenancy"], user=config["user"], fingerprint=config["fingerprint"], private_key_file_location=config.get("key_file"), pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"), private_key_content=config.get("key_content") ) return config, signer ########################################################################## # set parser ########################################################################## def set_parser_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File") parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)') parser.add_argument('-f', default="", dest='fileid', help='File Id to load') parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)') parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ') parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication') parser.add_argument('-du', default="", dest='duser', help='ADB User') parser.add_argument('-dp', default="", dest='dpass', help='ADB Password') parser.add_argument('-dn', default="", dest='dname', help='ADB Name') result = parser.parse_args() if not (result.duser and result.dpass and result.dname): parser.print_help() print_header("You must specify database credentials!!", 0) return None return result ########################################################################## # Main ########################################################################## def main_process(): cmd = set_parser_arguments() if cmd is None: exit() config, signer = create_signer(cmd) ############################################ # Start ############################################ print_header("Running Users to ADW", 0) print("Starts at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print("Command Line : " + ' '.join(x for x in sys.argv[1:])) ############################################ # Identity extract compartments ############################################ ############################################ # connect to database ############################################ connection = None try: print("\nConnecting to database " + cmd.dname) connection = cx_Oracle.connect(user=cmd.duser, password=<PASSWORD>, dsn=cmd.dname, encoding="UTF-8", nencoding="UTF-8") cursor = connection.cursor() print(" Connected") ############################################ # Getting Emails ############################################ print("Getting Emails...") sql = "select a.*, b.MANAGER, b.adminone, b.admintwo from V_LISTAGG_FLAGGED_ADBS a left join (select distinct EXTRACTED_EMAIL, manager, adminone, admintwo from V_SENDMAILS) b on a.EXTRACTED_EMAIL=b.EXTRACTED_EMAIL" cursor.execute(sql) l_flaggedadbs = cursor.fetchall() ############################################ # Send Emails ############################################ print("Sending Emails...") for i in range(len(l_flaggedadbs)): tmp_amdin_l = [] tmp_amdin_l = [i for i in [l_flaggedadbs[i][3],l_flaggedadbs[i][4]] if i] bcss = tmp_amdin_l + ['<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>'] bccs = ', '.join(list(set(bcss))) cursor.callproc('SEND_ADB_MAIL', ['<EMAIL>', #from l_flaggedadbs[i][0], #to email 'Private ADB', #subject str(l_flaggedadbs[i][0].split('.')[0].title()), #first name from email str(l_flaggedadbs[i][1]), #ADB list bccs ]) print("Pushed Email to ",str(l_flaggedadbs[i][0].split('.')[0].title()),' (Email:',l_flaggedadbs[i][0],') regarding ', str(l_flaggedadbs[i][1]),' to ', bccs) cursor.callproc('pushed') cursor.close() except cx_Oracle.DatabaseError as e: print("\nError manipulating database - " + str(e) + "\n") raise SystemExit except Exception as e: raise Exception("\nError manipulating database - " + str(e)) ############################################ # print completed ############################################ print("\nCompleted at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) ########################################################################## # Execute Main Process ########################################################################## main_process()
e154cc722683495b7fa6731fc23ead9fda9a99d7
[ "Python" ]
6
Python
saschahsp/oci_scripts
edba249292cdd69b59fd6904ae99a4d2b881db23
321494cb5a3417ee797ef10b110206a90f9ceae0
refs/heads/master
<file_sep># swiftlist Simple Android list app (outdated) <file_sep>package com.osmanthus.swiftlist; import android.app.Application; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; //DONE - add divider to last item in widget list //DONE - change curve radius of widget list //DONE - improve look of widget border //DONE - reduce checkmark size of widget list //DONE - dull out checked widget and list items //DONE - don't force this to be on the main thread //DONE - cleanup old code and imports //DONE - make clickable widget area better //TODO - add settings for transparency, color, add position (top or bot), text size //TODO - add setting for dark mode //TODO - drag to delete items //TODO - add undo toast for deleting items //TODO - make icons in main activity look good (add and delete icons) //TODO - update checkmark sprite //TODO - update widget preview image //TODO - add custom app icon /* Could use position as primary key When editing would have to set the position to something like 0, then change the other item's position, then change it back This would allow storing items in a hashmap yet still be useful for RecyclerAdapter */ public class MainActivity extends AppCompatActivity { private RecyclerViewAdapter adapter; private RecyclerView recyclerView; private static Handler adapterHandler; private static LinearLayoutManager layoutManager; private static FloatingActionButton fabAdd; private static FloatingActionButton fabDelete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Add item button fabAdd = findViewById(R.id.fab); fabAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent editListItem = new Intent(view.getContext(), EditListItem.class); startActivity(editListItem); } }); //Delete item(s) button fabDelete = findViewById(R.id.fab_delete); fabDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TaskDispatcher.getInstance().removeCheckedItems(getApplicationContext()); } }); //Disable buttons until list is retrieved from database //As far as I understand, onCreate must finish before messages can be handled, //so there shouldn't be any threading problems with this //(messages for the handler are queued on the main thread, and onCreate should be first) /* if (TaskDispatcher.getInstance().getChecklistItems(this) == null) { fabAdd.setAlpha(0.5f); fabDelete.setAlpha(0.5f); fabAdd.setEnabled(false); fabDelete.setEnabled(false); } */ initRecyclerView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //Log.d("BOOTY", "option pressed"); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); //return true; } return true; //return super.onOptionsItemSelected(item); } private void initRecyclerView() { recyclerView = findViewById(R.id.recyler_view); adapter = new RecyclerViewAdapter(this, recyclerView); recyclerView.setAdapter(adapter); adapterHandler = new AdapterHandler(getApplication(), adapter); TaskDispatcher.getInstance().setExternalHandler(adapterHandler); layoutManager = new LinearLayoutManager(this); //layoutManager.setStackFromEnd(true); //TODO - do I really need to do this? recyclerView.setLayoutManager(layoutManager); } @Override public void onPause() { TaskDispatcher.updateWidgetView(this); super.onPause(); } @Override public void onDestroy() { TaskDispatcher.getInstance().setExternalHandler(null); super.onDestroy(); } static class AdapterHandler extends Handler { private RecyclerViewAdapter adapter; private Application application; AdapterHandler(Application application, RecyclerViewAdapter adapter) { this.application = application; this.adapter = adapter; } @Override public void handleMessage(Message msg) { switch (msg.what) { case TaskDispatcher.UPDATE_ITEM: adapter.notifyItemChanged(msg.arg1); break; case TaskDispatcher.INSERT_ITEM: adapter.notifyItemInserted(msg.arg1); break; case TaskDispatcher.REMOVE_ITEM: //TODO - would like to eventually remove items more efficiently adapter.notifyDataSetChanged(); Toast.makeText(application.getApplicationContext(), msg.arg1 + " items deleted.", Toast.LENGTH_SHORT).show(); break; case TaskDispatcher.DATA_CHANGED: adapter.notifyDataSetChanged(); break; case TaskDispatcher.DATA_LOADED: adapter.notifyDataSetChanged(); /* fabAdd.setAlpha(1.0f); fabDelete.setAlpha(1.0f); fabAdd.setEnabled(true); fabDelete.setEnabled(true); */ break; case TaskDispatcher.SWAP_ITEM: //Starting from here int firstPos = layoutManager.findFirstCompletelyVisibleItemPosition(); int offsetTop = 0; if(firstPos >= 0){ View firstView = layoutManager.findViewByPosition(firstPos); offsetTop = layoutManager.getDecoratedTop(firstView) - layoutManager.getTopDecorationHeight(firstView); } adapter.notifyItemMoved(msg.arg1, msg.arg2); if(firstPos >= 0) { layoutManager.scrollToPositionWithOffset(firstPos, offsetTop); } //and ending here is from //https://stackoverflow.com/questions/27992427/recyclerview-adapter-notifyitemmoved0-1-scrolls-screen?answertab=votes#tab-top //adapter.notifyItemMoved(msg.arg1, msg.arg2); ChecklistItem test1 = TaskDispatcher.getInstance().getChecklistItems(application.getApplicationContext()).get(msg.arg1); ChecklistItem test2 = TaskDispatcher.getInstance().getChecklistItems(application.getApplicationContext()).get(msg.arg2); adapter.notifyItemChanged(msg.arg1, test2); adapter.notifyItemChanged(msg.arg2, test1); //adapter.notifyDataSetChanged(); break; default: //Shouldn't happen break; } super.handleMessage(msg); } } } <file_sep>package com.osmanthus.swiftlist; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.widget.RemoteViews; import android.widget.RemoteViewsService; public class ListWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new ListWidgetFactory(this.getApplicationContext(), intent); } } class ListWidgetFactory implements RemoteViewsService.RemoteViewsFactory { private Context context; private static int lastClicked; public ListWidgetFactory(Context context, Intent intent) { this.context = context; } @Override public void onCreate() { } @Override public void onDataSetChanged() { } @Override public void onDestroy() { } @Override public int getCount() { //TODO - should probably cache the list here too if (TaskDispatcher.getInstance().getChecklistItems(context) != null) { return TaskDispatcher.getInstance().getChecklistItems(context).size(); } else { return 0; } } @Override public RemoteViews getViewAt(int position) { if (TaskDispatcher.getInstance().getChecklistItems(context) != null) { lastClicked = position; RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.list_widget_item); ChecklistItem item = TaskDispatcher.getInstance().getChecklistItems(context).get(position); views.setTextViewText(R.id.widget_textView, item.text); //TODO - should cache the list instead if (item.isChecked) { views.setInt(R.id.widget_imageButton, "setImageResource", R.drawable.checkmark); views.setTextColor(R.id.widget_textView, Color.GRAY); } else { views.setInt(R.id.widget_imageButton, "setImageResource", R.drawable.checkmark_empty); views.setTextColor(R.id.widget_textView, Color.parseColor("#323232")); } Intent fillInIntent = new Intent(); fillInIntent.putExtra(ListWidget.ITEM_ID, item.id); fillInIntent.putExtra(ListWidget.ITEM_POS, position); views.setOnClickFillInIntent(R.id.widget_imageButton, fillInIntent); Intent launchApp = new Intent(); launchApp.putExtra(ListWidget.ITEM_ID, (long)(-1)); views.setOnClickFillInIntent(R.id.widget_textView, launchApp); return views; } else { return null; } } @Override public RemoteViews getLoadingView() { //TODO - can try to do something here to get rid of widget loading message return null; } @Override public int getViewTypeCount() { return 1; } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } }<file_sep>package com.osmanthus.swiftlist; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class EditListItem extends AppCompatActivity { public static final String TO_EDIT = "com.osmanthus.swiftlist.TO_EDIT"; public static final String TO_EDIT_ID = "com.osmanthus.swiftlist.TO_EDIT_ID"; public static final String TO_EDIT_POS = "com.osmanthus.swiftlist.TO_EDIT_POS"; private TextView textView; private Button saveButton; private Intent passedIntent; private boolean isEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_list_item); textView = findViewById(R.id.editText); passedIntent = getIntent(); String editText = passedIntent.getStringExtra(TO_EDIT); final long editID = passedIntent.getLongExtra(TO_EDIT_ID, 0); if (editText != null) { isEdit = true; textView.setText(editText); } textView.requestFocus(); saveButton = findViewById(R.id.button_save); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (textView.getText().toString().equals("")) { finish(); } else { saveEdit(textView.getText().toString(), editID); } } }); } private void saveEdit(String text, long id) { if (!isEdit) { TaskDispatcher.getInstance().addItem(this, text); } else { int pos = passedIntent.getIntExtra(TO_EDIT_POS, 0); TaskDispatcher.getInstance().updateItemText(this, pos, id, text); } finish(); } } <file_sep>package com.osmanthus.swiftlist; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.List; @Dao public interface ChecklistItemDao { @Query("SELECT * FROM checklistitem WHERE id IS :itemID LIMIT 1") ChecklistItem getItem(long itemID); @Query("SELECT position FROM checklistitem WHERE id IS :itemID LIMIT 1") int getItemPosition(long itemID); @Query("SELECT isChecked FROM checklistitem WHERE id IS :itemID LIMIT 1") boolean getChecked(long itemID); @Query("SELECT * FROM checklistitem") List<ChecklistItem> getAllChecklistItems(); @Query("SELECT * FROM checklistitem ORDER BY position ASC") List<ChecklistItem> getAllChecklistItemsByPosition(); @Query("UPDATE checklistitem SET text = :newText WHERE id IS :itemID") void setItemText(long itemID, String newText); @Query("UPDATE checklistitem SET isChecked = :checked WHERE id IS :itemID") void setItemChecked(long itemID, int checked); @Query("UPDATE checklistitem SET position = :pos WHERE id IS :itemID") void setItemPosition(long itemID, int pos); //Insert doesn't work with room database //@Query("INSERT INTO checklistitem VALUES(NULL, (SELECT COUNT(id) FROM checklistitem), :text, 0)") //ChecklistItem insertItem(String text); //@Query("SELECT id FROM checklistitem ORDER BY id DESC LIMIT 1") //could use max(position) since just trying to find last position @Query("SELECT COUNT(id) FROM checklistitem") int getItemCount(); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(ChecklistItem item); @Update void update(ChecklistItem item); @Update void updateList(List<ChecklistItem> items); @Delete void delete(ChecklistItem item); @Delete void deleteList(List<ChecklistItem> items); } <file_sep>package com.osmanthus.swiftlist; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.os.Handler; import android.os.Message; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TaskDispatcher { public static final int UPDATE_ITEM = 0; public static final int INSERT_ITEM = 1; public static final int REMOVE_ITEM = 2; public static final int SWAP_ITEM = 3; public static final int DATA_CHANGED = 4; public static final int DATA_LOADED = 5; private static final TaskDispatcher ourInstance = new TaskDispatcher(); public static TaskDispatcher getInstance() { return ourInstance; } private ExecutorService manager; private List<ChecklistItem> checklistItems; private static Handler externalHandler; private TaskDispatcher() { manager = Executors.newSingleThreadExecutor(); } public static void updateWidgetView(final Context context) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName componentName = new ComponentName(context, ListWidget.class); //TODO - would be nice to not have to fetch appWidgetIds every single time int[] appWidgetIds = appWidgetManager.getAppWidgetIds(componentName); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list); } private void verifyChecklistDatabase(final Context context) { if (checklistItems == null) checklistItems = ChecklistDatabase.getInstance(context).getChecklistDao().getAllChecklistItemsByPosition(); } public List<ChecklistItem> getChecklistItems(final Context context) { if (checklistItems == null) { manager.submit(new Runnable() { @Override public void run() { if (checklistItems == null) { checklistItems = ChecklistDatabase.getInstance(context).getChecklistDao().getAllChecklistItemsByPosition(); if (externalHandler != null) { Message msg = new Message(); msg.what = DATA_LOADED; externalHandler.sendMessage(msg); } updateWidgetView(context); } } }); } //This will return null if the list has not yet been initialized //so adapters must check for null return return checklistItems; } public void addItem(final Context context, final String itemText) { //TODO - disable add button before taskdispatcher has tried to get the info from database //TODO - disable delete button when list is empty final ChecklistItem toInsert; toInsert = new ChecklistItem(0, checklistItems.size(), itemText, false); checklistItems.add(toInsert); if (externalHandler != null) { Message msg = new Message(); msg.what = INSERT_ITEM; msg.arg1 = toInsert.position; externalHandler.sendMessage(msg); } manager.submit(new Runnable() { @Override public void run() { long id = ChecklistDatabase.getInstance(context).getChecklistDao().insert(toInsert); toInsert.id = id; } }); } public void updateItemText(final Context context, int initPos, final long itemID, final String itemText) { checklistItems.get(initPos).text = itemText; if (externalHandler != null) { Message msg = new Message(); msg.what = UPDATE_ITEM; msg.arg1 = initPos; externalHandler.sendMessage(msg); } manager.submit(new Runnable() { @Override public void run() { ChecklistDatabase.getInstance(context).getChecklistDao().setItemText(itemID, itemText); } }); } public void updateItemChecked(final Context context, int initPos, final long itemID, final boolean isChecked) { checklistItems.get(initPos).isChecked = isChecked; manager.submit(new Runnable() { @Override public void run() { ChecklistDatabase.getInstance(context).getChecklistDao().setItemChecked(itemID, isChecked ? 1 : 0); } }); } //Updates an item's checked status without being passed the new value //Slightly slower (I think), but less info needed (for widget use) public void toggleItemChecked(final Context context, final BroadcastReceiver.PendingResult pendingResult, int initPos, final long itemID) { //TODO - what if main activity gets closed after this is checked, but before item is set? //Could result in a null pointer exception. Should use a JobScheduler instead so that //TaskDispatcher can outlive the activity (if it still has pending jobs, that is) if (checklistItems != null) { checklistItems.get(initPos).isChecked = !checklistItems.get(initPos).isChecked; if (externalHandler != null) { Message msg = new Message(); msg.what = UPDATE_ITEM; msg.arg1 = initPos; externalHandler.sendMessage(msg); } } manager.submit(new Runnable() { @Override public void run() { boolean isChecked = !ChecklistDatabase.getInstance(context).getChecklistDao().getChecked(itemID); ChecklistDatabase.getInstance(context).getChecklistDao().setItemChecked(itemID, isChecked ? 1 : 0); updateWidgetView(context); pendingResult.finish(); } }); } public void removeCheckedItems(final Context context) { final List<ChecklistItem> removed = new ArrayList<>(); final List<ChecklistItem> updated = new ArrayList<>(); ChecklistItem tempItem; int totalDeleted = 0; int i = 0; //TODO - when/if i implement a custom list, this logic may no longer work //TODO - keep track of a separate list of checked items so don't need to go through //whole list while (i < checklistItems.size()) { tempItem = checklistItems.get(i); if(tempItem.isChecked) { totalDeleted++; removed.add(checklistItems.remove(i)); //Check if i is now outside of bounds if (i < checklistItems.size()) { //Must update position of item that took this one's place tempItem = checklistItems.get(i); tempItem.position = i; updated.add(tempItem); } //TODO - should keep track of all deleted then send them all to adapter //at once at the end } else { if ((totalDeleted != 0)) { tempItem.position = i; updated.add(tempItem); } i++; } } if (externalHandler != null) { Message msg = new Message(); msg.what = REMOVE_ITEM; msg.arg1 = totalDeleted; externalHandler.sendMessage(msg); } manager.submit(new Runnable() { @Override public void run() { ChecklistDatabase.getInstance(context).getChecklistDao().deleteList(removed); ChecklistDatabase.getInstance(context).getChecklistDao().updateList(updated); } }); } public void swapItems(final Context context, final int index1, final int index2) { final ChecklistItem cItem1 = checklistItems.get(index1); final ChecklistItem cItem2 = checklistItems.get(index2); cItem1.position = index2; cItem2.position = index1; Collections.swap(checklistItems, index1, index2); //final long item1ID = cItem1.id; //final long item2ID = cItem2.id; if (externalHandler != null) { Message msg = new Message(); msg.what = SWAP_ITEM; msg.arg1 = index1; msg.arg2 = index2; externalHandler.sendMessage(msg); } manager.submit(new Runnable() { @Override public void run() { //int pos1 = ChecklistDatabase.getInstance(context).getChecklistDao().getItemPosition(item1ID); //int pos2 = ChecklistDatabase.getInstance(context).getChecklistDao().getItemPosition(item2ID); //Using ref to real obj here b/c after adding an element, the id could still be 0 //But once at the point of running another task, item is guaranteed to have had its id set ChecklistDatabase.getInstance(context).getChecklistDao().setItemPosition(cItem1.id, index2); ChecklistDatabase.getInstance(context).getChecklistDao().setItemPosition(cItem2.id, index1); } }); } public void setExternalHandler(Handler handler) { externalHandler = handler; } }
29e7d32648c94a4d7c973dfa59dbfb25754e4569
[ "Markdown", "Java" ]
6
Markdown
StephenKamali/swiftlist
744e4e5e52ec6bfb509f2f40335e4f2114e86251
1765199cecb62f0936cdca7f0261f3bd5dea46c5
refs/heads/master
<repo_name>catalyticstorm/apiHomework<file_sep>/assets/script/script.js // JavaScript Document $("button").on("click", function() { var animal = $(this).attr("data-animal"); var queryY = "https://api.giphy.com/v1/gifs/search?q=" + animal + "&api_key=<KEY>&limit=1&rating=y"; var queryG = "https://api.giphy.com/v1/gifs/search?q=" + animal + "&api_key=<KEY>&limit=1&rating=g"; var queryPG = "https://api.giphy.com/v1/gifs/search?q=" + animal + "&api_key=<KEY>&limit=1&rating=pg"; var queryPGTHTN = "https://api.giphy.com/v1/gifs/search?q=" + animal + "&api_key=<KEY>&limit=1&rating=pg13"; $.ajax({ url: queryY, method: "GET" }).then(function(response) { var yStuff = response.data; console.log(yStuff); $("#gifDivY").prepend('<img src="' + yStuff[0].images.fixed_height.url + '" alt="">'); }); $.ajax({ url: queryG, method: "GET" }).then(function(response) { var gStuff = response.data; $("#gifDivG").prepend('<img src="' + gStuff[0].images.fixed_height.url + '" alt="">'); }); $.ajax({ url: queryPG, method: "GET" }).then(function(response) { var pgStuff = response.data; $("#gifDivPG").prepend('<img src="' + pgStuff[0].images.fixed_height.url + '" alt="">'); }); $.ajax({ url: queryPGTHTN, method: "GET" }).then(function(response) { var pgTHTNStuff = response.data; $("#gifDivPGTHTN").prepend('<img src="' + pgTHTNStuff[0].images.fixed_height.url + '" alt="">'); }); });
a75f0d17deac23cce848108a50aecc8c7afcfcbc
[ "JavaScript" ]
1
JavaScript
catalyticstorm/apiHomework
c44dfec2918159cdf788242602fee9d55ba47d63
6103e1619cbaab5512d3d1d024ab60612bbe2cb9
refs/heads/master
<repo_name>Coutanthomas/simple_navigation_goals<file_sep>/scripts/patrouille.py #! /usr/bin/python import rospy import math import traceback import sys import simple_navigation_goals if __name__ == "__main__": try: rospy.init_node("test_scenario") rospy.loginfo("SimpleNavigationGoals Initialization") nav_goals = simple_navigation_goals.SimpleNavigationGoals() rospy.loginfo("Initializations done") # What to do if shut down (e.g. ctrl + C or failure) rospy.on_shutdown(nav_goals._shutdown) while True: rospy.loginfo("Go to -2, 0, 0") if not (nav_goals.go_to(-2, 0, 0)): break rospy.loginfo("Go to 0.5, 0.5, PI/2") if not (nav_goals.go_to(0.5, 0.5, math.pi/2)): break rospy.loginfo("Go to 1.6, -1.6, 0") if not (nav_goals.go_to(1.6, -1.6, 0)): break rospy.spin() except rospy.ROSInterruptException: rospy.logerr(traceback.format_exc()) rospy.loginfo("test terminated.") <file_sep>/scripts/simple_navigation_goals.py #!/usr/bin/env python import rospy import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal import numpy as np class SimpleNavigationGoals: def __init__(self): pass def go_to(self, x, y, theta): client = None client = actionlib.SimpleActionClient('move_base',MoveBaseAction) client.wait_for_server() goal = MoveBaseGoal() goal.target_pose.header.frame_id = "map" goal.target_pose.header.stamp = rospy.Time.now() theta = self.euler_to_quaternion(theta) goal.target_pose.pose.position.x = x goal.target_pose.pose.position.y = y goal.target_pose.pose.position.z = 0 goal.target_pose.pose.orientation.w = theta client.send_goal(goal) wait = client.wait_for_result() if not wait: rospy.logerr("Action server not available!") rospy.signal_shutdown("Action server not available!") else: rospy.loginfo("Done") return client.get_result() def euler_to_quaternion(self, yaw): pitch = 0 roll = 0 qw = np.cos(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.sin(pitch/2) * np.sin(yaw/2) return qw def _shutdown(self): rospy.signal_shutdown("Shutdown!") <file_sep>/README.md # [Simple Navigation Goal](https://github.com/SamuelHuet/simple_navigation_goals) _[![ROS Melodic](https://img.shields.io/badge/ROS-Melodic-red)](http://wiki.ros.org/melodic/Installation/Ubuntu)_ _[![TurtleBot3](https://img.shields.io/badge/TurtleBot-3-brightgreen)](http://emanual.robotis.com/docs/en/platform/turtlebot3/pc_setup/)_ ![LICENSE](https://img.shields.io/badge/LICENSE-Apache%202.0-informational) ![MelodicTurtle](https://raw.githubusercontent.com/ros/ros_tutorials/melodic-devel/turtlesim/images/melodic.png) >The goal of this projet is to succeed a simplified version of the "Carry my luggage" test, imagined by the [RobotCup@Home](https://athome.robocup.org) contest. >For more information about rules and regulations, please refer to [this document](https://robocupathome.github.io/RuleBook/rulebook/master.pdf). - [Simple Navigation Goal](#simple-navigation-goal) - [Prerequisites](#prerequisites) - [Installation](#installation) - [How To](#how-to) - [Usage](#usage) - [Meta](#meta) - [Contributing](#contributing) ## Prerequisites - [Ubuntu 18.0.4 recommended](https://ubuntu.com/download/desktop) - [ROS Melodic](http://wiki.ros.org/melodic/Installation/Ubuntu) - [TurtleBot3](http://emanual.robotis.com/docs/en/platform/turtlebot3/pc_setup/) - [Git](https://git-scm.com/) ## Installation Simply clone this repository on your computer and catkin_make: ``` $ cd ~/catkin_ws/src $ git clone https://github.com/SamuelHuet/simple_navigation_goals.git $ cd .. $ catkin_make ``` ## How To Patrol points tested and working on turtlebot3_world ``` $ rosrun simple_navigation_goals patrouille.py ``` Or you can run in your own python script ``` import simple_navigation_goals rospy.init_node("test_scenario") nav_goals = simple_navigation_goals.SimpleNavigationGoals() nav_goals.go_to(x, y, rad) rospy.on_shutdown(nav_goals._shutdown) rospy.spin() ``` ## Usage The project contains a complete ROS Melodic package with several python scripts. The ``simple_navigation_goals.py`` script is executed with the ``patrouille.py`` script in order to realize all necessary tests required to pass the challenge. In order to pass the test, the TurtleBot have to patrol with three checkpoints. The checkpoints will be drawn randomly but can be modified in order to approach the simulation towards the physical reality. ## Meta Distributed under the Apache 2.0 license. See ``LICENSE`` for more information. ## Contributing 1. Fork it (<https://github.com/SamuelHuet/simple_navigation_goals/fork>) 2. Create your feature branch 3. Commit your changes 4. Push to the branch 5. Create a new Pull Request
03cbe38a99a4caa0f948d0c2fef8fa26cdf210a7
[ "Markdown", "Python" ]
3
Python
Coutanthomas/simple_navigation_goals
7cac77aad70ab308f52ad3662e6811bc05afb187
f409697d5a440cb9c04f7a577a2e550c34f2d49c
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: sauvegarder.h * Author: snir2g1 * * Created on 31 mars 2021, 14:49 */ #ifndef SAUVEGARDER_H #define SAUVEGARDER_H #include "lib/pugixml/src/pugixml.hpp" class sauvegarder { public: sauvegarder(); sauvegarder(const sauvegarder& orig); virtual ~sauvegarder(); bool enregistrerArgument(); private: }; #endif /* SAUVEGARDER_H */ <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: sauvegarder.cpp * Author: snir2g1 * * Created on 31 mars 2021, 14:49 */ #include "sauvegarder.h" sauvegarder::sauvegarder() { } sauvegarder::sauvegarder(const sauvegarder& orig) { } sauvegarder::~sauvegarder() { } bool sauvegarder::enregistrerArgument(){ //pugi::xml_document doc; }<file_sep># # Generated - do not edit! # # NOCDDL # CND_BASEDIR=`pwd` CND_BUILDDIR=build CND_DISTDIR=dist # Debug configuration CND_PLATFORM_Debug=GNU-Linux CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux CND_ARTIFACT_NAME_Debug=maintest CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/maintest CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package CND_PACKAGE_NAME_Debug=maintest.tar CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/maintest.tar # Release configuration CND_PLATFORM_Release=GNU-Linux CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux CND_ARTIFACT_NAME_Release=maintest CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/maintest CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package CND_PACKAGE_NAME_Release=maintest.tar CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/maintest.tar # # include compiler specific variables # # dmake command ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \ (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk) # # gmake command .PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)) # include nbproject/private/Makefile-variables.mk
ae7a52098622ffcd08504165aa4aa53bf2999ce5
[ "Makefile", "C++" ]
3
C++
kisa-josue/projetinit-2-
4db2830580072f9801471cdb2aa9d89ca85b81c9
776644fef649f8fab15ba195a70d8393ad5ff38d
refs/heads/master
<file_sep>package com.categorylist; import java.util.List; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class AbstractCategory { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public abstract void setKeywordsList(List<String> keywordsList); public abstract List<String> getKeywordsList(); public abstract void setCategoryName(String categoryName); public abstract String getCategoryName(); }
222913c7eaded7fd013508f67baf3a9288b7aac0
[ "Java" ]
1
Java
anantkshirsagar/JPADevnagari
337f60e5111878fad6c240d2a7fd034028453f92
e83423176c0d6dc1d29d5ef5228df9eaedbc66e9
refs/heads/master
<file_sep>/* 1. <NAME> MORAJU BITI IDENTICNI KAO U PRIMJERIMA, U SUPROTNOM SE RAD NECE BODOVATI 2. STAVITE KOMENTAR NA DIJELOVE CODE-A KOJE NE BUDETE IMPLEMENTIRALI 3. KREIRAJTE .DOC FAJL SA VASIM BROJEM INDEKSA ( NPR. IB130030.DOC BEZ IMENA I PREZIMENA), TE NA KRAJU ISPITA U NJEGA KOPIRAJTE RJESENJA VASIH ZADATAKA. NE PREDAVATI .CPP FAJLOVE 4. TOKOM IZRADE ISPITA NIJE DOZVOLJENO KORISTENJE HELP-A 5. TOKOM IZRADE ISPITA MOGU BITI POKRENUTA SAMO TRI PROGRAMA: PDF READER (ISPITNI ZADACI), MS VISUAL STUDIO, MS WORD (U KOJI CETE KOPIRATI VASA RJESENJA) 6. BEZ OBZIRA NA TO DA LI SU ISPITNI ZADACI URADJENI, SVI STUDENTI KOJI SU PRISTUPILI ISPITU MORAJU PREDATI SVOJ RAD */ #include<iostream> #include <vector> using namespace std; //narednu liniju code-a ignorisite, osim u slucaju da vam bude predstavljala smetnje u radu #pragma warning(disable:4996) const char *crt = "\n-------------------------------------------\n"; enum vrstaDokumenta { PDF, DOC, TXT, HTML }; const char * vrstaDokumentaChar[] = { "PDF", "DOC", "TXT", "HTML" }; enum Prioritet { VISOK, SREDNJI, NIZAK }; const char * PrioritetChar[] = { "VISOK", "SREDNJI", "NIZAK" }; char * AlocirajNizKaraktera(const char * sadrzaj) { int vel = strlen(sadrzaj) + 1; char * temp = new char[vel]; strcpy_s(temp, vel, sadrzaj); return temp; } const int BROJ_ZNAKOVA_PO_STRANICI = 30; struct DatumVrijeme { int *_dan = 0, *_mjesec = 0, *_godina = 0, *_sati = 0, *_minuti = 0; void Unos(int dan = 1, int mjesec = 1, int godina = 2000, int sati = 1, int minuti = 1) { _dan = new int(dan); _mjesec = new int(mjesec); _godina = new int(godina); _sati = new int(sati); _minuti = new int(minuti); } void Dealociraj() { delete _dan; _dan = nullptr; delete _mjesec; _mjesec = nullptr; delete _godina; _godina = nullptr; delete _sati; _sati = nullptr; delete _minuti; _minuti = nullptr; } void Ispis() { cout << *_dan << "." << *_mjesec << "." << *_godina << " " << *_sati << ":" << *_minuti << endl; } int GetDays() { return *_dan + *_mjesec * 30 + *_godina * 365; } int GetMins() { return *_minuti + *_sati * 60; } }; struct Filter { char * _sadrzaj; Prioritet _prioritet; int timesUsed; void Unos(const char * sadrzaj, Prioritet prioritet) { _sadrzaj = AlocirajNizKaraktera(sadrzaj); _prioritet = prioritet; timesUsed = 0; } void Dealociraj() { delete[] _sadrzaj; _sadrzaj = nullptr; } void Ispis() { cout << _sadrzaj << " (" << PrioritetChar[_prioritet] << ")" << endl; } }; struct Dokument { vrstaDokumenta _vrsta; char * _naziv; char * _sadrzaj; unique_ptr<DatumVrijeme> _kreiran; int _brojStranica; bool passesFilters; void Unos(vrstaDokumenta vrsta, const char * naziv, DatumVrijeme kreiran) { _naziv = AlocirajNizKaraktera(naziv); _vrsta = vrsta; //Moramo koristiti make_unique<DatumVrijeme> jer je gore definisan kao unique_ptr _kreiran = make_unique<DatumVrijeme>(kreiran); _brojStranica = 0;//broj stranica se odredjuje prilikom svakog dodavanja novog sadrzaja dokumentu _sadrzaj = nullptr; passesFilters = false; } void Dealociraj() { delete[] _naziv; _naziv = nullptr; delete[] _sadrzaj; _sadrzaj = nullptr; _kreiran.reset(); } void Ispis() { cout << crt << _naziv << " " << vrstaDokumentaChar[_vrsta] << " kreiran "; _kreiran->Ispis(); cout << crt << _sadrzaj << crt << " br.stranica (" << _brojStranica << ")" << crt; } void DodajSadrzaj(const char * c) { //Ako je trenutni sadržaj prazan, samo čemo alocirati naš novi sadržaj if (_sadrzaj == NULL) { _sadrzaj = AlocirajNizKaraktera(c); return; } //A ako nije prazan, prvo čemo kopirati stari sadržaj u novi temporary char * sa strcpy_s, te dodati novi sadržaj sa strcat_s int newSize = strlen(c) + strlen(_sadrzaj) + 1; char * newSadrzaj = new char[newSize]; strcpy_s(newSadrzaj, newSize, _sadrzaj); strcat_s(newSadrzaj, newSize, c); delete[] _sadrzaj; _sadrzaj = newSadrzaj; _brojStranica = (strlen(_sadrzaj) + strlen(c)) / BROJ_ZNAKOVA_PO_STRANICI; } void Kopiraj(Dokument & d) { _naziv = AlocirajNizKaraktera(d._naziv); _vrsta = d._vrsta; //Moramo koristiti make_unique<DatumVrijeme> jer je gore definisan kao unique_ptr _kreiran = make_unique<DatumVrijeme>(*d._kreiran); _brojStranica = d._brojStranica; passesFilters = d.passesFilters; //Ako u dokumentu kojeg kopiramo ne postoji sadrzaj, onda ga moramo oznaciti kao nullptr if (d._sadrzaj != NULL) _sadrzaj = AlocirajNizKaraktera(d._sadrzaj); else _sadrzaj = nullptr; } }; struct Printer { char * _model; Dokument * _dokumenti; int _trenutnoDokumenata; Filter * _filteri; int _trenutnoFiltera; void Unos(const char * model) { _model = AlocirajNizKaraktera(model); _filteri = nullptr; _dokumenti = nullptr; _trenutnoDokumenata = 0; _trenutnoFiltera = 0; } void Dealociraj() { delete[] _model; _model = nullptr; for (size_t i = 0; i < _trenutnoDokumenata; i++) _dokumenti[i].Dealociraj(); delete[]_dokumenti; _dokumenti = nullptr; for (size_t i = 0; i < _trenutnoFiltera; i++) _filteri[i].Dealociraj(); delete[]_filteri; _filteri = nullptr; } void Ispis() { cout << _model << crt; for (size_t i = 0; i < _trenutnoDokumenata; i++) if (_dokumenti[i].passesFilters) _dokumenti[i].Ispis(); } bool DodajFilter(const char * c, Prioritet p) { //Provjeri je li duplikat for (int i = 0; i < _trenutnoFiltera; i++) { if (strcmp(_filteri[i]._sadrzaj, c) == 0) return false; } //Ako ne, dodaj novi filter tako što češ napraviti novi pointer-array za 1 član veći, te kopirati sve članove iz orginalog pointer-arraya u taj novi, pa ubaciti novi filter Filter * newFilteri = new Filter[_trenutnoFiltera + 1]; for (int i = 0; i < _trenutnoFiltera; i++) { newFilteri[i].Unos(_filteri[i]._sadrzaj, _filteri[i]._prioritet); } newFilteri[_trenutnoFiltera].Unos(c, p); _trenutnoFiltera++; delete[] _filteri; _filteri = new Filter[_trenutnoFiltera]; _filteri = newFilteri; return true; } bool Printaj(Dokument & d) { //Provjeriti je li ime alfanumeričko sa isalpha() defaultnom funkcijom //Ovdje deklarišemo brojač varijablu van for loopa jer je želim koristi dole da provjerim ekstenziju //U ovom ovdje for loopu će ta varijabla prestati kada dođe do znaka '.' int index = 0; for (index; index < strlen(d._naziv) && d._naziv[index] != '.'; index++) { if (!isalpha(d._naziv[index])) return false; } //Provjeriti je li extenzija ista kao definisana na vrhu programa //Ako dužina ekstenzije dokumenta i njene ekstenzije po ._vrsti nije ista, znači da ekstenzija nije ista if (strlen(d._naziv) - index - 1 != strlen(vrstaDokumentaChar[d._vrsta])) return false; //A ako jeste, provjeriti sami tekst extenzije int p = 0; for (index = index + 1; index < strlen(d._naziv); index++) { if (toupper(d._naziv[index]) != vrstaDokumentaChar[d._vrsta][p]) return false; p++; } //Te dodajemo naš dokument u _dokumenti tako što čemo napraviti temporary newDokumenti, u njega kopirati sve članove _dokumenti, te dodati mu naš novi dokument Dokument * newDokumenti = new Dokument[_trenutnoDokumenata + 1]; for (int i = 0; i < _trenutnoDokumenata; i++) { newDokumenti[i].Kopiraj(_dokumenti[i]); } newDokumenti[_trenutnoDokumenata].Kopiraj(d); delete[] _dokumenti; _dokumenti = newDokumenti; _trenutnoDokumenata++; //Ako nema sadržaj, odmah samo printaj if (d._sadrzaj == NULL) return true; //Sada, za filtriranje pravimo jedan niz koji će nam čuvati broj koliko puta se filter kojeg prioriteta nalazi u sadržaju int filterNum[3] = { 0 }; //Napravit čemo temporary string koji sadrži sve isto kao sadržaj, samo u velikim slovima pomoću toupper(), jer su filteri sami velikim slovima napisani a neke //riječi samo počinju velikim slovima char * tempSadrzaj = AlocirajNizKaraktera(d._sadrzaj); for (int i = 0; i < strlen(tempSadrzaj); i++) { tempSadrzaj[i] = toupper(tempSadrzaj[i]); } //Počinjemo loop koji će proči kroz svaki član _filteri i provjeriti da li se nalazi u sadržaju for (int i = 0; i < _trenutnoFiltera; i++) { //char * c nam pokazuje na čitav tempSadrzaj. //Sa njime čemo provjeriti da li se nešto pojavljuje više puta u istom sadržaju, kao neka pseudo-rekurzija. Vidjet češ. char *c = tempSadrzaj; //Ovdje samo dodajem razmak na početak i kraj filtera kako bi hvatalo samo zasebne riječi. To pohranjujemo u char * filter kojeg čemo dalje koristiti dole char *filter = new char[strlen(_filteri[i]._sadrzaj) + 3]; //Jer stvaramo novi char * ručno, moramo mu dodjeliti null terminator na kraju filter[strlen(_filteri[i]._sadrzaj) + 2] = '\0'; filter[0] = filter[strlen(_filteri[i]._sadrzaj) + 1] = ' '; for (int x = 1; x < strlen(_filteri[i]._sadrzaj) + 1; x++) { filter[x] = _filteri[i]._sadrzaj[x-1]; } //Ovdje koristimo strstr() da vidimo koliko puta se filter pojavljuje u tempSadrzaj. //strstr() vraća pokazivač na prvo mjesto gdje se pojavljuje traženi substring, pa čemo baš to mjesto dodjeljivati našem char * c //Prvo provjeravamo da li strstr(c, filter) vraća išta. Ako ne vraća ništa, znači da se substring ne pojavljuje. //Ako vraća, vršimo ga ponovo sve dok se desi da više nema šta da vrati. Svaki put kad pronađe substring, dodajemo +1 na njegov filterNum. while (strstr(c, filter) != nullptr) { filterNum[_filteri[i]._prioritet]++; //Dodjeljujemo strstr(c, filter) c-u, a onda idemo naprijed za toliko slova koliko filter sadrži, kako ne bismo stalno išli u infinite //loop, pronalazeći istu riječ c = strstr(c, filter); c += strlen(filter); } } //Po dole kriterijima filtera, vračamo false ako su ispunjeni if (!(filterNum[0] == 0 && filterNum[1] <= 2 && filterNum[2] <= 3)) return false; //Zato što su prošli filtere, stavit čemo da je njihov passesFilters u _dokumenti true. To će nam trebati za iduće funkcije. _dokumenti[_trenutnoDokumenata - 1].passesFilters = true; //Te na koncu ispisujemo njihov _sadržaj cout << crt; for (int i = 0; i < strlen(d._sadrzaj); i++) { cout << d._sadrzaj[i]; if (i % 30 == 0 && i != 0) cout << crt; } cout << crt; return true; } float GetProsjecanBrojStranicaUPeriodu_Od_Do(DatumVrijeme d1, DatumVrijeme d2, int index = 0, int numStr = 0, int numDokument = 0) { //Gledamo da li je dan unutar granica d1 i d2, i da li dokument prolazi kroz filtere i moze biti printan. Tada dodajemo na numStr njegov broj stranica i povecavamo cifru //dokumenata if (d1.GetDays() <= _dokumenti[index]._kreiran->GetDays() && d2.GetDays() >= _dokumenti[index]._kreiran->GetDays() && _dokumenti[index].passesFilters) { numStr += _dokumenti[index]._brojStranica; numDokument++; } //Ako nismo provjerili sve članove _dokumenti, tj. naš index nije veličine samog niza _dokumenti (-1, jer _trenutnoDokumenata je broj članova, ne index zadnjeg člana) //onda vraćamo istu funkciju rekurzivno, samo sa većim indexom if (index != _trenutnoDokumenata - 1) { return GetProsjecanBrojStranicaUPeriodu_Od_Do(d1, d2, index+1, numStr, numDokument); } //A ako jesmo, ako smo došli do kraja, onda samo vraćamo srednju vrijednost kao float. return (float)numStr / numDokument; } Filter * GetNakoristenijiFilter() { //Self-explanatory, samo tražimo onaj sa najvećim timesUsed i dodjeljujemo njegovu adresu Filter * f-u Filter * f = nullptr; int mostUsed = 0; for (int i = 0; i < _trenutnoFiltera; i++) { if (_filteri[i].timesUsed > mostUsed) { f = &_filteri[i]; mostUsed = _filteri[i].timesUsed; } } return f; } }; int main() { DatumVrijeme prije3Dana; prije3Dana.Unos(3, 2, 2018, 10, 15); DatumVrijeme danas1; danas1.Unos(6, 2, 2018, 10, 15); DatumVrijeme danas2; danas2.Unos(6, 2, 2018, 10, 16); DatumVrijeme za10Dana; za10Dana.Unos(16, 2, 2018, 10, 15); Dokument ispitPRII, ispitMAT, ispitUIT, ispitUITDrugiRok; ispitPRII.Unos(DOC, "ispitPRII.doc", prije3Dana); ispitMAT.Unos(DOC, "ispitMAT.doc", danas1); ispitUIT.Unos(DOC, "ispitUIT.doc", danas2); ispitUITDrugiRok.Unos(PDF, "ispitUITDrugiRok.pdf", za10Dana); /*<NAME> DOKUMENTA SE AUTOMATSKI ODREDJUJE PRILIKOM DODAVANJA SADRZAJA. ZA POTREBE ISPITA PRETPOSTAVLJAMO DA NA JEDNU STRANICU MOZE STATI BROJ_ZNAKOVA_PO_STRANICI ZNAKOVA UKLJUCUJUCI RAZMAKE I DRUGE VRSTE ZNAKOVA*/ ispitPRII.DodajSadrzaj("Programiranje ili racunarsko programiranje (engl. programming) jeste vjestina pomocu koje "); ispitPRII.DodajSadrzaj("korisnik stvara i izvrsava algoritme koristeci odredjene programske jezike da bi ... "); cout << "Broj stranica -> " << ispitPRII._brojStranica << endl; ispitPRII.Ispis();//ISPISUJE SVE PODATKE O DOKUMENTU ispitMAT.DodajSadrzaj("Matematika se razvila iz potrebe da se obavljaju proracuni u trgovini, vrse mjerenja zemljista i predvidjaju "); ispitMAT.DodajSadrzaj("astronomski dogadjaji, i ove tri primjene se mogu dovesti u vezu sa grubom podjelom matematike "); Printer hp3200; hp3200.Unos("HP 3200"); /*PRINTER NECE DOZVOLITI PRINTANJE DOKUMENATA U CIJEM SADRZAJU SE NALAZI NEKA OD ZABRANJENIH RIJECI DEFINISANIH FILTERIMA*/ if (hp3200.DodajFilter("RE", NIZAK)) //VISOK :) cout << "Filter dodan!" << endl; if (hp3200.DodajFilter("RAT", VISOK)) cout << "Filter dodan!" << endl; if (hp3200.DodajFilter("UBITI", VISOK)) cout << "Filter dodan!" << endl; if (hp3200.DodajFilter("MRZITI", SREDNJI)) cout << "Filter dodan!" << endl; if (!hp3200.DodajFilter("MRZITI", SREDNJI))/* ONEMOGUCITI PONAVLJANJE FILTERA, BEZ OBZIRA STO SU RAZLICITOG PRIORITETA*/ cout << "Filter nije dodan!" << endl; /* DA BI PRINTER ISPRINTAO NEKI DOKUMENT MORAJU BITI ZADOVOLJENA SLJEDECA PRAVILA: 1. NAZIV DOKUMENTA MOZE SADRZAVATI SAMO SLOVA, A EKSTENZIJA MOZE BITI IDENTICNA ONOJ DEFINISANOJ VRIJEDNOSCU ATRIBUTA vrstaDokumenta 2. SADRZAJ DOKUMENTA MOZE POSJEDOVATI RIJECI DEFINISANE FILTERIMA, ALI PREMA SLJEDECIM PRAVILIMA: - NITI JEDNU RIJEC OZNACENU FILTEROM PRIORITETA VISOK - NAJVISE 2 RIJECI OZNACENE FILTEROM PRIORITETA SREDNJI - NAJVISE 3 RIJECI OZNACENE FILTEROM PRIORITETA NIZAK UKOLIKO NEKI OD NAVEDENIH USLOVA NIJE ZADOVOLJEN FUNKCIJA PRINTAJ DOKUMENT TREBA SACUVATI U NIZ _dokumenti, ALI TAJ DOKUMENT NE TREBA PRINTATI I FUNKCIJA VRACA FALSE. UKOLIKO DOKUMENT ISPUNJAVA SVE USLOVE ZA PRINTANJE POTREBNO JE NA KONZOLU ISPISATI SADRZAJ DOKUMENTA KOJI SE PRINTA, A SA CRT LINIJOM ODVAJATI STRANICE DOKUMENTA */ if (hp3200.Printaj(ispitPRII)) cout << "Printam -> " << ispitPRII._naziv << endl; if (hp3200.Printaj(ispitMAT)) cout << "Printam -> " << ispitMAT._naziv << endl; if (hp3200.Printaj(ispitUIT)) cout << "Printam -> " << ispitUIT._naziv << endl; if (hp3200.Printaj(ispitUITDrugiRok)) cout << "Printam -> " << ispitUITDrugiRok._naziv << endl; //PROSJECAN BROJ STRANICA = UKUPAN BROJ STRANICA / BROJ PRINTANIH DOKUMENATA //REKURZIVNA FUNKCIJA VRACA PROSJECAN BROJ ISPRINTANIH STRANICA (KOJE SU ZADOVOLJILE POSTAVLJENE FILTERE) U PERIODU OD (npr.prije3Dana) - DO (npr.danas2), UKLJUCUJUCI I TAJ PERIOD cout << "Prosjecan broj printanih stranica je -> " << hp3200.GetProsjecanBrojStranicaUPeriodu_Od_Do(prije3Dana, danas2, 0, 0, 0) << crt; //VRACA SADRZAJ FILTERA KOJI SE NAJCESCE KORISTIO U DOKUMENTIMA Filter * f = hp3200.GetNakoristenijiFilter(); if (f != nullptr && f->_sadrzaj != nullptr) cout << "Najcesce koristeni sadrzaj filtera je -> " << f->_sadrzaj << crt; //PORED VRIJEDNOSTI SVIH OSTALIH ATRIBUTA, ISPISUJE SAMO ONE DOKUMENTE KOJI ZADOVOLJAVAJU SVA PRETHODNO DEFINISANA PRAVILA hp3200.Ispis(); /*NAPISATI LAMBDA FUNKCIJU ZamijeniIPrintaj KOJA U SADRZAJU DOKUMENTA MIJENJA PRVI POSLATI PARAMETAR SA VRIJEDNOSCU DRUGOG PARAMETRA, TE VRACA BROJ ZAMIJENJENIH ZNAKOVA*/ auto ZamijeniIPrintaj = [&hp3200](char c1, char c2, DatumVrijeme d) { //Samo idemo redom po svim dokumentima, i ako naiđemo na jedan sa istim datumom kao argumentom d, a ima sadržaj, onda samo pređemo preko čitavog sadržaja, //zamjenimo c1 sa c2, i svaki put kad to uradimo dodamo +1 na int zamjenjeno. Na koncu vratimo zamjenjeno. int zamjenjeno = 0; for (int i = 0; i < hp3200._trenutnoDokumenata; i++) { if (hp3200._dokumenti[i]._kreiran->GetDays() == d.GetDays() && hp3200._dokumenti[i]._sadrzaj != NULL) { for (int j = 0; j < strlen(hp3200._dokumenti[i]._sadrzaj); j++) { if (hp3200._dokumenti[i]._sadrzaj[j] == c1) { zamjenjeno++; hp3200._dokumenti[i]._sadrzaj[j] = c2; } } } } return zamjenjeno; }; //RAZMAK MIJENJA ZNAKOM CRTICA U SADRZAJU DOKUMENATA KOJI SU PRINTANI danas1 int zamijenjeno = ZamijeniIPrintaj(' ', '-', danas1); cout << "Zamijenjeno -> " << zamijenjeno << " znakova" << endl; hp3200.Ispis(); prije3Dana.Dealociraj(); danas1.Dealociraj(); danas2.Dealociraj(); za10Dana.Dealociraj(); ispitMAT.Dealociraj(); ispitPRII.Dealociraj(); ispitUIT.Dealociraj(); ispitUITDrugiRok.Dealociraj(); hp3200.Dealociraj(); system("PAUSE"); return 0; }<file_sep># fit-pr-ispiti Postavke i rijesenja ispita iz Programiranja na FIT Mostar Hvala emir97 na postavci zadataka. Sve je iskomentarisano =)
b9b431e8b941dca0c05176dc07797e8e51413835
[ "Markdown", "C++" ]
2
C++
Azrynn/fit-pr-ispiti
0c36f712fe2885144f35c0958c5215e73344a8fd
2b811196fe01713db15bfcc4a66853bb537d477a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class LoginDetailsController : ApiController { public IEnumerable<LoginDetail> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.LoginDetails.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.LoginDetails.FirstOrDefault(e => e.ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Login with Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] LoginDetail loginDetail) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.LoginDetails.Add(loginDetail); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, loginDetail); message.Headers.Location = new Uri(Request.RequestUri + loginDetail.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoginDetails.FirstOrDefault(e => e.ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Login with Id " + id.ToString() + " Not Found!"); } else { entities.LoginDetails.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] LoginDetail loginDetail) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoginDetails.FirstOrDefault(e => e.ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Login with Id " + id.ToString() + " Not Found!"); } else { entity.Mail = loginDetail.Mail; entity.Pan = loginDetail.Pan; entity.Pass = loginDetail.Pass; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class StatusController : ApiController { public IEnumerable<Status> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Status.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Status.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Status status) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Status.Add(status); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, status); message.Headers.Location = new Uri(Request.RequestUri + status.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Status.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Status.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Status status) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Status.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Personal_Applied = status.Personal_Applied; entity.Personal_Status = status.Personal_Status; entity.Personal_Correction = status.Personal_Correction; entity.Home_Applied = status.Home_Applied; entity.Home_Status = status.Home_Status; entity.Home_Correction = status.Home_Correction; entity.Education_Applied = status.Education_Applied; entity.Education_Status = status.Education_Status; entity.Education_Correction = status.Education_Correction; entity.Gold_Applied = status.Gold_Applied; entity.Gold_Status = status.Gold_Status; entity.Gold_Correction = status.Gold_Correction; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PurpPersonalController : ApiController { public IEnumerable<PurpPersonal> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.PurpPersonals.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.PurpPersonals.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] PurpPersonal purppersonal) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.PurpPersonals.Add(purppersonal); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, purppersonal); message.Headers.Location = new Uri(Request.RequestUri + purppersonal.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PurpPersonals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.PurpPersonals.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] PurpPersonal purppersonal) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PurpPersonals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Ppu_Reason = purppersonal.Ppu_Reason; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class EmpGoldController : ApiController { public IEnumerable<EmpGold> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.EmpGolds.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.EmpGolds.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] EmpGold empgold) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.EmpGolds.Add(empgold); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, empgold); message.Headers.Location = new Uri(Request.RequestUri + empgold.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EmpGolds.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.EmpGolds.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] EmpGold empgold) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EmpGolds.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Ge_Occ_Type = empgold.Ge_Occ_Type; entity.Ge_Org_Type = empgold.Ge_Org_Type; entity.Ge_Emp_Buss_Name = empgold.Ge_Emp_Buss_Name; entity.Ge_Designation = empgold.Ge_Designation; entity.Ge_Curr_Work_Years = empgold.Ge_Curr_Work_Years; entity.Ge_Total_work_Years = empgold.Ge_Total_work_Years; entity.Ge_Net_Ann_Inc = empgold.Ge_Net_Ann_Inc; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class LoanEduController : ApiController { public IEnumerable<LoanEdu> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.LoanEdus.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.LoanEdus.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] LoanEdu loanedu) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.LoanEdus.Add(loanedu); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, loanedu); message.Headers.Location = new Uri(Request.RequestUri + loanedu.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoanEdus.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.LoanEdus.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] LoanEdu loanedu) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoanEdus.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Edu_Tut_Fees = loanedu.Edu_Tut_Fees; entity.Edu_Living_Expen = loanedu.Edu_Living_Expen; entity.Edu_Travel_Expen = loanedu.Edu_Travel_Expen; entity.Edu_Other_Expen = loanedu.Edu_Other_Expen; entity.Edu_Total_Expen = loanedu.Edu_Total_Expen; entity.Edu_Own_Inc = loanedu.Edu_Own_Inc; entity.Edu_Scholar_Inc = loanedu.Edu_Scholar_Inc; entity.Edu_Other_Inc = loanedu.Edu_Other_Inc; entity.Edu_Loan_Required = loanedu.Edu_Loan_Required; entity.Edu_Disburs_Details = loanedu.Edu_Disburs_Details; entity.Edu_Mode = loanedu.Edu_Mode; entity.Edu_Dd_In_Favour_Of = loanedu.Edu_Dd_In_Favour_Of; entity.Edu_Payable_At_For = loanedu.Edu_Payable_At_For; entity.Edu_DD_Amount = loanedu.Edu_DD_Amount; entity.Edu_Tt_Swift_Code = loanedu.Edu_Tt_Swift_Code; entity.Edu_Rtgs_Neft = loanedu.Edu_Rtgs_Neft; entity.Edu_University_Ac = loanedu.Edu_University_Ac; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class LoanDetailsController : ApiController { public IEnumerable<LoginDetail> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.LoginDetails.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.LoginDetails.FirstOrDefault(e => e.ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Data with Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] LoanDetail loandetail) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.LoanDetails.Add(loandetail); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, loandetail); message.Headers.Location = new Uri(Request.RequestUri + loandetail.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoanDetails.FirstOrDefault(e => e.ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data with Id " + id.ToString() + " Not Found!"); } else { entities.LoanDetails.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] LoanDetail loandetail) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.LoanDetails.FirstOrDefault(e => e.ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data with Id " + id.ToString() + " Not Found!"); } else { entity.Personal_Interest_Rate = loandetail.Personal_Interest_Rate; entity.Personal_Loan_Tenure = loandetail.Personal_Loan_Tenure; entity.Personal_Loan_Amount = loandetail.Personal_Loan_Amount; entity.Personal_Processing_Fees = loandetail.Personal_Processing_Fees; entity.Education_Interest_Rate = loandetail.Education_Interest_Rate; entity.Education_Loan_Type = loandetail.Education_Loan_Type; entity.Education_Loan_Amount = loandetail.Education_Loan_Amount; entity.Education_Concession = loandetail.Education_Concession; entity.Home_InterestRate_1 = loandetail.Home_InterestRate_1; entity.Home_InterestRate_2 = loandetail.Home_InterestRate_2; entity.Home_InterestRate_3 = loandetail.Home_InterestRate_3; entity.Home_Processing_Fees = loandetail.Home_Processing_Fees; entity.Gold_Min_Loan = loandetail.Gold_Min_Loan; entity.Gold_Max_Loan = loandetail.Gold_Max_Loan; entity.Gold_Margin = loandetail.Gold_Margin; entity.Gold_Processing_Fees = loandetail.Gold_Processing_Fees; entity.Clients = loandetail.Clients; entity.Loan_Approved = loandetail.Loan_Approved; entity.Hours_Support = loandetail.Hours_Support; entity.Hard_Workers = loandetail.Hard_Workers; entity.Trusty_City = loandetail.Trusty_City; entity.Trusty_State = loandetail.Trusty_State; entity.Trusty_Country = loandetail.Trusty_Country; entity.Trusty_Mail = loandetail.Trusty_Mail; entity.Trusty_Phone = loandetail.Trusty_Phone; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class EduAppDocController : ApiController { public IEnumerable<EduAppDoc> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.EduAppDocs.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.EduAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] EduAppDoc eduappdoc) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.EduAppDocs.Add(eduappdoc); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, eduappdoc); message.Headers.Location = new Uri(Request.RequestUri + eduappdoc.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.EduAppDocs.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] EduAppDoc eduappdoc) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Doc1_Name = eduappdoc.Doc1_Name; entity.Doc1 = eduappdoc.Doc1; entity.Doc2_Name = eduappdoc.Doc2_Name; entity.Doc2 = eduappdoc.Doc2; entity.Doc3_Name = eduappdoc.Doc3_Name; entity.Doc3 = eduappdoc.Doc3; entity.Doc4_Name = eduappdoc.Doc4_Name; entity.Doc4 = eduappdoc.Doc4; entity.Doc5_Name = eduappdoc.Doc5_Name; entity.Doc5 = eduappdoc.Doc5; entity.Doc6_Name = eduappdoc.Doc6_Name; entity.Doc6 = eduappdoc.Doc6; entity.Doc7_Name = eduappdoc.Doc7_Name; entity.Doc7 = eduappdoc.Doc7; entity.Doc8_Name = eduappdoc.Doc8_Name; entity.Doc8 = eduappdoc.Doc8; entity.Doc9_Name = eduappdoc.Doc9_Name; entity.Doc9 = eduappdoc.Doc9; entity.Doc10_Name = eduappdoc.Doc10_Name; entity.Doc10 = eduappdoc.Doc10; entity.Doc11_Name = eduappdoc.Doc11_Name; entity.Doc11 = eduappdoc.Doc11; entity.Doc12_Name = eduappdoc.Doc12_Name; entity.Doc12 = eduappdoc.Doc12; entity.Doc13_Name = eduappdoc.Doc13_Name; entity.Doc13 = eduappdoc.Doc13; entity.Doc14_Name = eduappdoc.Doc14_Name; entity.Doc14 = eduappdoc.Doc14; entity.Doc15_Name = eduappdoc.Doc15_Name; entity.Doc15 = eduappdoc.Doc15; entity.Doc16_Name = eduappdoc.Doc16_Name; entity.Doc16 = eduappdoc.Doc16; entity.Doc17_Name = eduappdoc.Doc17_Name; entity.Doc17 = eduappdoc.Doc17; entity.Doc18_Name = eduappdoc.Doc18_Name; entity.Doc18 = eduappdoc.Doc18; entity.Doc19_Name = eduappdoc.Doc19_Name; entity.Doc19 = eduappdoc.Doc19; entity.Doc20_Name = eduappdoc.Doc20_Name; entity.Doc20 = eduappdoc.Doc20; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class ReferenceController : ApiController { public IEnumerable<Reference> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.References.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.References.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Reference reference) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.References.Add(reference); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, reference); message.Headers.Location = new Uri(Request.RequestUri + reference.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.References.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.References.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Reference reference) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.References.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Ref_Name1 = reference.Ref_Name1; entity.Ref_Relat1 = reference.Ref_Relat1; entity.Ref_Addr1 = reference.Ref_Addr1; entity.Ref_Pin1 = reference.Ref_Pin1; entity.Ref_City1 = reference.Ref_City1; entity.Ref_State1 = reference.Ref_State1; entity.Ref_Country1 = reference.Ref_Country1; entity.Ref_Mob_Tel1 = reference.Ref_Mob_Tel1; entity.Ref_Email1 = reference.Ref_Email1; entity.Ref_Name2 = reference.Ref_Name2; entity.Ref_Relat2 = reference.Ref_Relat2; entity.Ref_Addr2 = reference.Ref_Addr2; entity.Ref_Pin2 = reference.Ref_Pin2; entity.Ref_City2 = reference.Ref_City2; entity.Ref_State2 = reference.Ref_State2; entity.Ref_Country2 = reference.Ref_Country2; entity.Ref_Mob_Tel2 = reference.Ref_Mob_Tel2; entity.Ref_Email2 = reference.Ref_Email2; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class DeclarController : ApiController { public IEnumerable<Declar> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Declars.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Declars.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Declar declar) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Declars.Add(declar); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, declar); message.Headers.Location = new Uri(Request.RequestUri + declar.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Declars.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Declars.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Declar declar) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Declars.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Dec_Place = declar.Dec_Place; entity.Dec_Date = declar.Dec_Date; entity.Dec_App_Photo = declar.Dec_App_Photo; entity.Dec_App_Sign = declar.Dec_App_Sign; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PropPersonalController : ApiController { public IEnumerable<PropPersonal> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.PropPersonals.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.PropPersonals.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] PropPersonal proppersonal) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.PropPersonals.Add(proppersonal); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, proppersonal); message.Headers.Location = new Uri(Request.RequestUri + proppersonal.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropPersonals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.PropPersonals.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] PropPersonal proppersonal) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropPersonals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Ppr_Amount = proppersonal.Ppr_Amount; entity.Ppr_Terms = proppersonal.Ppr_Terms; entity.Ppr_Proces_Fee = proppersonal.Ppr_Proces_Fee; entity.Ppr_Roi = proppersonal.Ppr_Roi; entity.Ppr_Repayt_Mode = proppersonal.Ppr_Repayt_Mode; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PropGoldController : ApiController { public IEnumerable<PropGold> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.PropGolds.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.PropGolds.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "PropGold with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] PropGold propGold) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.PropGolds.Add(propGold); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, propGold); message.Headers.Location = new Uri(Request.RequestUri + propGold.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropGolds.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "PropGold with P_Id " + id.ToString() + " Not Found!"); } else { entities.PropGolds.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] PropGold propGold) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropGolds.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "PropGold with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Gpr_Loan_Amount = propGold.Gpr_Loan_Amount; entity.Gpr_Tenure_Months = propGold.Gpr_Tenure_Months; entity.Gpr_Payment_Date = propGold.Gpr_Payment_Date; entity.Gpr_Int_Pay_Mode = propGold.Gpr_Int_Pay_Mode; entity.Gpr_Disburs_Mode = propGold.Gpr_Disburs_Mode; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class NomineeController : ApiController { public IEnumerable<Nominee> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Nominees.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Nominees.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Nominee nominee) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Nominees.Add(nominee); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, nominee); message.Headers.Location = new Uri(Request.RequestUri + nominee.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Nominees.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Nominees.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Nominee nominee) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Nominees.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Nom_App_Name = nominee.Nom_App_Name; entity.Nom_App_Addr = nominee.Nom_App_Addr; entity.Nom_Name = nominee.Nom_Name; entity.Nom_Addr = nominee.Nom_Addr; entity.Nom_Relation = nominee.Nom_Relation; entity.Nom_Age = nominee.Nom_Age; entity.Nom_Dob = nominee.Nom_Dob; entity.Nom_Guar_Name = nominee.Nom_Guar_Name; entity.Nom_Guar_Age = nominee.Nom_Guar_Age; entity.Nom_Guar_Addr = nominee.Nom_Guar_Addr; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PersonalAppDocController : ApiController { public IEnumerable<PersonalAppDoc> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.PersonalAppDocs.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.PersonalAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] PersonalAppDoc personalappdoc) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.PersonalAppDocs.Add(personalappdoc); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, personalappdoc); message.Headers.Location = new Uri(Request.RequestUri + personalappdoc.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PersonalAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.PersonalAppDocs.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] PersonalAppDoc personalappdoc) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PersonalAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Doc1_Name = personalappdoc.Doc1_Name; entity.Doc1 = personalappdoc.Doc1; entity.Doc2_Name = personalappdoc.Doc2_Name; entity.Doc2 = personalappdoc.Doc2; entity.Doc3_Name = personalappdoc.Doc3_Name; entity.Doc3 = personalappdoc.Doc3; entity.Doc4_Name = personalappdoc.Doc4_Name; entity.Doc4 = personalappdoc.Doc4; entity.Doc5_Name = personalappdoc.Doc5_Name; entity.Doc5 = personalappdoc.Doc5; entity.Doc6_Name = personalappdoc.Doc6_Name; entity.Doc6 = personalappdoc.Doc6; entity.Doc7_Name = personalappdoc.Doc7_Name; entity.Doc7 = personalappdoc.Doc7; entity.Doc8_Name = personalappdoc.Doc8_Name; entity.Doc8 = personalappdoc.Doc8; entity.Doc9_Name = personalappdoc.Doc9_Name; entity.Doc9 = personalappdoc.Doc9; entity.Doc10_Name = personalappdoc.Doc10_Name; entity.Doc10 = personalappdoc.Doc10; entity.Doc11_Name = personalappdoc.Doc11_Name; entity.Doc11 = personalappdoc.Doc11; entity.Doc12_Name = personalappdoc.Doc12_Name; entity.Doc12 = personalappdoc.Doc12; entity.Doc13_Name = personalappdoc.Doc13_Name; entity.Doc13 = personalappdoc.Doc13; entity.Doc14_Name = personalappdoc.Doc14_Name; entity.Doc14 = personalappdoc.Doc14; entity.Doc15_Name = personalappdoc.Doc15_Name; entity.Doc15 = personalappdoc.Doc15; entity.Doc16_Name = personalappdoc.Doc16_Name; entity.Doc16 = personalappdoc.Doc16; entity.Doc17_Name = personalappdoc.Doc17_Name; entity.Doc17 = personalappdoc.Doc17; entity.Doc18_Name = personalappdoc.Doc18_Name; entity.Doc18 = personalappdoc.Doc18; entity.Doc19_Name = personalappdoc.Doc19_Name; entity.Doc19 = personalappdoc.Doc19; entity.Doc20_Name = personalappdoc.Doc20_Name; entity.Doc20 = personalappdoc.Doc20; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class FinancialController : ApiController { public IEnumerable<Financial> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Financials.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Financials.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Financial financial) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Financials.Add(financial); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, financial); message.Headers.Location = new Uri(Request.RequestUri + financial.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Financials.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Financials.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Financial financial) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Financials.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Fin_Status = financial.Fin_Status; entity.Fin_Inc_Gross = financial.Fin_Inc_Gross; entity.Fin_Inc_Net = financial.Fin_Inc_Net; entity.Fin_Inc_Othr = financial.Fin_Inc_Othr; entity.Fin_Inc_Total = financial.Fin_Inc_Total; entity.Fin_Bank1_Name = financial.Fin_Bank1_Name; entity.Fin_Bank1_Branch = financial.Fin_Bank1_Branch; entity.Fin_Bank1_Ac_Type = financial.Fin_Bank1_Ac_Type; entity.Fin_Bank1_Ac_No = financial.Fin_Bank1_Ac_No; entity.Fin_Bank2_Name = financial.Fin_Bank2_Name; entity.Fin_Bank2_Branch = financial.Fin_Bank2_Branch; entity.Fin_Bank2_Ac_Type = financial.Fin_Bank2_Ac_Type; entity.Fin_Bank2_Ac_No = financial.Fin_Bank2_Ac_No; entity.Fin_Deposits_Inv = financial.Fin_Deposits_Inv; entity.Fin_Shares_Inv = financial.Fin_Shares_Inv; entity.Fin_Insurance_Inv = financial.Fin_Insurance_Inv; entity.Fin_Mutual_Funds_Inv = financial.Fin_Mutual_Funds_Inv; entity.Fin_Others_Inv = financial.Fin_Others_Inv; entity.Fin_Total_Inv = financial.Fin_Total_Inv; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class NriController : ApiController { public IEnumerable<Nri> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Nris.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Nris.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Nri nri) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Nris.Add(nri); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, nri); message.Headers.Location = new Uri(Request.RequestUri + nri.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Nris.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Nris.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Nri nri) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Nris.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Nri_Country_Name = nri.Nri_Country_Name; entity.Nri_Country_Code = nri.Nri_Country_Code; entity.Nri_Tax_Resid = nri.Nri_Tax_Resid; entity.Nri_Jurid_Resid = nri.Nri_Jurid_Resid; entity.Nri_Tin = nri.Nri_Tin; entity.Nri_Birth_Country = nri.Nri_Birth_Country; entity.Nri_Birth_City = nri.Nri_Birth_City; entity.Nri_Jur_Addr = nri.Nri_Jur_Addr; entity.Nri_City = nri.Nri_City; entity.Nri_State = nri.Nri_State; entity.Nri_Zip_Post_Code = nri.Nri_Zip_Post_Code; entity.Nri_Iso = nri.Nri_Iso; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PropertyController : ApiController { public IEnumerable<Property> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Properties.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Properties.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Property property) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Properties.Add(property); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, property); message.Headers.Location = new Uri(Request.RequestUri + property.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Properties.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Properties.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Property property) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Properties.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Ag_Prop_Type = property.Ag_Prop_Type; entity.Ag_Prop_Classif = property.Ag_Prop_Classif; entity.Ag_Building_Age = property.Ag_Building_Age; entity.Ag_Market_Value = property.Ag_Market_Value; entity.Ag_Regis_Value = property.Ag_Regis_Value; entity.Ag_Prop_Land_Area = property.Ag_Prop_Land_Area; entity.Ag_Buildup_Area = property.Ag_Buildup_Area; entity.Ag_Prop_Addr = property.Ag_Prop_Addr; entity.Ag_Landmark = property.Ag_Landmark; entity.Ag_Pin = property.Ag_Pin; entity.Ag_City = property.Ag_City; entity.Ag_State = property.Ag_State; entity.Ag_Country = property.Ag_Country; entity.Ag_Rev_Mortage = property.Ag_Rev_Mortage; entity.Ag_Lumpsum_Amount = property.Ag_Lumpsum_Amount; entity.Ag_Annuity_Periodicity = property.Ag_Annuity_Periodicity; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class GoldAppDocController : ApiController { public IEnumerable<GoldAppDoc> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.GoldAppDocs.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.GoldAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] GoldAppDoc goldappdoc) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.GoldAppDocs.Add(goldappdoc); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, goldappdoc); message.Headers.Location = new Uri(Request.RequestUri + goldappdoc.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.GoldAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.GoldAppDocs.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] GoldAppDoc goldappdoc) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.GoldAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Doc1_Name = goldappdoc.Doc1_Name; entity.Doc1 = goldappdoc.Doc1; entity.Doc2_Name = goldappdoc.Doc2_Name; entity.Doc2 = goldappdoc.Doc2; entity.Doc3_Name = goldappdoc.Doc3_Name; entity.Doc3 = goldappdoc.Doc3; entity.Doc4_Name = goldappdoc.Doc4_Name; entity.Doc4 = goldappdoc.Doc4; entity.Doc5_Name = goldappdoc.Doc5_Name; entity.Doc5 = goldappdoc.Doc5; entity.Doc6_Name = goldappdoc.Doc6_Name; entity.Doc6 = goldappdoc.Doc6; entity.Doc7_Name = goldappdoc.Doc7_Name; entity.Doc7 = goldappdoc.Doc7; entity.Doc8_Name = goldappdoc.Doc8_Name; entity.Doc8 = goldappdoc.Doc8; entity.Doc9_Name = goldappdoc.Doc9_Name; entity.Doc9 = goldappdoc.Doc9; entity.Doc10_Name = goldappdoc.Doc10_Name; entity.Doc10 = goldappdoc.Doc10; entity.Doc11_Name = goldappdoc.Doc11_Name; entity.Doc11 = goldappdoc.Doc11; entity.Doc12_Name = goldappdoc.Doc12_Name; entity.Doc12 = goldappdoc.Doc12; entity.Doc13_Name = goldappdoc.Doc13_Name; entity.Doc13 = goldappdoc.Doc13; entity.Doc14_Name = goldappdoc.Doc14_Name; entity.Doc14 = goldappdoc.Doc14; entity.Doc15_Name = goldappdoc.Doc15_Name; entity.Doc15 = goldappdoc.Doc15; entity.Doc16_Name = goldappdoc.Doc16_Name; entity.Doc16 = goldappdoc.Doc16; entity.Doc17_Name = goldappdoc.Doc17_Name; entity.Doc17 = goldappdoc.Doc17; entity.Doc18_Name = goldappdoc.Doc18_Name; entity.Doc18 = goldappdoc.Doc18; entity.Doc19_Name = goldappdoc.Doc19_Name; entity.Doc19 = goldappdoc.Doc19; entity.Doc20_Name = goldappdoc.Doc20_Name; entity.Doc20 = goldappdoc.Doc20; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class EduCourseController : ApiController { public IEnumerable<EduCourse> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.EduCourses.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.EduCourses.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] EduCourse educourse) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.EduCourses.Add(educourse); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, educourse); message.Headers.Location = new Uri(Request.RequestUri + educourse.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduCourses.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.EduCourses.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] EduCourse educourse) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduCourses.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.St_Ssc_Inst = educourse.St_Ssc_Inst; entity.St_Ssc_Year = educourse.St_Ssc_Year; entity.St_Ssc_Per = educourse.St_Ssc_Per; entity.St_Ssc_Class = educourse.St_Ssc_Class; entity.St_Ssc_Money_Won = educourse.St_Ssc_Money_Won; entity.St_Hsc_Inst = educourse.St_Hsc_Inst; entity.St_Hsc_Year = educourse.St_Hsc_Year; entity.St_Hsc_Per = educourse.St_Hsc_Per; entity.St_Hsc_Class = educourse.St_Hsc_Class; entity.St_Hsc_Money_Won = educourse.St_Hsc_Money_Won; entity.St_LD_Inst = educourse.St_LD_Inst; entity.St_LD_Year = educourse.St_LD_Year; entity.St_LD_Per = educourse.St_LD_Per; entity.St_LD_Class = educourse.St_LD_Class; entity.St_LD_Money_Won = educourse.St_LD_Money_Won; entity.St_Exam_Score = educourse.St_Exam_Score; entity.St_College_Details = educourse.St_College_Details; entity.St_City = educourse.St_City; entity.St_State = educourse.St_State; entity.St_District = educourse.St_District; entity.St_Pin_Code = educourse.St_Pin_Code; entity.St_Country = educourse.St_Country; entity.St_Admission_Status = educourse.St_Admission_Status; entity.St_Univ_Name = educourse.St_Univ_Name; entity.St_Univ_Person = educourse.St_Univ_Person; entity.St_Course_Name = educourse.St_Course_Name; entity.St_Course_Appr = educourse.St_Course_Appr; entity.St_Admsn = educourse.St_Admsn; entity.St_Course_Cat = educourse.St_Course_Cat; entity.St_Course_Type = educourse.St_Course_Type; entity.St_Course_Start = educourse.St_Course_Start; entity.St_Course_End = educourse.St_Course_End; entity.St_Morat1 = educourse.St_Morat1; entity.St_Morat2 = educourse.St_Morat2; entity.St_Total_Morat = educourse.St_Total_Morat; entity.St_Emi_Repay = educourse.St_Emi_Repay; entity.St_Loan_Period = educourse.St_Loan_Period; entity.St_Int_Serv = educourse.St_Int_Serv; entity.St_Exp_Income = educourse.St_Exp_Income; entity.St_Clg_Name = educourse.St_Clg_Name; entity.St_Course_Persuid = educourse.St_Course_Persuid; entity.St_Compl_Date = educourse.St_Compl_Date; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class HomeController : ApiController { public IEnumerable<Home> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Homes.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Homes.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Home home) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Homes.Add(home); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, home); message.Headers.Location = new Uri(Request.RequestUri + home.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Homes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Homes.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Home home) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Homes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Prop_Type = home.Prop_Type; entity.Prop_Trans_Type = home.Prop_Trans_Type; entity.Prop_Builder_Name = home.Prop_Builder_Name; entity.Prop_Project_Name = home.Prop_Project_Name; entity.Prop_Building_Name = home.Prop_Building_Name; entity.Prop_Land_Area = home.Prop_Land_Area; entity.Prop_Cost = home.Prop_Cost; entity.Prop_Addr = home.Prop_Addr; entity.Prop_Landmark = home.Prop_Landmark; entity.Prop_Pin = home.Prop_Pin; entity.Prop_City = home.Prop_City; entity.Prop_State = home.Prop_State; entity.Prop_Country = home.Prop_Country; entity.Prop_Ownership = home.Prop_Ownership; entity.Prop_Seller_Name = home.Prop_Seller_Name; entity.Prop_Seller_Addr = home.Prop_Seller_Addr; entity.Prop_Const_Stage = home.Prop_Const_Stage; entity.Prop_Pur_Con_Cost = home.Prop_Pur_Con_Cost; entity.Prop_Reg_Cost = home.Prop_Reg_Cost; entity.Prop_Total_Cost = home.Prop_Total_Cost; entity.Prop_Stamp_Cost = home.Prop_Stamp_Cost; entity.Prop_Other_Cost = home.Prop_Other_Cost; entity.Prop_Own_Contrib = home.Prop_Own_Contrib; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class EduCoDocController : ApiController { public IEnumerable<EduCoDoc> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.EduCoDocs.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.EduCoDocs.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] EduCoDoc educodoc) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.EduCoDocs.Add(educodoc); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, educodoc); message.Headers.Location = new Uri(Request.RequestUri + educodoc.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduCoDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.EduCoDocs.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] EduCoDoc educodoc) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EduCoDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Doc1_Name = educodoc.Doc1_Name; entity.Doc1 = educodoc.Doc1; entity.Doc2_Name = educodoc.Doc2_Name; entity.Doc2 = educodoc.Doc2; entity.Doc3_Name = educodoc.Doc3_Name; entity.Doc3 = educodoc.Doc3; entity.Doc4_Name = educodoc.Doc4_Name; entity.Doc4 = educodoc.Doc4; entity.Doc5_Name = educodoc.Doc5_Name; entity.Doc5 = educodoc.Doc5; entity.Doc6_Name = educodoc.Doc6_Name; entity.Doc6 = educodoc.Doc6; entity.Doc7_Name = educodoc.Doc7_Name; entity.Doc7 = educodoc.Doc7; entity.Doc8_Name = educodoc.Doc8_Name; entity.Doc8 = educodoc.Doc8; entity.Doc9_Name = educodoc.Doc9_Name; entity.Doc9 = educodoc.Doc9; entity.Doc10_Name = educodoc.Doc10_Name; entity.Doc10 = educodoc.Doc10; entity.Doc11_Name = educodoc.Doc11_Name; entity.Doc11 = educodoc.Doc11; entity.Doc12_Name = educodoc.Doc12_Name; entity.Doc12 = educodoc.Doc12; entity.Doc13_Name = educodoc.Doc13_Name; entity.Doc13 = educodoc.Doc13; entity.Doc14_Name = educodoc.Doc14_Name; entity.Doc14 = educodoc.Doc14; entity.Doc15_Name = educodoc.Doc15_Name; entity.Doc15 = educodoc.Doc15; entity.Doc16_Name = educodoc.Doc16_Name; entity.Doc16 = educodoc.Doc16; entity.Doc17_Name = educodoc.Doc17_Name; entity.Doc17 = educodoc.Doc17; entity.Doc18_Name = educodoc.Doc18_Name; entity.Doc18 = educodoc.Doc18; entity.Doc19_Name = educodoc.Doc19_Name; entity.Doc19 = educodoc.Doc19; entity.Doc20_Name = educodoc.Doc20_Name; entity.Doc20 = educodoc.Doc20; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class HomeAppDocController : ApiController { public IEnumerable<HomeAppDoc> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.HomeAppDocs.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.HomeAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] HomeAppDoc homeappdoc) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.HomeAppDocs.Add(homeappdoc); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, homeappdoc); message.Headers.Location = new Uri(Request.RequestUri + homeappdoc.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.HomeAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.HomeAppDocs.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] HomeAppDoc homeappdoc) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.HomeAppDocs.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Doc1_Name = homeappdoc.Doc1_Name; entity.Doc1 = homeappdoc.Doc1; entity.Doc2_Name = homeappdoc.Doc2_Name; entity.Doc2 = homeappdoc.Doc2; entity.Doc3_Name = homeappdoc.Doc3_Name; entity.Doc3 = homeappdoc.Doc3; entity.Doc4_Name = homeappdoc.Doc4_Name; entity.Doc4 = homeappdoc.Doc4; entity.Doc5_Name = homeappdoc.Doc5_Name; entity.Doc5 = homeappdoc.Doc5; entity.Doc6_Name = homeappdoc.Doc6_Name; entity.Doc6 = homeappdoc.Doc6; entity.Doc7_Name = homeappdoc.Doc7_Name; entity.Doc7 = homeappdoc.Doc7; entity.Doc8_Name = homeappdoc.Doc8_Name; entity.Doc8 = homeappdoc.Doc8; entity.Doc9_Name = homeappdoc.Doc9_Name; entity.Doc9 = homeappdoc.Doc9; entity.Doc10_Name = homeappdoc.Doc10_Name; entity.Doc10 = homeappdoc.Doc10; entity.Doc11_Name = homeappdoc.Doc11_Name; entity.Doc11 = homeappdoc.Doc11; entity.Doc12_Name = homeappdoc.Doc12_Name; entity.Doc12 = homeappdoc.Doc12; entity.Doc13_Name = homeappdoc.Doc13_Name; entity.Doc13 = homeappdoc.Doc13; entity.Doc14_Name = homeappdoc.Doc14_Name; entity.Doc14 = homeappdoc.Doc14; entity.Doc15_Name = homeappdoc.Doc15_Name; entity.Doc15 = homeappdoc.Doc15; entity.Doc16_Name = homeappdoc.Doc16_Name; entity.Doc16 = homeappdoc.Doc16; entity.Doc17_Name = homeappdoc.Doc17_Name; entity.Doc17 = homeappdoc.Doc17; entity.Doc18_Name = homeappdoc.Doc18_Name; entity.Doc18 = homeappdoc.Doc18; entity.Doc19_Name = homeappdoc.Doc19_Name; entity.Doc19 = homeappdoc.Doc19; entity.Doc20_Name = homeappdoc.Doc20_Name; entity.Doc20 = homeappdoc.Doc20; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class EmpEduHomeController : ApiController { public IEnumerable<EmpEduHome> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.EmpEduHomes.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.EmpEduHomes.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] EmpEduHome empeduhome) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.EmpEduHomes.Add(empeduhome); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, empeduhome); message.Headers.Location = new Uri(Request.RequestUri + empeduhome.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EmpEduHomes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.EmpEduHomes.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] EmpEduHome empeduhome) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.EmpEduHomes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Org_Res_Own = empeduhome.Org_Res_Own; entity.Org_Employment_Nat = empeduhome.Org_Employment_Nat; entity.Org_Nat = empeduhome.Org_Nat; entity.Org_Emp_Busi_Nat = empeduhome.Org_Emp_Busi_Nat; entity.Org_Designation = empeduhome.Org_Designation; entity.Org_Current_Year = empeduhome.Org_Current_Year; entity.Org_Total_Year = empeduhome.Org_Total_Year; entity.Org_Name = empeduhome.Org_Name; entity.Org_Address = empeduhome.Org_Address; entity.Org_Pin = empeduhome.Org_Pin; entity.Org_City = empeduhome.Org_City; entity.Org_State = empeduhome.Org_State; entity.Org_Country = empeduhome.Org_Country; entity.Org_Phone = empeduhome.Org_Phone; entity.Org_UAN = empeduhome.Org_UAN; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PersonalController : ApiController { public IEnumerable<Personal> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Personals.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Personals.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Personal personal) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Personals.Add(personal); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, personal); message.Headers.Location = new Uri(Request.RequestUri + personal.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Personals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Personals.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Personal personal) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Personals.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.App_Name = personal.App_Name; entity.App_Fath_Spou_Name = personal.App_Fath_Spou_Name; entity.App_Mother_Name = personal.App_Mother_Name; entity.App_Status = personal.App_Status; entity.App_Pan = personal.App_Pan; entity.App_Doc_Type = personal.App_Doc_Type; entity.App_Doc_No = personal.App_Doc_No; entity.App_Doc_Exp = personal.App_Doc_Exp; entity.App_Ckyc_No = personal.App_Ckyc_No; entity.App_Dob = personal.App_Dob; entity.App_Gender = personal.App_Gender; entity.App_Nationality = personal.App_Nationality; entity.App_Religion = personal.App_Religion; entity.App_Category = personal.App_Category; entity.App_Disability = personal.App_Disability; entity.App_Education = personal.App_Education; entity.App_Marital_Status = personal.App_Marital_Status; entity.App_Dependants_No = personal.App_Dependants_No; entity.App_Email = personal.App_Email; entity.App_Off_Email = personal.App_Off_Email; entity.App_Telephone = personal.App_Telephone; entity.App_Mobile = personal.App_Mobile; entity.App_Pre_Addr = personal.App_Pre_Addr; entity.App_Pre_Landmark = personal.App_Pre_Landmark; entity.App_Pre_Pin = personal.App_Pre_Pin; entity.App_Pre_City = personal.App_Pre_City; entity.App_Pre_State = personal.App_Pre_State; entity.App_Per_Addr = personal.App_Per_Addr; entity.App_Per_Landmark = personal.App_Per_Landmark; entity.App_Per_Pin = personal.App_Per_Pin; entity.App_Per_City = personal.App_Per_City; entity.App_Per_State = personal.App_Per_State; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class PropHomeController : ApiController { public IEnumerable<PropHome> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.PropHomes.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.PropHomes.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] PropHome prophome) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.PropHomes.Add(prophome); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, prophome); message.Headers.Location = new Uri(Request.RequestUri + prophome.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropHomes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.PropHomes.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] PropHome prophome) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.PropHomes.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.Pr_Loan_For = prophome.Pr_Loan_For; entity.Pr_Amount = prophome.Pr_Amount; entity.Pr_Terms = prophome.Pr_Terms; entity.Pr_Loan_Purpose = prophome.Pr_Loan_Purpose; entity.Pr_Loan_Prod_Categ = prophome.Pr_Loan_Prod_Categ; entity.Pr_Repay_Mode = prophome.Pr_Repay_Mode; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using LoanDataAccess; namespace MajorWebApi.Controllers { public class GstinController : ApiController { public IEnumerable<Gstin> Get() { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; return entities.Gstins.ToList(); } } public HttpResponseMessage Get(int id) { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; var entity = entities.Gstins.FirstOrDefault(e => e.P_ID == id); if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, message: "Person with P_Id " + id.ToString() + " Not Found!"); } } } public HttpResponseMessage Post([FromBody] Gstin gstin) { try { using (loandbEntities entities = new loandbEntities()) { entities.Configuration.ProxyCreationEnabled = false; entities.Gstins.Add(gstin); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, gstin); message.Headers.Location = new Uri(Request.RequestUri + gstin.ID.ToString()); return message; } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Delete(int id) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Gstins.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entities.Gstins.Remove(entity); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } public HttpResponseMessage Put(int id, [FromBody] Gstin gstin) { try { using (loandbEntities entities = new loandbEntities()) { var entity = entities.Gstins.FirstOrDefault(e => e.P_ID == id); if (entity == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Person with P_Id " + id.ToString() + " Not Found!"); } else { entity.ID = entity.ID; entity.P_ID = entity.P_ID; entity.Gst_Reg = gstin.Gst_Reg; entity.Gst_Exem = gstin.Gst_Exem; entity.Gst_Exem_Reason = gstin.Gst_Exem_Reason; entity.Gst_Exem_date = gstin.Gst_Exem_date; entity.Gst_Reg_Date = gstin.Gst_Reg_Date; entity.Gst_Reg_Type = gstin.Gst_Reg_Type; entity.Gst_Eco_Zone = gstin.Gst_Eco_Zone; entity.Gst_default = gstin.Gst_default; entity.Gstin_Addr = gstin.Gstin_Addr; entity.Gst_Pin = gstin.Gst_Pin; entity.Gst_City = gstin.Gst_City; entity.Gst_State = gstin.Gst_State; entity.Gst_Country = gstin.Gst_Country; entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK); } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } }
b9f21124526fd864b9c5510f709ebadea16189a5
[ "C#" ]
25
C#
harshbaisware/MajorWebApi
9e5f7f545bec5b43ad346950185077ab85d2efdd
9277e41dfa1789dd1153f9b862932eed76ed3945
refs/heads/master
<file_sep>package ajpportal; /** * <p>MetaAgent represents the agents</p> * * <p>This program is part of the solution for the second ICA for AJP in * Teesside University.</p> * * <p>AJP middleware 2013-SOLUTION is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details.</p> * * <p>You should have received a copy of the GNU General Public License along * with this program. If not, see http://www.gnu.org/licenses/.</p> * * <p>Copyright <NAME> <EMAIL> 10-April-2013 </p> * <p>Copyright Chris </p> <p>Copyright Sean 13-Dec-2012 </p> */ class MetaAgent extends BlockingQueue implements Runnable { MetaAgent name; Portal portal; Thread thread; BlockingQueue bq; // LinkedBlockingQueue lbq = new LinkedBlockingQueue(); public MetaAgent() { } public MetaAgent(MetaAgent name, Portal portal) { super(); this.name = name; this.portal = portal; msgHandler(bq.dequeue().toString()); thread = new Thread() { // msgHandler(lbq.peek()); }; } public void msgHandler(String msg) { // reactive behaviour to messages } public void sendMessage(String recipient, String msg) { portal.enqueue(wrap(name,recipient,msg)); } public String wrap(MetaAgent name, String recipient, String msg) { System.out.println(name + recipient + msg); return name + recipient + msg; } @Override public void run() { //continually extract messages from the agent's queue // pass them to the agen'ts message handler. } } <file_sep>package ajpportal; import java.net.Socket; /**SocketAgent is responsible for * * @author Anastasov */ public class SocketAgent extends MetaAgent { MetaAgent metaAgent; Socket socket; Portal portal; // write and read methods public void makeReadLoop() { new Thread() { // while (open(socket)) // { // portal.enqueue(name (socket.read())) // } }; } public void msgHangler(String msg) { // socket.write(msgToText(msg)); } } <file_sep>/** * <p>Main class</p> * * <p>This program is part of the solution for the second ICA for AJP in Teesside * University.</p> * * <p>AJP middleware 2013-SOLUTION is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details.</p> * * <p>You should have received a copy of the GNU General Public License along * with this program. If not, see http://www.gnu.org/licenses/.</p> * * <p>Copyright <NAME> <EMAIL> 10-April-2013 </p> * <p>Copyright Chris </p> * <p>Copyright Sean 13-Dec-2012 </p> */ package ajpportal; /** * * @author Anastasov */ public class AJPPortal { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Test"); Portal p1 = new Portal("p1"); new Sender(p1, "Kiril"); // Portal p1 = new Portal("Portal01"); // new Sender(p1, "Kiril"); } } <file_sep><<<<<<< HEAD This is part of the solution for the AJP. This part is responsible for the portal. ======= Advanced-Java-Programming ========================= Middlleware part 1 >>>>>>> 6321fd98420d9d19682a140aad111e26428a33c1 <file_sep>package ajpportal; import java.util.HashMap; /** * <p>Portal represents the portals which allow the agents to communicate.</p> * * <p>This program is part of the solution for the second ICA for AJP in Teesside * University.</p> * * <p>AJP middleware 2013-SOLUTION is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details.</p> * * <p>You should have received a copy of the GNU General Public License along * with this program. If not, see http://www.gnu.org/licenses/.</p> * * <p>Copyright <NAME> <EMAIL> 10-April-2013 </p> * <p>Copyright Chris </p> * <p>Copyright Sean 13-Dec-2012 </p> */ public class Portal extends MetaAgent { /** * routingTable */ static HashMap mapForAgents = new HashMap(); MetaAgent name; // Portal portal; String portalName; // BlockingQueue bq; public Portal() { } public Portal(String portalName) { this.portalName = portalName; } @Override public void msgHandler(String msg) { // System.out.println(name + recipient + msg); mapForAgents.get(portal.enqueue(msg)); // } public void addAgent(String name, MetaAgent agent) { mapForAgents.put(name, agent); } // public void addAgent(MetaAgent agent) // { // portal.addAgent(agent); // // } } <file_sep>package ajpportal; /**MsgId is responsible for * * @author Anastasov */ public class MsgId { } <file_sep>package ajpportal; /**BlockingQueue is responsible for * * @author Anastasov */ public class BlockingQueue<E> extends Queue{ } <file_sep>package ajpportal; /**UserAgent is responsible for * * @author Anastasov */ public class UserAgent extends MetaAgent { String name; public UserAgent(String name) { this.name = name; } public void messageRecieved(String message) { } public String getSender(String message) { return message; } public String getRecipient(String message) { return message; } public String getMessageBody(String message) { return message; } public String getMessageID(String message) { return message; } public String getSessionID(String message) { return message; } }
54531a9edd0569b10ca71f1c921517c0dba12d11
[ "Markdown", "Java" ]
8
Java
kanastasov/Advanced-Java-Programming
8f0ec2d9e28eead77858833abef5ea0f342b8882
40840a0960fcfe7197f2308d746186484ab82417
refs/heads/master
<file_sep>package com.ldoublem.loadingviewlib; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; public class LVSunSetView extends View { public LVSunSetView(Context context) { super(context); } public LVSunSetView(Context context, AttributeSet attrs) { super(context, attrs); } public LVSunSetView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } int sun_angle = 12; String SunstartTime = "2019-09-06 05:38:00"; String SunendTime = "2019-09-06 18:16:00"; public void setSunstartTime(String sunstartTime) { SunstartTime = sunstartTime; invalidate(); } public void setSunendTime(String sunendTime) { SunendTime = sunendTime; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); // mPaint. initPaint(); canvas.drawLine(0 + mWidth / 12, mHeight - mWidth / 6 , mWidth - mWidth / 12, mHeight - mWidth / 6, mPaint); mPaint.setStyle(Paint.Style.FILL); mPaint.setTextSize(35); mPaint.setStrokeWidth(1); String startTime = getTimeText(SunstartTime); String endTime = getTimeText(SunendTime); Rect rect = new Rect(); mPaint.getTextBounds(startTime, 0, startTime.length(), rect); int w = rect.width(); int h = rect.height() * 2; canvas.drawText(startTime, mWidth / 6 - w / 2, mHeight - mWidth / 6 + h, mPaint); canvas.drawText(endTime, mWidth - mWidth / 6 - w / 2, mHeight - mWidth / 6 + h, mPaint); mPaint.setStyle(Paint.Style.STROKE);//设置空心 mPaint.setStrokeWidth(2.5f); mPaint.setPathEffect(new DashPathEffect(new float[]{14, 12}, 0)); RectF oval1 = new RectF(mWidth / 2 - mWidth / 3, (float) ((float) (mHeight - mWidth / 6 - mWidth / 3) + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3) , mWidth / 2 + mWidth / 3, (float) (mHeight - mWidth / 6 + mWidth / 3 + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3)); canvas.drawArc(oval1, 180 + sun_angle, (180 - 2 * sun_angle), false, mPaint);//小弧形 float intervalf = 0f; try { long TodayInterval = getTimeInterval(SunstartTime, SunendTime); Timestamp ts = new Timestamp(System.currentTimeMillis()); String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ts.getTime()); long nowInterval = getTimeInterval(SunstartTime, nowtime); intervalf = nowInterval * 1.0f / TodayInterval * mAnimatedValue; if (intervalf > 1f) { intervalf = 1f; } } catch (ParseException e) { e.printStackTrace(); } // float y = (float) (Math.sin(Math.toRadians(sun_angle + (180 - 2 * sun_angle) * intervalf)) * mWidth / 3); // float x = (float) (Math.cos(Math.toRadians(sun_angle + (180 - 2 * sun_angle) * intervalf)) * mWidth / 3); // mPaint.setStyle(Paint.Style.FILL);//设置空心 // canvas.drawBitmap(getSun(intervalf), mWidth / 2 - x - mWidth / 3 / 4, (float) (mHeight - mWidth / 6 - y - mWidth / 3 / 4 + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3), mPaint); canvas.drawBitmap(getSunbg(intervalf), 0, 0, mPaint); canvas.restore(); } Paint mPaint; public void startSunset() { mhandler.obtainMessage(0).sendToTarget(); Message m = new Message(); m.what = 1; mhandler.sendMessageDelayed(m, 200); } public void start() { stopAnim(); float intervalf = 0f; try { long TodayInterval = getTimeInterval(SunstartTime, SunendTime); Timestamp ts = new Timestamp(System.currentTimeMillis()); String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ts.getTime()); long nowInterval = getTimeInterval(SunstartTime, nowtime); intervalf = nowInterval * 1.0f / TodayInterval; if (intervalf > 1f) { intervalf = 1f; } } catch (ParseException e) { e.printStackTrace(); } startViewAnim(0f, 1f, (long) (4000 * intervalf)); } private void initPaint() { mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.WHITE); mPaint.setStrokeWidth(4); } int mWidth = 0; int mHeight = 0; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mHeight = getMeasuredHeight(); mWidth = getMeasuredWidth(); } private ValueAnimator valueAnimator; private float mAnimatedValue = 0f; public void stopAnim() { if (valueAnimator != null) { clearAnimation(); valueAnimator.setRepeatCount(0); valueAnimator.cancel(); mAnimatedValue = 0f; postInvalidate(); } } private ValueAnimator startViewAnim(float startF, final float endF, long time) { valueAnimator = ValueAnimator.ofFloat(startF, endF); valueAnimator.setDuration(time); valueAnimator.setInterpolator(new LinearInterpolator()); valueAnimator.setRepeatCount(0); valueAnimator.setRepeatMode(ValueAnimator.RESTART); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { mAnimatedValue = (float) valueAnimator.getAnimatedValue(); invalidate(); } }); valueAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); } @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); } @Override public void onAnimationRepeat(Animator animation) { super.onAnimationRepeat(animation); } }); if (!valueAnimator.isRunning()) { valueAnimator.start(); } return valueAnimator; } public long getTimeInterval(String oldTime, String newTime) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long NTime = df.parse(newTime).getTime(); //从对象中拿到时间 long OTime = df.parse(oldTime).getTime(); long diff = (NTime - OTime) / 1000 / 60; return diff; } private String getTimeText(String tsStr) { Timestamp ts = new Timestamp(System.currentTimeMillis()); // String tsStr = "2011-05-09 11:49:45"; String time = "00:00"; try { ts = Timestamp.valueOf(tsStr); time = new SimpleDateFormat("HH:mm").format(ts.getTime()); } catch (Exception e) { e.printStackTrace(); } return time; } private Bitmap getSunbg(float intervalf) { Bitmap b = Bitmap.createBitmap(mWidth, mHeight - mWidth / 6, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); c.save(); mPaint.setStyle(Paint.Style.STROKE);//设置空心 mPaint.setColor(Color.argb(255, 254, 219, 57)); if (intervalf < 1f) { RectF oval2 = new RectF(mWidth / 2 - mWidth / 3, (float) ((float) (mHeight - mWidth / 6 - mWidth / 3) + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3) , mWidth / 2 + mWidth / 3, (float) (mHeight - mWidth / 6 + mWidth / 3 + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3)); c.drawArc(oval2, 180 + sun_angle, (180 - 2 * sun_angle) * intervalf, false, mPaint);//小弧形 } mPaint.setStyle(Paint.Style.FILL);//设置空心 //如果从地下开始日出这个 sun_angle用0使用 float y = (float) (Math.sin(Math.toRadians(sun_angle + (180 - 2 * sun_angle) * intervalf)) * mWidth / 3); float x = (float) (Math.cos(Math.toRadians(sun_angle + (180 - 2 * sun_angle) * intervalf)) * mWidth / 3); c.drawBitmap(getSun(intervalf), mWidth / 2 - x - mWidth / 3 / 4, (float) (mHeight - mWidth / 6 - y - mWidth / 3 / 4 + Math.sin(Math.toRadians(sun_angle)) * mWidth / 3), mPaint); c.restore(); return b; } private Bitmap getSun(float intervalf) { // intervalf = 0; Bitmap b = Bitmap.createBitmap(mWidth / 3 / 2, mWidth / 3 / 2, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); c.save(); mPaint.setStyle(Paint.Style.FILL);//设置空心 c.rotate(intervalf * 180, mWidth / 3 / 4, mWidth / 3 / 4); if (intervalf >= 0.3f || intervalf <= 0.7f) { mPaint.setColor(Color.argb(255, 254, 219, 57)); } if (intervalf < 0.3f) { float colorap = (float) (intervalf / 0.3f); int suncolor = (int) (230 + (25 * (colorap))); mPaint.setColor(Color.argb(suncolor, 254, 219, 57)); } else if (intervalf > 0.7f) { float colorap = (float) ((1f - intervalf) / 0.3f); int suncolor = (int) (230 + (25 * (colorap))); mPaint.setColor(Color.argb(suncolor, 254, 219, 57)); } if (intervalf > 0 && intervalf < 1) { c.drawCircle(mWidth / 3 / 4, mWidth / 3 / 4, mWidth / 3 / 10, mPaint); mPaint.setStrokeWidth(5); c.drawLine(mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) - (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine(mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine(mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) , mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) - (mWidth / 3 / 10 / 2) , mPaint ); c.drawLine(mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) , mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); // Log.e("eeeee", (Math.sqrt(2) + "")); } else if (intervalf == 0) { RectF oval1 = new RectF(); oval1.set(mWidth / 3 / 4 - mWidth / 3 / 10, mWidth / 3 / 4 - mWidth / 3 / 10, mWidth / 3 / 4 + mWidth / 3 / 10, mWidth / 3 / 4 + mWidth / 3 / 10); c.drawArc(oval1, 180, 180, true, mPaint);//小弧形 mPaint.setStrokeWidth(5); c.drawLine(mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) - (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine(mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) , mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) - (mWidth / 3 / 10 / 2) , mPaint ); c.drawLine(mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine((float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); } else if (intervalf == 1) { mPaint.setStrokeWidth(5); RectF oval1 = new RectF(); oval1.set(mWidth / 3 / 4 - mWidth / 3 / 10, mWidth / 3 / 4 - mWidth / 3 / 10, mWidth / 3 / 4 + mWidth / 3 / 10, mWidth / 3 / 4 + mWidth / 3 / 10); c.drawArc(oval1, 180, -180, true, mPaint);//小弧形 c.drawLine(mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 - mWidth / 3 / 10 - (mWidth / 3 / 10 / 5) - (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine(mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) , mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2) , mPaint ); c.drawLine(mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5), mWidth / 3 / 4, mWidth / 3 / 4 + mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2) , mWidth / 3 / 4, mPaint ); c.drawLine((float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 - ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); c.drawLine((float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5)) / Math.sqrt(2))), (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , (float) (mWidth / 3 / 4 + ((float) (mWidth / 3 / 10 + (mWidth / 3 / 10 / 5) + (mWidth / 3 / 10 / 2)) / Math.sqrt(2))) , mPaint ); } c.restore(); return b; } private android.os.Handler mhandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0) { mAnimatedValue = 0f; invalidate(); } else if (msg.what == 1) { start(); } } }; } <file_sep>package com.ldoublem.loadingView; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import com.ldoublem.loadingviewlib.LVSunSetView; import com.ldoublem.loadingviewlib.view.LVBattery; import com.ldoublem.loadingviewlib.view.LVBlazeWood; import com.ldoublem.loadingviewlib.view.LVBlock; import com.ldoublem.loadingviewlib.LVChromeLogo; import com.ldoublem.loadingviewlib.LVCircular; import com.ldoublem.loadingviewlib.LVCircularCD; import com.ldoublem.loadingviewlib.view.LVCircularJump; import com.ldoublem.loadingviewlib.view.LVCircularRing; import com.ldoublem.loadingviewlib.view.LVCircularSmile; import com.ldoublem.loadingviewlib.view.LVCircularZoom; import com.ldoublem.loadingviewlib.view.LVEatBeans; import com.ldoublem.loadingviewlib.view.LVFinePoiStar; import com.ldoublem.loadingviewlib.view.LVFunnyBar; import com.ldoublem.loadingviewlib.view.LVGears; import com.ldoublem.loadingviewlib.view.LVGearsTwo; import com.ldoublem.loadingviewlib.view.LVGhost; import com.ldoublem.loadingviewlib.LVLineWithText; import com.ldoublem.loadingviewlib.view.LVNews; import com.ldoublem.loadingviewlib.view.LVPlayBall; import com.ldoublem.loadingviewlib.view.LVRingProgress; import com.ldoublem.loadingviewlib.view.LVWifi; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { LVPlayBall mLVPlayBall; LVCircularRing mLVCircularRing; LVCircular mLVCircular; LVCircularJump mLVCircularJump; LVCircularZoom mLVCircularZoom; LVLineWithText mLVLineWithText; LVEatBeans mLVEatBeans; LVCircularCD mLVCircularCD; LVCircularSmile mLVCircularSmile; LVGears mLVGears; LVGearsTwo mLVGearsTwo; LVFinePoiStar mLVFinePoiStar; LVChromeLogo mLVChromeLogo; LVBattery mLVBattery; LVWifi mLVWifi; LVNews mLVNews; LVBlock mLVBlock; LVGhost mLVGhost; LVFunnyBar mLVFunnyBar; LVRingProgress mLVRingProgress; LVSunSetView lv_sunset; LVBlazeWood mLVBlazeWood; int mValueLVLineWithText = 0; int mValueLVNews = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏 setContentView(R.layout.activity_main); mLVCircular = (LVCircular) findViewById(R.id.lv_circular); mLVCircular.setViewColor(Color.rgb(255, 99, 99)); mLVCircular.setRoundColor(Color.rgb(255, 0, 0)); mLVCircularCD = (LVCircularCD) findViewById(R.id.lv_circularCD); mLVCircularCD.setViewColor(Color.rgb(0, 255, 0)); mLVLineWithText = (LVLineWithText) findViewById(R.id.lv_linetext); mLVLineWithText.setViewColor(Color.rgb(33, 66, 77)); mLVLineWithText.setTextColor(Color.rgb(233, 166, 177)); mLVCircularJump = (LVCircularJump) findViewById(R.id.lv_circularJump); mLVCircularJump.setViewColor(Color.rgb(133, 66, 99)); mLVCircularRing = (LVCircularRing) findViewById(R.id.lv_circularring); mLVCircularRing.setViewColor(Color.argb(100, 255, 255, 255)); mLVCircularRing.setBarColor(Color.YELLOW); mLVCircularSmile = (LVCircularSmile) findViewById(R.id.lv_circularSmile); mLVCircularSmile.setViewColor(Color.rgb(144, 238, 146)); mLVCircularZoom = (LVCircularZoom) findViewById(R.id.lv_circularZoom); mLVCircularZoom.setViewColor(Color.rgb(255, 0, 122)); mLVEatBeans = (LVEatBeans) findViewById(R.id.lv_eatBeans); mLVEatBeans.setViewColor(Color.WHITE); mLVEatBeans.setEyeColor(Color.BLUE); mLVFinePoiStar = (LVFinePoiStar) findViewById(R.id.lv_finePoiStar); mLVFinePoiStar.setViewColor(Color.WHITE); mLVFinePoiStar.setCircleColor(Color.YELLOW); mLVFinePoiStar.setDrawPath(true); mLVGears = (LVGears) findViewById(R.id.lv_gears); mLVGears.setViewColor(Color.rgb(55, 155, 233)); mLVGearsTwo = (LVGearsTwo) findViewById(R.id.lv_gears_two); mLVGearsTwo.setViewColor(Color.rgb(155, 55, 233)); mLVWifi = (LVWifi) findViewById(R.id.lv_wifi); mLVWifi.setViewColor(Color.BLACK); mLVNews = (LVNews) findViewById(R.id.lv_news); mLVNews.setViewColor(Color.WHITE); mLVRingProgress = (LVRingProgress) findViewById(R.id.lv_ringp); mLVRingProgress.setViewColor(Color.WHITE); mLVRingProgress.setTextColor(Color.BLACK); mLVRingProgress.setPorBarStartColor(Color.YELLOW); mLVRingProgress.setPorBarEndColor(Color.BLUE); mLVGhost = (LVGhost) findViewById(R.id.lv_ghost); mLVGhost.setViewColor(Color.WHITE); mLVGhost.setHandColor(Color.BLACK); mLVPlayBall = (LVPlayBall) findViewById(R.id.lv_playball); mLVPlayBall.setViewColor(Color.WHITE); mLVPlayBall.setBallColor(Color.RED); mLVChromeLogo = (LVChromeLogo) findViewById(R.id.lv_chromeLogo); mLVBattery = (LVBattery) findViewById(R.id.lv_battery); mLVBattery.setBatteryOrientation(LVBattery.BatteryOrientation.VERTICAL);//LVBattery.BatteryOrientation.HORIZONTAL mLVBattery.setShowNum(false); mLVBattery.setViewColor(Color.WHITE); mLVBattery.setCellColor(Color.GREEN); mLVBlock = (LVBlock) findViewById(R.id.lv_block); mLVBlock.setViewColor(Color.rgb(245, 209, 22)); mLVBlock.setShadowColor(Color.BLACK); // mLVBlock.isShadow(false); mLVFunnyBar = (LVFunnyBar) findViewById(R.id.lv_funnybar); mLVFunnyBar.setViewColor(Color.rgb(234, 167, 107)); mLVBlazeWood = (LVBlazeWood) findViewById(R.id.lv_wood); // mLVLineWithText.setValue(50); lv_sunset = (LVSunSetView) findViewById(R.id.lv_sunset); lv_sunset.setSunendTime("2019-09-06 16:20:00"); lv_sunset.setSunstartTime("2019-09-06 7:16:00"); } public void startAnim(View v) { stopAll(); if (v instanceof LVCircular) { ((LVCircular) v).startAnim(); } else if (v instanceof LVCircularCD) { ((LVCircularCD) v).startAnim(); } else if (v instanceof LVCircularSmile) { ((LVCircularSmile) v).startAnim(); } else if (v instanceof LVCircularRing) { ((LVCircularRing) v).startAnim(); } else if (v instanceof LVCircularZoom) { ((LVCircularZoom) v).startAnim(); } else if (v instanceof LVCircularJump) { ((LVCircularJump) v).startAnim(); } else if (v instanceof LVEatBeans) { ((LVEatBeans) v).startAnim(3500); } else if (v instanceof LVPlayBall) { ((LVPlayBall) v).startAnim(); } else if (v instanceof LVLineWithText) { startLVLineWithTextAnim(); } else if (v instanceof LVGears) { ((LVGears) v).startAnim(); } else if (v instanceof LVGearsTwo) { ((LVGearsTwo) v).startAnim(); } else if (v instanceof LVFinePoiStar) { ((LVFinePoiStar) v).setDrawPath(false); ((LVFinePoiStar) v).startAnim(3500); } else if (v instanceof LVChromeLogo) { ((LVChromeLogo) v).startAnim(); } else if (v instanceof LVBattery) { ((LVBattery) v).startAnim(5000); } else if (v instanceof LVWifi) { ((LVWifi) v).startAnim(9000); } else if (v instanceof LVNews) { startLVNewsAnim(); } else if (v instanceof LVBlock) { ((LVBlock) v).startAnim(); } else if (v instanceof LVGhost) { ((LVGhost) v).startAnim(); } else if (v instanceof LVFunnyBar) { ((LVFunnyBar) v).startAnim(); } else if (v instanceof LVRingProgress) { ((LVRingProgress) v).startAnim(3000); } else if (v instanceof LVBlazeWood) { ((LVBlazeWood) v).startAnim(500); } else if (v instanceof LVSunSetView) { ((LVSunSetView) v).startSunset(); } } public void startAnimAll(View v) { mLVCircular.startAnim(); mLVCircularRing.startAnim(); mLVPlayBall.startAnim(); mLVCircularJump.startAnim(); mLVCircularZoom.startAnim(); startLVLineWithTextAnim(); mLVEatBeans.startAnim(3500); mLVCircularCD.startAnim(); mLVCircularSmile.startAnim(1000); mLVGears.startAnim(); mLVGearsTwo.startAnim(); mLVFinePoiStar.setDrawPath(true); mLVFinePoiStar.startAnim(3500); mLVChromeLogo.startAnim(); mLVBattery.startAnim(5000); mLVWifi.startAnim(9000); startLVNewsAnim(); mLVBlock.startAnim(); mLVGhost.startAnim(); mLVFunnyBar.startAnim(); mLVRingProgress.startAnim(3000); mLVBlazeWood.startAnim(500); lv_sunset.startSunset(); } public void stopAnim(View v) { stopAll(); } private void stopAll() { mLVCircular.stopAnim(); mLVPlayBall.stopAnim(); mLVCircularJump.stopAnim(); mLVCircularZoom.stopAnim(); mLVCircularRing.stopAnim(); mLVEatBeans.stopAnim(); stopLVLineWithTextAnim(); mLVCircularCD.stopAnim(); mLVCircularSmile.stopAnim(); mLVGears.stopAnim(); mLVGearsTwo.stopAnim(); mLVFinePoiStar.stopAnim(); mLVChromeLogo.stopAnim(); mLVBattery.stopAnim(); mLVWifi.stopAnim(); stopLVNewsAnim(); // mLVNews.stopLVNewsAnim(); mLVBlock.stopAnim(); mLVGhost.stopAnim(); mLVFunnyBar.stopAnim(); mLVRingProgress.stopAnim(); mLVBlazeWood.stopAnim(); } public Timer mTimerLVLineWithText = new Timer();// 定时器 public Timer mTimerLVNews = new Timer();// 定时器 private void startLVLineWithTextAnim() { mValueLVLineWithText = 0; if (mTimerLVLineWithText != null) { mTimerLVLineWithText.cancel();// 退出之前的mTimer } mTimerLVLineWithText = new Timer(); timerTaskLVLineWithText(); } private void stopLVLineWithTextAnim() { if (mTimerLVLineWithText != null) { mTimerLVLineWithText.cancel();// 退出之前的mTimer mLVNews.setValue(mValueLVNews); } } private void startLVNewsAnim() { mValueLVNews = 0; if (mTimerLVNews != null) { mTimerLVNews.cancel(); } mTimerLVNews = new Timer(); timerTaskLVNews(); } private void stopLVNewsAnim() { mLVNews.stopAnim(); if (mTimerLVNews != null) { mTimerLVNews.cancel(); mLVLineWithText.setValue(mValueLVLineWithText); } } public void timerTaskLVNews() { mTimerLVNews.schedule(new TimerTask() { @Override public void run() { if (mValueLVNews < 100) { mValueLVNews++; Message msg = mHandle.obtainMessage(1); msg.arg1 = mValueLVNews; mHandle.sendMessage(msg); } else { mTimerLVNews.cancel(); } } }, 0, 10); } public void timerTaskLVLineWithText() { mTimerLVLineWithText.schedule(new TimerTask() { @Override public void run() { if (mValueLVLineWithText < 100) { mValueLVLineWithText++; Message msg = mHandle.obtainMessage(2); msg.arg1 = mValueLVLineWithText; mHandle.sendMessage(msg); } else { mTimerLVLineWithText.cancel(); } } }, 0, 50); } @SuppressLint("HandlerLeak") private Handler mHandle = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 2) mLVLineWithText.setValue(msg.arg1); else if (msg.what == 1) { mLVNews.setValue(msg.arg1); } } }; } <file_sep># LoadingView a simple loadingview for android with animation 简单的带有动画效果的加载控件 #Preview ![screen](https://github.com/ldoublem/LoadingView/blob/master/screen/screen.gif) ![screen2](https://github.com/ldoublem/LoadingView/blob/master/screen/screen2.gif) #Gradle ```compile 'com.ldoublem.loadingview:loadingviewlib:1.0'``` --- |Id| Picture | Name | Method | |---|---|---|---| 1|![1](https://github.com/ldoublem/LoadingView/blob/master/screen/1.png) | LVCircularCD | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 2|![2](https://github.com/ldoublem/LoadingView/blob/master/screen/2.png) | LVCircularRing | setViewColor(int color)<br>setBarColor(int color)<br>startAnim(int time)<br>stopAnim() 3|![3](https://github.com/ldoublem/LoadingView/blob/master/screen/3.png) | LVCircular | setViewColor(int color)<br>setRoundColor(int color)<br>startAnim(int time)<br>stopAnim() 4|![4](https://github.com/ldoublem/LoadingView/blob/master/screen/4.png) | LVFinePoiStar | setViewColor(int color)<br>setCircleColor(int color)<br>startAnim(int time)<br>stopAnim()<br>setDrawPath(boolean isDrawPath) 5|![5](https://github.com/ldoublem/LoadingView/blob/master/screen/5.png) | LVCircularSmile | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 6|![6](https://github.com/ldoublem/LoadingView/blob/master/screen/6.png) | LVGears | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 7|![7](https://github.com/ldoublem/LoadingView/blob/master/screen/7.png) | LVGearsTwo | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 8|![8](https://github.com/ldoublem/LoadingView/blob/master/screen/8.png) | LVWifi | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 9|![9](https://github.com/ldoublem/LoadingView/blob/master/screen/9.png) | LVCircularJump | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 10|![10](https://github.com/ldoublem/LoadingView/blob/master/screen/10.png) | LVCircularZoom | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 11|![11](https://github.com/ldoublem/LoadingView/blob/master/screen/11.png) | LVPlayBall | setViewColor(int color)<br>setBallColor(int color)<br>startAnim(int time)<br>stopAnim() 12|![12](https://github.com/ldoublem/LoadingView/blob/master/screen/12.png) | LVNews | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 13|![13](https://github.com/ldoublem/LoadingView/blob/master/screen/13.png) | LVLineWithText | setViewColor(int color)<br>setTextColor(int color)<br>setValue(int value)//0-100 14|![14](https://github.com/ldoublem/LoadingView/blob/master/screen/14.png) | LVEatBeans | setViewColor(int color)<br>setEyeColor(int color)<br>startAnim(int time)<br>stopAnim() 15|![15](https://github.com/ldoublem/LoadingView/blob/master/screen/15.png) | LVChromeLogo | startAnim(int time)<br>stopAnim() 16|![16](https://github.com/ldoublem/LoadingView/blob/master/screen/16.png) | LVRingProgress | setViewColor(int color)<br>setTextColor(int color)<br>setPorBarStartColor(int color)<br>setPorBarEndColor(int color)<br>startAnim(int time)<br>stopAnim() 17|![17](https://github.com/ldoublem/LoadingView/blob/master/screen/17.png) | LVBlock | setViewColor(int color)<br>isShadow(boolean boolean show)<br>setShadowColor(int color)<br>startAnim(int time)<br>stopAnim() 18|![18](https://github.com/ldoublem/LoadingView/blob/master/screen/18.png) | LVFunnyBar | setViewColor(int color)<br>startAnim(int time)<br>stopAnim() 19|![19](https://github.com/ldoublem/LoadingView/blob/master/screen/19.png) | LVGhost | setViewColor(int color)<br>setHandColor(int color)<br>startAnim(int time)<br>stopAnim() 20|![20](https://github.com/ldoublem/LoadingView/blob/master/screen/20.png) | LVBlazeWood | startAnim(int time)<br>stopAnim() 21|![21](https://github.com/ldoublem/LoadingView/blob/master/screen/21.png) | LVBattery | setViewColor(int color)<br>setCellColor(int color)<br>setShowNum(boolean show)<br>setValue(int value)//0-100<br>startAnim(int time)<br>stopAnim() 22|![22](https://github.com/ldoublem/LoadingView/blob/master/screen/22.png) | LVSunSetView | setSunendTime(String endtime)<br>setSunstartTime(String starttime)<br>startSunset() ## About me An android developer in Hangzhou. If you want to make friends with me, You can email to me. my [email](mailto:<EMAIL>) :smiley: License ======= The MIT License (MIT) Copyright (c) 2016 ldoublem 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.
2e8ae56a2fe08928505227f85c0d192732d390a7
[ "Markdown", "Java" ]
3
Java
dengdailk/LoadingView-master
c715ba04349cb187af154f7802551ffbd001e2cd
87ec2e027b9cb86837e9cffdff03baec88a5eef0
refs/heads/master
<file_sep>package com.example.buypool; import android.app.Application; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class SendCardActivity extends AppCompatActivity { // This Class uses on Card Your sent activitys , // This class used to control //1. Action bar //2.Implement returned information from database and fill it into each cards CurrentUserInfo currentUserInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_card_send); //Set Tool Bar starts here Toolbar toolbar = findViewById(R.id.SendCardTooBar); setSupportActionBar(toolbar); TextView textView = toolbar.findViewById(R.id.toolbar_title); textView.setText("Cards Your Uploaded"); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.getOverflowIcon().setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_ATOP); //Sets tool bar ends here RecyclerView recyclerView = findViewById(R.id.recyclerViewSendCard); recyclerView.setLayoutManager(new LinearLayoutManager(this));//create a recycling view in a linear layout SendCardAdapter myadapter = new SendCardAdapter( this,getMyList(),currentUserInfo); recyclerView.setAdapter(myadapter); } //modifiy the return data as and set model private ArrayList<Model> getMyList(){ ArrayList<Model> models = new ArrayList<>(); LocalDatabase helper = new LocalDatabase(getApplicationContext(), "Cards", null, 1); SQLiteDatabase db = helper.getWritableDatabase(); //GET ALL THE cards the current_user collected String sql = "SELECT title,description,address,date,cards.phone_number,username,gender,cardStatus,cards.id FROM cards,usersremote where create_userID = usersremote.id AND create_userID = ?;"; currentUserInfo= (CurrentUserInfo) getApplicationContext(); Cursor cardlist = db.rawQuery(sql, new String[]{""+currentUserInfo.getID()}); while (cardlist.moveToNext()){ String title = cardlist.getString(0); String description = cardlist.getString(1); String address = cardlist.getString(2); String time = cardlist.getString(3).split(" ")[0]; String phoneNumber = cardlist.getString(4); String username = cardlist.getString(5); int gender = cardlist.getInt(6); int cardStatus = cardlist.getInt(7); int cardID = cardlist.getInt(8); Model m = new Model(); m.setTitle(title); m.setDesription(description); m.setImg(gender == 0?R.drawable.male:R.drawable.female); m.setDate(time); m.setAddress(address); m.setUserNameOnCard(username); m.setPhoneNumber(phoneNumber); m.setCardStatus(cardStatus); m.setCardID(cardID); models.add(m); } return models; } } <file_sep>package com.example.buypool; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; public class ProfileActivity extends AppCompatActivity { //This class associate with profile acitivity , //what is does //1. Set Action bar heading //2. go into other activity i.e Card Your collected and Cards you Upload Activity CurrentUserInfo userInfo; TextView userName, cardNumberCollected, CardPulished; EditText createFormTitleInput, createFormPhoneNumberInput, createFormAddressInput, createFormDiscriptionTextInput; Button formSubmit; LocalDatabase helper; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); userInfo = (CurrentUserInfo) getApplicationContext(); String name = userInfo.getUserName(); userName = findViewById(R.id.UserNameOnCard); cardNumberCollected = findViewById(R.id.cardNumberCollected); CardPulished = findViewById(R.id.CardPulished); //set profile name userName.setText(name); helper = new LocalDatabase(getApplicationContext(), "Cards", null, 1); db = helper.getWritableDatabase(); //get collected cards count String sql = "SELECT count(*) FROM orders where order_userID = ?;"; Cursor collected = db.rawQuery(sql, new String[]{"" + userInfo.getID()}); collected.moveToNext(); int number = collected.getInt(0); collected.close(); cardNumberCollected.setText(number <= 1 ? number + " card" : number + " cards"); //get sent cards count String sql1 = "SELECT count(*) FROM cards where create_userID = ?;"; Cursor sent = db.rawQuery(sql1, new String[]{"" + userInfo.getID()}); sent.moveToNext(); final int numbers = sent.getInt(0); sent.close(); CardPulished.setText(numbers <= 1 ? numbers + " card" : numbers + " cards"); //get the corresponding view createFormAddressInput = findViewById(R.id.createFormAddressInput); createFormTitleInput = findViewById(R.id.createFormTitleInput); createFormPhoneNumberInput = findViewById(R.id.createFormPhoneNumberInput); createFormDiscriptionTextInput = findViewById(R.id.createFormDiscriptionTextInput); formSubmit = findViewById(R.id.FormSubmit); createFormPhoneNumberInput.setText(userInfo.getPhoneNumber()); //set submission onclick formSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder bb = new AlertDialog.Builder(ProfileActivity.this); bb.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { addCard(numbers); } }); bb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); bb.setMessage("Are you sure you want to create this order?"); bb.setTitle("Order Creation Confirmation"); bb.show(); } }); //tool bar start here Toolbar toolbar = findViewById(R.id.ProfileToolBarId); setSupportActionBar(toolbar); TextView textView = toolbar.findViewById(R.id.toolbar_title); textView.setText("Profile"); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.getOverflowIcon().setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_ATOP); //too bar ends here //to card collection activity ImageView toCardCollectionPage = findViewById(R.id.toCardCollectionPage); toCardCollectionPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toCardCollectionActivity(); } }); //ends here //to send card activity ImageView toCardSendPage = findViewById(R.id.toSendCard); toCardSendPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toCardSendActivity(); } }); //end here } //function move to a collection card public void toCardCollectionActivity() { Intent intent = new Intent(this, CardCollectionActivity.class); startActivity(intent); } public void toCardSendActivity() { //function move to a send card Intent intent = new Intent(this, SendCardActivity.class); startActivity(intent); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_profile, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Go into different activity page if a user clicked onto given icons int id = item.getItemId(); if (id == R.id.Logout) { //change page should be here Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } return true; } public void addCard(int numbers) { String address = createFormAddressInput.getText().toString(); String title = createFormTitleInput.getText().toString(); String phoneNumber = createFormPhoneNumberInput.getText().toString(); String description = createFormDiscriptionTextInput.getText().toString(); if (address.equals("") || title.equals("") || phoneNumber.equals("") || description.equals("")) { String text = ""; int previous = 0; if (title.equals("")) { text += "title"; previous = 1; } if (phoneNumber.equals("")) if (previous == 0) { text += "phoneNumber"; previous = 1; } else { text += " and phoneNumber"; } if (address.equals("")) if (previous == 0) { text += "address"; previous = 1; } else { text += " and address"; } if (description.equals("")) if (previous == 0) { text += "description"; previous = 1; } else { text += " and description"; } text += " can not be empty"; Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show(); return; } ContentValues contentValue = new ContentValues(); contentValue.put("address", address); contentValue.put("title", title); contentValue.put("phone_number", phoneNumber); contentValue.put("description", description); contentValue.put("cardStatus", "0"); contentValue.put("create_userID", "" + userInfo.getID()); long cards = db.insert("cards", null, contentValue); if (cards > 0) { CardPulished.setText(numbers + 1 <= 1 ? (numbers + 1) + " card" : (numbers + 1) + " cards"); Toast.makeText(getApplicationContext(), "Order is created successfully", Toast.LENGTH_LONG).show(); } } } <file_sep>package com.example.buypool; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.IllegalFormatCodePointException; public class CardCollectionAdapter extends RecyclerView.Adapter<MyHolder> { // This Class Used as Adapter for recyclerView that located in CardCollectionAcitity class //what it does //1.receives all cards information and put into put those information on to cards //2. It also passes intent information of cards to activity_show_card_Details , // as user clicks the card and wants to view detail description of that cards. Context c; ArrayList<Model> models; LocalDatabase helper; SQLiteDatabase db; CurrentUserInfo userInfo; // this array list create a list of array which parameter define in our model class public CardCollectionAdapter(Context c, ArrayList<Model> models, CurrentUserInfo userInfo) { this.c = c; this.models = models; helper = new LocalDatabase(c, "Cards", null, 1); db = helper.getWritableDatabase(); this.userInfo = (CurrentUserInfo) userInfo; } @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.each_card_collected, null); //this line inflate our public_card return new MyHolder(view);//this will return our view to holder class } @SuppressLint("RestrictedApi") @Override public void onBindViewHolder(@NonNull final MyHolder myHolder, int position) { final int position2 = position; if (models.get(position).getCardStatus() == 2) { myHolder.mCardCompeleted.setClickable(false); myHolder.DontWantCardCollected.setVisibility(View.INVISIBLE); } else if (models.get(position).getCardStatus() == 1) { myHolder.mCardCompeleted.setChecked(false); } myHolder.mTitle.setText(models.get(position).getTitle()); myHolder.mDes.setText(models.get(position).getDesription()); myHolder.mDate.setText(models.get(position).getDate()); myHolder.mAddress.setText(models.get(position).getAddress()); myHolder.mUserNameOnCard.setText(models.get(position).getUserNameOnCard()); myHolder.mcardPhoneNumber.setText(models.get(position).getPhoneNumber()); //add card finished function for switch myHolder.mCardCompeleted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) { if (isChecked) { AlertDialog.Builder bb = new AlertDialog.Builder(c); bb.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @SuppressLint("RestrictedApi") @Override public void onClick(DialogInterface dialog, int which) { int cardID = models.get(position2).getCardID(); ContentValues contentValue = new ContentValues(); if (isChecked) { contentValue.put("cardStatus", "2"); int cardUpdate = db.update("cards", contentValue, "id = ?", new String[]{"" + cardID}); if (cardUpdate == 1) { Toast.makeText(c, "Order is finished", Toast.LENGTH_LONG).show(); myHolder.DontWantCardCollected.setVisibility(View.INVISIBLE); //update ui models.get(position2).setCardStatus(2); notifyDataSetChanged(); } else Toast.makeText(c, "Update error, please try it later!", Toast.LENGTH_LONG).show(); } } }); bb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { myHolder.mCardCompeleted.setChecked(false); dialog.dismiss(); } }); bb.setMessage("Are you sure you complete this order?"); bb.setTitle("Order Completion"); bb.show(); } } }); //drop collected card function myHolder.DontWantCardCollected.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder bb = new AlertDialog.Builder(c); bb.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int cardID = models.get(position2).getCardID(); ContentValues contentValue = new ContentValues(); contentValue.put("cardStatus", "0"); int cardUpdate = db.update("cards", contentValue, "id = ?", new String[]{"" + cardID}); if (cardUpdate != 1) { Toast.makeText(c, "Order is dropped unsuccessfully, please try it later!", Toast.LENGTH_LONG).show(); return; } int orderDelete = db.delete("orders", "cardID = ?", new String[]{"" + cardID}); if (orderDelete > 0) { Toast.makeText(c, "Order is dropped successfully", Toast.LENGTH_LONG).show(); //update ui models.remove(position2); notifyDataSetChanged(); } else { Toast.makeText(c, "Order is dropped unsuccessfully, please try it later!", Toast.LENGTH_LONG).show(); } } }); bb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); bb.setMessage("Are you sure you want to drop this order?"); bb.setTitle("Order Drop Confirmation"); bb.show(); } }); // This is a way to get image from Resource drawable , // but just leave it ;if we want to return image fro data base the this like should be change myHolder.mImaeView.setImageResource(models.get(position).getImg()); //this is all part two myHolder.setItemClickListener(new ItemClickListener() { @Override public void onItemClickListener(View v, int position) { String gAddress = models.get(position).getAddress(); String gPhoneNumber = models.get(position).getPhoneNumber(); String gUserNameOnCard = models.get(position).getUserNameOnCard(); String gDate = models.get(position).getDate(); String gTitle = models.get(position).getTitle(); String gDesc = models.get(position).getDesription();//get data from previous activity BitmapDrawable bitmapDrawable = (BitmapDrawable) myHolder.mImaeView.getDrawable(); // this will get our image from drawble Bitmap bitmap = bitmapDrawable.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); //image will get stream and bytes; bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);//this will compress our image byte[] bytes = stream.toByteArray(); //get out data with intent Intent intent = new Intent(c, ShowCardDetailActivity.class); intent.putExtra("iTitle", gTitle); intent.putExtra("iDesc", gDesc); intent.putExtra("iImage", bytes); intent.putExtra("iAddress", gAddress); intent.putExtra("iPhoneNumber", gPhoneNumber); intent.putExtra("iUserNameOnCard", gUserNameOnCard); intent.putExtra("iDate", gDate); c.startActivity(intent); } }); } @Override public int getItemCount() { return models.size(); } } <file_sep>package com.example.buypool; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; public class SignUpActivity extends AppCompatActivity { //This class used for signUp acitivity //what it does //Signup and store the information into database private Button btnLogin , btnSignup, getBtnSignup; private EditText userName,email,password,phoneNumber,rePassword; private Switch gender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); btnLogin = findViewById(R.id.btnLogin); btnSignup = findViewById(R.id.btnSignup); getBtnSignup = findViewById(R.id.SignButton); userName = findViewById(R.id.signup_name); email = findViewById(R.id.EnterEmail); password = findViewById(R.id.Password); email = findViewById(R.id.EnterEmail); phoneNumber = findViewById(R.id.PhoneNumber); rePassword = findViewById(R.id.ConfirmPassword); gender = findViewById(R.id.MaleFemale); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OpenLoginActivity(); } }); getBtnSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signUp(); } }); } public void OpenLoginActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void signUp(){ LocalDatabase helper = new LocalDatabase(getApplicationContext(), "User", null, 1); SQLiteDatabase db = helper.getWritableDatabase(); String email = this.email.getText().toString(); String password = this.password.getText().toString().trim(); String rePassword = this.rePassword.getText().toString().trim(); String userName = this.userName.getText().toString(); String phoneNumber = this.phoneNumber.getText().toString(); String gender = this.gender.isChecked()?"1":"0"; if (email.equals("") || password.equals("") || rePassword.equals("") || userName.equals("") || phoneNumber.equals("")){ Toast.makeText(getApplicationContext(), "All information can not be empty!", Toast.LENGTH_LONG).show(); return; } if (!password.equals(rePassword)){ Toast.makeText(getApplicationContext(), "Passwords are different!", Toast.LENGTH_LONG).show(); return; } Cursor hasEmail= db.query("usersremote", null, "email =? ", new String[]{email}, null, null, null); if (hasEmail.moveToLast()){ Toast.makeText(getApplicationContext(), "The email has been registered", Toast.LENGTH_LONG).show(); }else{ ContentValues contentValues = new ContentValues(); contentValues.put("username", userName); contentValues.put("email", email); contentValues.put("password", <PASSWORD>); contentValues.put("phone_number", phoneNumber); contentValues.put("gender", gender); db.insert("usersremote", null, contentValues); Toast.makeText(getApplicationContext(), "Ok,please login", Toast.LENGTH_LONG).show(); } } } <file_sep>package com.example.buypool; import androidx.appcompat.app.AppCompatActivity; import android.app.Application; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { // This class is associate with Login activity //what it does is that it is able to implenement login function i.e verifys user details with database private Button btnLogin , btnSignup, getBtnLogin; private EditText email, password; private CheckBox remember; CurrentUserInfo userInfo ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnLogin = findViewById(R.id.btnLogin); btnSignup = findViewById(R.id.btnSignup); getBtnLogin = findViewById(R.id.ButtonLoginInto); email = findViewById(R.id.EnterEmail); password = findViewById(R.id.Password); remember = findViewById(R.id.checkBox); btnSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openSignUpActivity(); } }); getBtnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { storeUser(); } }); getUser(); } public void openSignUpActivity() { Intent intent = new Intent(this, SignUpActivity.class); startActivity(intent); } public void getUser(){ LocalDatabase helper = new LocalDatabase(getApplicationContext(), "Cards", null, 1); SQLiteDatabase db = helper.getWritableDatabase(); Cursor users = db.query("userslocal", null, null, null, null, null, null); if (users.moveToLast()){ int checked = users.getInt(3); if (checked == 1) { this.remember.setChecked(true); } String email = users.getString(1); String password = users.getString(2); this.email.setText(email); this.password.setText(password); } } public void storeUser(){ LocalDatabase helper = new LocalDatabase(getApplicationContext(), "Cards", null, 1); SQLiteDatabase db = helper.getWritableDatabase(); String email = this.email.getText().toString(); String password = this.password.getText().toString().trim(); Cursor usersremote = db.query("usersremote", null, "email=? and password=?", new String[]{email, password}, null, null, null); if (usersremote.moveToNext()){ userInfo = (CurrentUserInfo) getApplicationContext(); userInfo.setID(usersremote.getInt(0)); userInfo.setUserName(usersremote.getString(1)); userInfo.setPhoneNumber(usersremote.getString(4)); ContentValues contenValuses = new ContentValues(); contenValuses.put("email", email); if (this.remember.isChecked()){ contenValuses.put("is_remember", 1); contenValuses.put("password", <PASSWORD>); }else { contenValuses.put("is_remember", 0); contenValuses.put("password", ""); } int user = db.update("userslocal", contenValuses, "id = 1", null); }else { Toast.makeText(getApplicationContext(), "Username or Password Wrong!", Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(this, PublicBuyPoolDisplayPageActivity.class); startActivity(intent); } } <file_sep>package com.example.buypool; import android.os.Bundle; import android.os.PersistableBundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class MenuActivity extends AppCompatActivity { //uses to call activity buy_pool_display_page @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy_pool_display_page); } } <file_sep>include ':app' rootProject.name='buypool' <file_sep>package com.example.buypool; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import android.graphics.PorterDuff; import android.os.Bundle; import android.widget.TextView; public class NoticeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notice); //Set Tool Bar starts here Toolbar toolbar = findViewById(R.id.NoticeTooBar); setSupportActionBar(toolbar); TextView textView = toolbar.findViewById(R.id.toolbar_title); textView.setText("Notice"); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.getOverflowIcon().setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_ATOP); //Sets tool bar ends here } } <file_sep>package com.example.buypool; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.Manifest; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.PorterDuff; import android.location.Location; import android.os.Bundle; import android.os.StrictMode; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class PublicBuyPoolDisplayPageActivity extends AppCompatActivity { // This Class uses on Card Your BuyPoolDsplay activitys or Public gallery activitys , // This class used to control //1. Action bar //2.Implement returned information from database and fill it into each cards //3. go to other activity page i.e profile CurrentUserInfo userInfo; ArrayList<Model> models = new ArrayList<>(); LocalDatabase helper; SQLiteDatabase db; TextView view_temp; TextView view_desc; TextView view_city; ImageView view_weather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy_pool_display_page); helper= new LocalDatabase(getApplicationContext(), "Cards", null, 1); db = helper.getWritableDatabase(); //Tool Bar starts from here Toolbar toolbar = findViewById(R.id.buyPool_toolbar_title); setSupportActionBar(toolbar); TextView textView = toolbar.findViewById(R.id.toolbar_title); textView.setText("Public Card Gallery"); getSupportActionBar().setDisplayShowTitleEnabled(false); // Change color of the overflow 'The three dot' on Tool bar toolbar.getOverflowIcon().setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_ATOP); // Tool Bars ends here RecyclerView recyclerView = findViewById(R.id.recyclerViewBuyPoolPage); recyclerView.setLayoutManager(new LinearLayoutManager(this));//create a recycling view in a linear layout PublicCardAdapter myadapter = new PublicCardAdapter( this,getMyList(),userInfo); recyclerView.setAdapter(myadapter); //Recyckerview end here // weather api starts here view_city=findViewById(R.id.town); view_city.setText("If not show weather "); view_temp=findViewById(R.id.temp); view_temp.setText("This is due api delay by asking permssion Please restart the app "); view_desc=findViewById(R.id.desc); view_desc.setText(""); view_weather=findViewById(R.id.wheather_image); ActivityCompat.requestPermissions(PublicBuyPoolDisplayPageActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123); api_key(); onBackPressed(); } @Override public void onBackPressed() { //Provent go back to login page return; } //modifiy the return data as and set model private ArrayList<Model> getMyList(){ // Cursor cardlist = db.query("cards", null, null, null, null, null, null); userInfo = (CurrentUserInfo) getApplicationContext(); String sql = "SELECT title,description,address,date,cards.phone_number,username,gender,cardStatus,cards.id FROM cards,usersremote where create_userID = usersremote.id AND cardStatus != 1 AND cardStatus != 2 AND create_userID != ?;"; Cursor cardlist = db.rawQuery(sql, new String[]{""+userInfo.getID()}); while (cardlist.moveToNext()){ String title = cardlist.getString(0); String description = cardlist.getString(1); String address = cardlist.getString(2); String time = cardlist.getString(3).split(" ")[0]; String phoneNumber = cardlist.getString(4); String username = cardlist.getString(5); int gender = cardlist.getInt(6); int cardStatus = cardlist.getInt(7); int cardID = cardlist.getInt(8); Model m = new Model(); m.setTitle(title); m.setDesription(description); m.setImg(gender == 0?R.drawable.male:R.drawable.female); m.setDate(time); m.setAddress(address); m.setUserNameOnCard(username); m.setPhoneNumber(phoneNumber); m.setCardStatus(cardStatus); m.setCardID(cardID); models.add(m); } return models; } public boolean onCreateOptionsMenu(Menu menu) { // push menu icons onto the toolbars getMenuInflater().inflate(R.menu.buypooldisplaypage, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.Logout) { //change page should be here Intent intent = new Intent(this, MainActivity.class); startActivity(intent);} else if (id == R.id.toProfile) { Intent intent = new Intent(this, ProfileActivity.class); startActivity(intent); } return true; } private void api_key( ) { Gps gt = new Gps(getApplicationContext()); Location l = gt.getLocation(); if( l == null){ Toast.makeText(getApplicationContext(),"GPS unable to get Value",Toast.LENGTH_SHORT).show(); }else { double lat = l.getLatitude(); double lon = l.getLongitude(); OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder() .url("https://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&appid=a6f41d947e0542a26580bcd5c3fb90ef&units=metric") .get() .build(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { Response response= client.newCall(request).execute(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { String responseData= response.body().string(); try { JSONObject json=new JSONObject(responseData); JSONArray array=json.getJSONArray("weather"); JSONObject object=array.getJSONObject(0); String description=object.getString("description"); String icons = object.getString("icon"); JSONObject temp1= json.getJSONObject("main"); Double Temperature=temp1.getDouble("temp"); String City=json.getString("name"); setText(view_city,City); String temps=Math.round(Temperature)+" °C"; setText(view_temp,temps); setText(view_desc,description); setImage(view_weather,icons); } catch (JSONException e) { e.printStackTrace(); } } }); }catch (IOException e){ e.printStackTrace(); } } } private void setText(final TextView text, final String value){ runOnUiThread(new Runnable() { @Override public void run() { text.setText(value); } }); } private void setImage(final ImageView imageView, final String value){ // Reference https://github.com/Lukieoo/WheatherAplication runOnUiThread(new Runnable() { @Override public void run() { //paste switch switch (value){ case "01d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d01d)); break; case "01n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d01d)); break; case "02d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d02d)); break; case "02n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d02d)); break; case "03d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d03d)); break; case "03n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d03d)); break; case "04d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d04d)); break; case "04n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d04d)); break; case "09d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d09d)); break; case "09n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d09d)); break; case "10d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d10d)); break; case "10n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d10d)); break; case "11d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d11d)); break; case "11n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d11d)); break; case "13d": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d13d)); break; case "13n": imageView.setImageDrawable(getResources().getDrawable(R.drawable.d13d)); break; default: imageView.setImageDrawable(getResources().getDrawable(R.drawable.wheather)); } } }); } }
e19e931c6140a1613f71054079a4e82a16c0fa49
[ "Java", "Gradle" ]
9
Java
jiaru01/Android_Development
58b7ebb8e100dd9f0927fbcaadbf9c5d52db4526
9301953f4f77781f257bad22c16957b9a479e65a
refs/heads/master
<file_sep>module.exports = function(sequelize, DataTypes) { var Product = sequelize.define('Product', { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING }, category: { type: DataTypes.ENUM('Music', 'Movie', 'Book', 'Game') } }, { freezeTableName: true, classMethods: { associate: function(models) { Product.belongsToMany(models.User, { through: "Property" }); Product.belongsToMany(models.Borrow, { through: "Property" }); } } }); return Product; };
575b360deb02ae25bbc37ec3021136ffeda6a644
[ "JavaScript" ]
1
JavaScript
amelie-certin/Librarize
ff126c23596673fe5f5691b9fad13d0bc00caaf8
77807588ab32dadf1c97825124d8b67e0a7087ca
refs/heads/main
<repo_name>djberg96/ez-email<file_sep>/docker-compose.yml services: mailhog: image: mailhog/mailhog:latest restart: always logging: driver: 'none' # disable saving logs ports: - 1025:1025 # smtp server - 8025:8025 # web ui <file_sep>/Gemfile source 'https://rubygems.org' do gemspec end <file_sep>/spec/ez_email_spec.rb ######################################################################## # ez_email_spec.rb # # Specs for the EZ::Email library. These specs assume that you are # running the mailhog docker container on port 1025. # # Install docker and run "docker compose run mailhog" first. ######################################################################## require 'rspec' require 'ez/email' require 'socket' require 'etc' RSpec.describe EZ::Email do let(:host){ Socket.gethostname } let(:login){ Etc.getlogin } let(:port){ 1025 } before do @to = '<EMAIL>' @from = '<EMAIL>' @subj = 'This is a test' @body = 'How are you?' @opts = {:to => @to, :from => @from, :subject => @subj, :body => @body } @email = EZ::Email.new(@opts) end example "version is set to expected value" do expect(EZ::Email::VERSION).to eq('0.3.0') expect(EZ::Email::VERSION).to be_frozen end example "to getter method basic functionality" do expect(@email).to respond_to(:to) expect{ @email.to }.not_to raise_error expect(@email.to).not_to be_nil end example "to getter method returns expected value" do expect(@email.to).to eq(@to) end example "to setter method basic functionality" do expect(@email).to respond_to(:to=) expect{ @email.to = '<EMAIL>' }.not_to raise_error end example "to setter actually sets value" do @email.to = '<EMAIL>' expect('<EMAIL>').to eq(@email.to) end example "from getter basic functionality" do expect(@email).to respond_to(:from) expect{ @email.from }.not_to raise_error expect(@email.from).not_to be_nil end example "from setter basic functionality" do expect(@email).to respond_to(:from=) expect{ @email.from = '<EMAIL>' }.not_to raise_error end example "from method returns expected value" do expect(@email.from).to eq(@from) end example "from defaults to username@host if not set in constructor" do @email = EZ::Email.new(:to => 'x', :subject => 'x', :body => 'x') expected = login << '@' << host expect(@email.from).to eq(expected) end example "subject getter basic functionality" do expect(@email).to respond_to(:subject) expect{ @email.subject }.not_to raise_error expect(@email.subject).not_to be_nil end example "subject setter basic functionality" do expect(@email).to respond_to(:subject=) expect{ @email.subject = '<EMAIL>' }.not_to raise_error end example "subject method returns expected value" do expect(@email.subject).to eq(@subj) end example "body getter basic functionality" do expect(@email).to respond_to(:body) expect{ @email.body }.not_to raise_error expect(@email.body).not_to be_nil end example "body setter basic functionality" do expect(@email).to respond_to(:body=) expect{ @email.body = "Test" }.not_to raise_error end example "body method returns the expected value" do expect(@email.body).to eq(@body) end example "mail_host getter basic functionality" do expect(EZ::Email).to respond_to(:mail_host) expect{ EZ::Email.mail_host }.not_to raise_error expect(EZ::Email.mail_host).not_to be_nil end example "mail_host setter basic functionality" do expect(EZ::Email).to respond_to(:mail_host=) expect{ EZ::Email.mail_host = 'Test' }.not_to raise_error expect(EZ::Email.mail_host).to eq('Test') end example "mail_port singleton getter basic functionality" do expect(EZ::Email).to respond_to(:mail_port) end example "mail_port method returns the expected default value" do expect(EZ::Email.mail_port).to eq(25) end example "mail_port singleton setter basic functionality" do expect(EZ::Email).to respond_to(:mail_port=) expect{ EZ::Email.mail_port = port }.not_to raise_error expect(EZ::Email.mail_port).to eq(1025) end example "deliver singleton method basic functionality" do expect(EZ::Email).to respond_to(:deliver) end example "deliver singleton method works without error" do EZ::Email.mail_host = 'localhost' EZ::Email.mail_port = port expect{ EZ::Email.deliver(@opts) }.not_to raise_error end example "passing an invalid option to the constructor raises an error" do expect{ EZ::Email.send(:new, {:bogus => 77}) }.to raise_error(ArgumentError) end end <file_sep>/README.md ### Description A very easy interface for sending simple text based emails. ### Installation `gem install ez-email` ### Adding the trusted cert `gem cert --add <(curl -Ls https://raw.githubusercontent.com/djberg96/ez-email/main/certs/djberg96_pub.pem)` ### Synopsis ```ruby require 'ez-email' EZ::Email.deliver( :to => '<EMAIL>', :from => '<EMAIL>', :subject => 'Hello', :body => 'How are you?' ) ``` ### Rationale When I originally created this library the existing list of email handling libraries were either not designed for sending email, were extremely cumbersome, had lousy interfaces, or were no longer maintained. I just wanted to send a flippin' email! This library scratched that itch. Hopefully you will find its simplicity useful, too. Update: Since I wrote this there is also now the Pony library which is almost as simple and more flexible since it can also handle attachments, among other things. Consequently, these days I would generally recommend that library over this one for sending simple emails: https://github.com/benprew/pony However, I will continue to maintain this library for now. ### Local Testing To run the specs you will need a mail server running locally. If you do not already have a mail server running on port 1025 then install docker and run the following command: `docker compose run mailhog` Once the mailhog docker image is installed and a container is running, you can run the specs. You can also view the emails that were generated by pointing your web browser at http://localhost:8025 after running the specs for visual verification. ### Bugs None that I'm aware of. Please log any bug reports on the project page at https://github.com/djberg96/ez-email. ### License Apache-2.0 ### Copyright (C) 2009-2023, <NAME>, All Rights Reserved ### Author <NAME> <file_sep>/lib/ez-email.rb # frozen_string_literal: true require_relative 'ez/email' <file_sep>/MANIFEST.md - CHANGES.md - LICENSE - MANIFEST.md - README.md - Rakefile - docker-compose.yml - ez-email.gemspec - certs/djberg96_pub.pem - lib/ez-email.rb - lib/ez/email.rb - spec/ez_email_spec.rb <file_sep>/ez-email.gemspec require 'rubygems' Gem::Specification.new do |spec| spec.name = 'ez-email' spec.version = '0.3.0' spec.license = 'Apache-2.0' spec.summary = 'Really easy emails' spec.description = 'A very simple interface for sending email' spec.author = '<NAME>' spec.email = '<EMAIL>' spec.homepage = 'https://github.com/djberg96/ez-email' spec.test_file = 'spec/ez_email_spec.rb' spec.files = Dir['**/*'].reject{ |f| f.include?('git') } spec.cert_chain = Dir['certs/*'] spec.extra_rdoc_files = ['README.md', 'CHANGES.md', 'MANIFEST.md'] spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/ez-email', 'bug_tracker_uri' => 'https://github.com/djberg96/ez-email/issues', 'changelog_uri' => 'https://github.com/djberg96/ez-email/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/ez-email/wiki', 'source_code_uri' => 'https://github.com/djberg96/ez-email', 'wiki_uri' => 'https://github.com/djberg96/ez-email/wiki' } end <file_sep>/CHANGES.md ## 0.3.0 - 20-Oct-2020 - Switch test suite from test-unit to rspec. ## 0.2.2 - 3-Aug-2020 - Switch README, CHANGES and MANIFEST files to markdown format. ## 0.2.1 - 1-Jun-2020 - Added a LICENSE file to the distro as required by the Apache-2.0 license. ## 0.2.0 - 28-Jan-2019 - Changed license to Apache-2.0. - Fixed a bug where it was blowing up on a single "to" argument. - The VERSION constant is now frozen. - Added the ez-mail.rb file for convenience. - Modified code internally to use singletons instead of class variables. - Updated cert, should be good for about 10 years. - Added metadata to the gemspec. ## 0.1.5 - 12-Dec-2015 - This gem is now signed. - Updates to Rakefile and gemspec for gem signing. ## 0.1.4 - 8-Nov-2014 - Minor updates to gemspec and Rakefile. ## 0.1.3 - 9-Jan-2013 - Fixed a bug where the default 'from' value was not actually being set if it wasn't explicitly specified. - Refactored the tests and use test-unit 2 instead. ## 0.1.2 - 31-Aug-2011 - Refactored the Rakefile. Removed the old install task, added a clean task, added a default task, and reorganized the gem tasks. ## 0.1.1 - 27-Sep-2009 - Changed license to Artistic 2.0. - The mail host now defaults to localhost if the mailhost cannot be resolved. - Added the 'gem' Rake task. - Some gemspec updates. ## 0.1.0 - 23-Jan-2009 - Initial release
173803a9231dad36dff5c9efd1f700561c009892
[ "Markdown", "Ruby", "YAML" ]
8
YAML
djberg96/ez-email
6389ef5dea7a7b7702284eaed0e89271e8658ee8
48424ef116c554ff0cc0e5d78024f4f034f2b93e
refs/heads/master
<repo_name>life1347/ryu_ofp_error_parser<file_sep>/ofp_error_parser.py # all following information come from OpenFlow Spec v1.3 # https://www.opennetworking.org/images/stories/downloads/sdn-resources/onf-specifications/openflow/openflow-spec-v1.3.0.pdf OFPET_HELLO_FAILED = { 0: 'OFPHFC_INCOMPATIBLE, No compatible version.', 1: 'OFPHFC_EPERM, Permissions error.' } OFPET_BAD_REQUEST = { 0: 'OFPBRC_BAD_VERSION, ofp_header.version not supported.', 1: 'OFPBRC_BAD_TYPE, ofp_header.type not supported.', 2: 'OFPBRC_BAD_MULTIPART, ofp_multipart_request.type not supported.', 3: 'OFPBRC_BAD_EXPERIMENTER, Experimenter id not supported.', 4: 'OFPBRC_BAD_EXP_TYPE, Experimenter type not supported.', 5: 'OFPBRC_EPERM, Permissions error.', 6: 'OFPBRC_BAD_LEN, Wrong request length for type.', 7: 'OFPBRC_BUFFER_EMPTY, Specified buffer has already been used.', 8: 'OFPBRC_BUFFER_UNKNOWN, Specified buffer does not exist.', 9: 'OFPBRC_BAD_TABLE_ID, Specified table-id invalid or does not exist.', 10: 'OFPBRC_IS_SLAVE0, Denied because controller is slave.', 11: 'OFPBRC_BAD_PORT, Invalid port.', 12: 'OFPBRC_BAD_PACKET, Invalid packet in packet-out.', 13: 'OFPBRC_MULTIPART_BUFFER_OVERFLOW, ofp_multipart_request overflowed the assigned buffer.' } OFPET_BAD_ACTION = { 0: 'OFPBAC_BAD_TYPE, Unknown action type.', 1: 'OFPBAC_BAD_LEN, Length problem in actions.', 2: 'OFPBAC_BAD_EXPERIMENTER, Unknown experimenter id specified.', 3: 'OFPBAC_BAD_EXP_TYPE, Unknown action for experimenter id.', 4: 'OFPBAC_BAD_OUT_PORT, Problem validating output port.', 5: 'OFPBAC_BAD_ARGUMENT, Bad action argument.', 6: 'OFPBAC_EPERM, Permissions error.', 7: 'OFPBAC_TOO_MANY, Can not handle this many actions.', 8: 'OFPBAC_BAD_QUEUE, Problem validating output queue.', 9: 'OFPBAC_BAD_OUT_GROUP, Invalid group id in forward action.', 10: 'OFPBAC_MATCH_INCONSISTENT, Action can not apply for this match, or Set-Field missing prerequisite.', 11: 'OFPBAC_UNSUPPORTED_ORDER, Action order is unsupported for the action list in an Apply-Actions instruction.', 12: 'OFPBAC_BAD_TAG, Actions uses an unsupported tag / encap.', 13: 'OFPBAC_BAD_SET_TYPE, Unsupported type in SET_FIELD action.', 14: 'OFPBAC_BAD_SET_LEN, Length problem in SET_FIELD action.', 15: 'OFPBAC_BAD_SET_ARGUMENT, Bad argument in SET_FIELD action.' } OFPET_BAD_INSTRUCTION = { 0: 'OFPBIC_UNKNOWN_INST: Unknown instruction.', 1: 'OFPBIC_UNSUP_INST: Switch or table does not support the instruction.', 2: 'OFPBIC_BAD_TABLE_ID: Invalid Table-ID specified.', 3: 'OFPBIC_UNSUP_METADATA: Metadata value unsupported by datapath.', 4: 'OFPBIC_UNSUP_METADATA_MASK: Metadata mask value unsupported by datapath.', 5: 'OFPBIC_BAD_EXPERIMENTER: Unknown experimenter id specified.', 6: 'OFPBIC_BAD_EXP_TYPE: Unknown instruction for experimenter id.', 7: 'OFPBIC_BAD_LEN: Length problem in instructions.', 8: 'OFPBIC_EPERM: Permissions error.' } OFPET_BAD_MATCH = { 0: 'OFPBMC_BAD_TYPE: Unsupported match type specified by the match', 1: 'OFPBMC_BAD_LEN: Length problem in match.', 2: 'OFPBMC_BAD_TAG: Match uses an unsupported tag / encap.', 3: 'OFPBMC_BAD_DL_ADDR_MASK: Unsupported datalink addr mask - switch does not support arbitrary datalink address mask. ', 4: 'OFPBMC_BAD_NW_ADDR_MASK: Unsupported network addr mask - switch does not support arbitrary network address mask.', 5: 'OFPBMC_BAD_WILDCARDS: Unsupported combination of fields masked or omitted in the match.', 6: 'OFPBMC_BAD_FIELD: Unsupported field type in the match.', 7: 'OFPBMC_BAD_VALUE: Unsupported value in a match field.', 8: 'OFPBMC_BAD_MASK: Unsupported mask specified in the match, field is not dl-address or nw-address.', 9: 'OFPBMC_BAD_PREREQ: A prerequisite was not met.', 10: 'OFPBMC_DUP_FIELD: A field type was duplicated.', 11: 'OFPBMC_EPERM: Permissions error.' } OFPET_FLOW_MOD_FAILED = { 0: 'OFPFMFC_UNKNOWN: Unspecified error.', 1: 'OFPFMFC_TABLE_FULL: Flow not added because table was full.', 2: 'OFPFMFC_BAD_TABLE_ID: Table does not exist', 3: 'OFPFMFC_OVERLAP: Attempted to add overlapping flow with CHECK_OVERLAP flag set.', 4: 'OFPFMFC_EPERM: Permissions error.', 5: 'OFPFMFC_BAD_TIMEOUT Flow not added because of unsupported idle / hard timeout.', 6: 'OFPFMFC_BAD_COMMAND: Unsupported or unknown command.', 7: 'OFPFMFC_BAD_FLAGS: Unsupported or unknown flags.' } OFPET_GROUP_MOD_FAILED = { 0: 'OFPGMFC_GROUP_EXISTS: Group not added because a group ADD attempted to replace an already-present group.', 1: 'OFPGMFC_INVALID_GROUP: Group not added because Group specified is invalid.', 2: 'OFPGMFC_WEIGHT_UNSUPPORTED: Switch does not support unequal load sharing with select groups.', 3: 'OFPGMFC_OUT_OF_GROUPS: The group table is full.', 4: 'OFPGMFC_OUT_OF_BUCKETS: The maximum number of action buckets for a group has been exceeded.', 5: 'OFPGMFC_CHAINING_UNSUPPORTED: Switch does not support groups that forward to groups.', 6: 'OFPGMFC_WATCH_UNSUPPORTED: This group can not watch the watch_port or watch_group specified.', 7: 'OFPGMFC_LOOP: Group entry would cause a loop.', 8: 'OFPGMFC_UNKNOWN_GROUP: Group not modified because a group MODIFY attempted to modify a non-existent group.', 9: 'OFPGMFC_CHAINED_GROUP: Group not deleted because another group is forwarding to it.', 10: 'OFPGMFC_BAD_TYPE: Unsupported or unknown group type.', 11: 'OFPGMFC_BAD_COMMAND: Unsupported or unknown command.', 12: 'OFPGMFC_BAD_BUCKET: Error in bucket.', 13: 'OFPGMFC_BAD_WATCH: Error in watch port / group.', 14: 'OFPGMFC_EPERM: Permissions error.' } OFPET_PORT_MOD_FAILED = { 0: 'OFPPMFC_BAD_PORT, Specified port number does not exist.', 1: 'OFPPMFC_BAD_HW_ADDR, Specified hardware address does not match the port number.', 2: 'OFPPMFC_BAD_CONFIG, Specified config is invalid.', 3: 'OFPPMFC_BAD_ADVERTISE, Specified advertise is invalid.', 4: 'OFPPMFC_EPERM, Permissions error.' } OFPET_TABLE_MOD_FAILED = { 0: 'OFPTMFC_BAD_TABLE, Specified table does not exist.', 1: 'OFPTMFC_BAD_CONFIG, Specified config is invalid.', 2: 'OFPTMFC_EPERM, Permissions error.' } OFPET_QUEUE_OP_FAILED = { 0: 'OFPQOFC_BAD_PORT, Invalid port (or port does not exist).', 1: 'OFPQOFC_BAD_QUEUE, Queue does not exist.', 2: 'OFPQOFC_EPERM, Permissions error.' } OFPET_SWITCH_CONFIG_FAILED = { 0: 'OFPSCFC_BAD_FLAGS, Specified flags is invalid.', 1: 'OFPSCFC_BAD_LEN, Specified len is invalid.', 2: 'OFPQCFC_EPERM, Permissions error.' } OFPET_ROLE_REQUEST_FAILED = { 0: 'OFPRRFC_STALE, Stale Message: old generation_id.', 1: 'OFPRRFC_UNSUP, Controller role change unsupported.', 2: 'OFPRRFC_BAD_ROLE, Invalid role.' } OFPET_METER_MOD_FAILED = { 0: 'OFPMMFC_UNKNOWN, Unspecified error.', 1: 'OFPMMFC_METER_EXISTS, Meter not added because a Meter ADD attempted to replace an existing Meter.', 2: 'OFPMMFC_INVALID_METER, Meter not added because Meter specified is invalid.', 3: 'OFPMMFC_UNKNOWN_METER, Meter not modified because a Meter MODIFY attempted to modify a non-existent Meter.', 4: 'OFPMMFC_BAD_COMMAND, Unsupported or unknown command.', 5: 'OFPMMFC_BAD_FLAGS, Flag configuration unsupported.', 6: 'OFPMMFC_BAD_RATE, Rate unsupported.', 7: 'OFPMMFC_BAD_BURST, Burst size unsupported.', 8: 'OFPMMFC_BAD_BAND, Band unsupported.', 9: 'OFPMMFC_BAD_BAND_VALUE, Band value unsupported.', 10: 'OFPMMFC_OUT_OF_METERS, No more meters available.', 11: 'OFPMMFC_OUT_OF_BANDS, The maximum number of properties for a meter has been exceeded.' } OFPET_TABLE_FEATURES_FAILED = { 0: 'OFPTFFC_BAD_TABLE, Specified table does not exist.', 1: 'OFPTFFC_BAD_METADATA, Invalid metadata mask.', 2: 'OFPTFFC_BAD_TYPE, Unknown property type.', 3: 'OFPTFFC_BAD_LEN, Length problem in properties.', 4: 'OFPTFFC_BAD_ARGUMENT, Unsupported property value.', 5: 'OFPTFFC_EPERM, Permissions error.' } # OFPET_EXPERIMENTER = {} of_error_msg = { 0: ('OFPET_HELLO_FAILED', OFPET_HELLO_FAILED), 1: ('OFPET_BAD_REQUEST', OFPET_BAD_REQUEST), 2: ('OFPET_BAD_ACTION', OFPET_BAD_ACTION), 3: ('OFPET_BAD_INSTRUCTION', OFPET_BAD_INSTRUCTION), 4: ('OFPET_BAD_MATCH', OFPET_BAD_MATCH), 5: ('OFPET_FLOW_MOD_FAILED', OFPET_FLOW_MOD_FAILED), 6: ('OFPET_GROUP_MOD_FAILED', OFPET_GROUP_MOD_FAILED), 7: ('OFPET_PORT_MOD_FAILED', OFPET_PORT_MOD_FAILED), 8: ('OFPET_TABLE_MOD_FAILED', OFPET_TABLE_MOD_FAILED), 9: ('OFPET_QUEUE_OP_FAILED', OFPET_QUEUE_OP_FAILED), 10: ('OFPET_SWITCH_CONFIG_FAILED', OFPET_SWITCH_CONFIG_FAILED), 11: ('OFPET_ROLE_REQUEST_FAILED', OFPET_ROLE_REQUEST_FAILED), 12: ('OFPET_METER_MOD_FAILED', OFPET_METER_MOD_FAILED), 13: ('OFPET_TABLE_FEATURES_FAILED', OFPET_TABLE_FEATURES_FAILED), # 65535: ('OFPET_EXPERIMENTER', OFPET_EXPERIMENTER) } def parse_ofp_err_msg(err_type, err_code): err_type, err_codes = of_error_msg.get(err_type) err_code = err_codes.get(err_code) return (err_type, err_code) <file_sep>/README.md # Intro: Ryu_ofp_error_parser is the OpenFlow error msg parser. All information come from OpenFlow Spec v1.3 https://www.opennetworking.org/images/stories/downloads/sdn-resources/onf-specifications/openflow/openflow-spec-v1.3.0.pdf # Usage: ```python from of_error import parse_ofp_err_msg error_type_msg, error_code_msg = parse_ofp_err_msg(err_type, err_code) ```
3ce5b82c7fffae15e6273b56705cfc144094f41c
[ "Markdown", "Python" ]
2
Python
life1347/ryu_ofp_error_parser
d5d7a429749f4645d044063119732e6062afa201
1808de813257f3292e227f0bf90976e7fa9adbd0
refs/heads/master
<repo_name>bartlab2/Hello<file_sep>/hello/src/hello/Hello.java package hello; public class Hello { public static void main(String args[]){ System.out.println("Hello1"); System.out.println("Hera am I"); } }
69ac11efde8630eec2257bec93fb4fa5890ffe62
[ "Java" ]
1
Java
bartlab2/Hello
80a413048ef5729913203101b3c10231dc10438f
cf6abcbfd9b388460fe3bd4c025fd73cddfecedc
refs/heads/master
<repo_name>barrazamiguel/rpgWebReact<file_sep>/README.md # rpgWebReact test de react <file_sep>/src/components/Juego.js import React from 'react'; export default class Juego extends React.Component { constructor(props) { super(props); this.state ={ pj: props.location.state.pj, info: "Realiza tu primer ataque." } } render() { return ( <div> <h1>Datos:</h1> <p>{this.state.pj.nombre}, vida: {this.state.pj.vida}</p> <br /> <h1>Historial:</h1> <div aria-live="polite"> <p>{this.state.info}</p> </div> <br /> <h1>Ataques</h1> {this.state.pj.ataques.map((ataque, index) => <button onClick={(e) => this.atacar(e, ataque)}>{ataque.nombre}</button>)} </div> ); } atacar(e, ataque) { e.preventDefault(); this.setState({ info: ataque.nombre }); } } <file_sep>/src/App.js import React, { Component } from 'react'; import { HashRouter, Route, Switch } from 'react-router-dom' import Home from './components/Home'; import SeleccionarPersonaje from './components/SeleccionarPersonaje'; import Juego from './components/Juego'; export default class App extends Component { render() { return ( <HashRouter> <Switch> <Route path="/" component={Home} exact/> <Route path="/select" component={SeleccionarPersonaje} exact/> <Route path="/game" component={Juego} exact/> </Switch> </HashRouter> ); } } <file_sep>/src/components/Home.js import React from 'react'; import { Link } from "react-router-dom"; export default class Home extends React.Component { constructor(props) { super(props); this.state ={ pj: props.pj } } render() { return ( <div> <h1>Bienvenido:</h1> <br /> <p>este es un juego mas.<br /> <Link to="/select">Iniciar</Link> </p> </div> ); } } <file_sep>/src/components/SeleccionarPersonaje.js import React from 'react'; import {PJS} from '../datos'; export default class SeleccionarPersonaje extends React.Component { constructor(props) { super(props); this.state ={ pj: PJS[0] } } render() { return ( <div> <form onSubmit={this.seleccionar.bind(this)}> <p>Seleccione con que personaje desea jugar:</p> <p><select onChange={this.datosPj.bind(this)}> {PJS.map((pj, index) => <option value={index}>{pj.nombre}</option>)} </select></p> <div aria-live="polite"> <p><h1>Datos de {this.state.pj.nombre}:</h1> puntos de vida: {this.state.pj.vida}.</p> </div> <p><input type="submit" value="seleccionar" /></p> </form> </div> ); } datosPj(e) { this.setState({ pj: PJS[e.target.value] }); } seleccionar(e) { e.preventDefault(); this.props.history.push({ pathname: '/game', state: { pj: this.state.pj } }) } } <file_sep>/src/datos.js class Pj { constructor(nombre, vida) { this.nombre = nombre; this.vida = vida; this.ataques = []; } addAttack(ataque) { this.ataques.push(ataque); } } class Ataque { constructor(nombre, poder) { this.nombre = nombre; this.poder = poder; } } // ataques: let patada = new Ataque("patada", 3); let golpe = new Ataque("golpe", 2); // declaracion de personajes: let juan = new Pj("juan", 20); juan.addAttack(patada); juan.addAttack(golpe); let sofia = new Pj("sofia", 30); sofia.addAttack(golpe); // enemigos: let jorge = new Pj("jorge", 20); jorge.addAttack(patada); jorge.addAttack(golpe); export const PJS = [ juan, sofia ]; export const PNJ = [jorge];
34c35c5f38fa6d56338c80c6ad19534540d0227c
[ "Markdown", "JavaScript" ]
6
Markdown
barrazamiguel/rpgWebReact
ceece73b872e45e9b76bbb4f3edbb2c5565ffb6e
48af2ac06e0d3600c6c749ece0273dc466228779
refs/heads/master
<file_sep>import { createElement, updateElement } from './dom' export function render(component, container) { let {type,props} = component let element = createElement({type:type}) for (let key in props) { if(key === 'children') { if(typeof props[key] === 'object'){ props[key].forEach(item => { if(typeof item === 'object'){ render(item,element) }else { element.appendChild(createElement({type:String,value:item})) } }) } else { element.appendChild(createElement({type:String,value:props[key]})) } } else { let attribute = {} attribute[key] = props[key] updateElement({attributes: attribute}, element) } } container.appendChild(element) }<file_sep> react code learn
c357999f02f54d9636576ac073a7de3eb8c9f15d
[ "JavaScript", "Markdown" ]
2
JavaScript
newship/react-code-learn
e035be63207245b8aaa778fd7485782a98dbd36f
08145cba824f75954c8e01b12ab81d5f20c0ab8c
refs/heads/master
<repo_name>Juande10/-MIA-_201314412<file_sep>/main.c //*************LIBRERIAS****************** #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #include <dirent.h> #include <stdbool.h> #include <unistd.h> #include <sys/stat.h> //***************STRUCTS***************** typedef struct { //ESTRUCTURA DE LOS COMANDOS char comando [100]; } Comando; typedef struct { char part_status; //indica si esta activa o no char part_type; //indica si es primaria o extendida [P o E] char part_fit; //Tipo de ajuste de la particion [B(best),F(first),W(worst)] int part_start; //indica en que byte del disco inicia la particion int part_size; //Contiene el tamaño total de la particion char part_name[16]; //Nombre de la particion } struct_particion; typedef struct { char mbr_fecha_creacion[16]; //Fecha y hora de creación del disco int mbr_tamano; //tamaño total del disco en bytes int mbr_disk_signature; //numero random que identifica de forma unica cada disco struct_particion mbr_particiones[4]; //info de la particion 1 } struct_mbr; //TAMAÑO 136 BYTES typedef struct { char part_status; //Inidica si la particion esta activa o no char part_fit; //Tipo de ajuste de la particion [B(best),F(first),W(worst)] int part_start; //Indica en que byte del disco inicia la particion int part_size; //Contiene el tamaño total de la particion en bytes int part_next; //byte que esta el proximo EBR, -1 si no hay char part_name[16]; //Nombre de la particion } struct_ebr; //TAMAÑO 32 BYTES typedef struct { //ESTRUCTURA PARA LOS MONTADOS int estado; char id[6]; char nombre[16]; //Nombre de la particion montada char fecha_montado[16]; //Fecha y hora del montado } PosicionMontado; typedef struct { char path[200]; PosicionMontado posicion[26]; } Montado; //**************VARS GLOBALES************ Montado montados[50]; Comando Comandos[20]; char letras[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; //********************PROTOTIPOS*********************** void Mkdisk(Comando comando[]); //METODO PARA CREAR DISCOS void VerificarPath(char Path[]); //Verificar si una path existe o sino crearla void CrearDisco(char cadena[], char unit[],char name[], int size); //Metodo donde se crea el disco void Rmdisk(Comando comando[]); //METODO PARA ELIMINAR DISCOS void Fdisk(Comando comando[]); //METODO PARA MODIFICAR PARTICIONES void CrearParticion(char path[], int size, char unit[], char type[], char fit[], char Name[]); //METODO DONDE SE CREAN LAS PARTICIONES void EliminarParticion(char path[], char deletev[], char name[]); //METODO DONDE SE ELIMINAN LAS PARTICIONES void ModificarParticion(char path[], char unit[], int add, char name[]); //METODO DONDE SE MODIFICAN LAS PARTICIONES void Mount(Comando comando[]); //METODO DONDE SE MONTA void Umount(Comando comando[]); //METODO DONDE SE DESMONTA void Reporte(Comando comando[]); //METODO DONDE SE GENERAN LOS REPORTES void VerificarPathReporte(char Path[]); //Verificar si una path existe o sino crearla void GenerarReporteMBR(char disco[], char archivosalida[]); //REPORTE DE MBR void GenerarReporteDisk(char nombreArchivo[], char nombreSalida[]); //REPORTE DE DISCO void Exec(Comando comando[]); //METODO DONDE SE LEE EL ARCHIVO PARA EJECUTAR LAS INSTRUCCIONES EN OTRO METODO void EjecutarScript(char instruccion[]); //METODO DONDE SE EJECUTAN LOS SCRIPT DEL EXEC //PROTOTIPOS AUXILIARES int ContarSlash(char path[]); void cambio(char aux[]); void limpiarvar(char aux[], int n); char** SplitComando(char* texto, const char caracter_delimitador); int ContarSlash(char *path); int CantidadParticionesPrimarias(struct_mbr mbr); int CantidadParticionesExtendidas(struct_mbr mbr); void InicializarMontados(); int main(){ InicializarMontados(); printf("PROYECTO MANEJO E IMPLEMENTACION DE ARCHIVOS \n"); printf("SECCION A+\n"); printf("201314412\n\n"); printf("CONSOLA DE COMANDOS\n\n"); int salida = 0; while(salida != 1){ int i; for (i = 0; i < 25; i++) { strcpy(Comandos[i].comando, "VACIO"); } char comando[200]; //variable donde se ira guardando cada linea de comando limpiarvar(comando, 200); char comando2[200]; //variable donde se ira guardando cada linea de comando limpiarvar(comando2, 200); printf("Juande@juande: "); fgets(comando, 200, stdin); cambio(comando); //printf("El comando es: %s \n", comando); char** tokens, tokens2; char * completo; char** variables; char * completo2; char** ssplit; //segundo split con : int count = 0; bool multi = false; tokens = SplitComando(comando, ' '); //separando el comando por espacios en blanco if(tokens){ int i; for (i = 0; *(tokens + i); i++){ char * valor = *(tokens + i); if(valor[0] == '\\'){ multi = true; fgets(comando2, 200, stdin); cambio(comando2); strcat(comando, " "); strcat(comando, comando2); free(tokens); }else{ if(i!=0){ strcat(comando, " "); strcat(comando, valor); } } } } //printf("El comando es: %s \n", comando); tokens = SplitComando(comando, ' '); //separando el comando por espacios en blanco if (tokens) { int i; for (i = 0; *(tokens + i); i++){ completo = *(tokens + i); variables = SplitComando(completo, ':'); if (variables) { int j; for (j = 0; *(variables + j); j++) { completo2 = *(variables + j); ssplit = SplitComando(completo2, ':'); if(ssplit){ int k; for (k = 0; *(ssplit + k); k++) { char * valor = *(ssplit + k); strcpy(comando,valor); strcpy(Comandos[count].comando,valor); count++; } free(ssplit); } } free(variables); } } free(tokens); } // int re; // for (re = 0; re < 25; re++) { // printf("Comando %i : %s \n",re,Comandos[re].comando); // } //rep -id::vda1 -path::/home/juande/Escritorio/disco1.jpg -name::disk printf("\n"); if (strcasecmp(Comandos[0].comando, "mkdisk") == 0) { printf("CREACION DE DISCO DURO \n"); Mkdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "rmdisk") == 0) { printf("ELIMINACION DE DISCO DURO \n"); Rmdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "fdisk") == 0) { printf("EDICION DE PARTICIONES \n"); Fdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "mount") == 0) { printf("MONTAR PARTICION \n"); Mount(Comandos); } else if (strcasecmp(Comandos[0].comando, "umount") == 0) { printf("DESMONTAR PARTICION \n"); Umount(Comandos); } else if (strcasecmp(Comandos[0].comando, "rep") == 0) { printf("REPORTES \n"); Reporte(Comandos); } else if (strcasecmp(Comandos[0].comando, "exec") == 0) { Exec(Comandos); }else if (strcasecmp(Comandos[0].comando, "clear") == 0) { system("clear"); printf("PROYECTO MANEJO E IMPLEMENTACION DE ARCHIVOS \n"); printf("SECCION A\n"); printf("201314412\n\n"); printf("CONSOLA DE COMANDOS\n\n"); } else if (strcasecmp(Comandos[0].comando, "exit") == 0) { salida = 1; } else if (Comandos[0].comando[0] == '#') { printf("Comentario\n\n"); } else { printf("COMANDO INVALIDO \n\n"); } } return 0; } void Mkdisk(Comando comando[]){ //METODO PARA CREAR DISCOS srand(time(NULL)); //semilla para el numero random //variables para almacenar datos int size; char unit[2] = "m"; char name[50]; limpiarvar(name,50); char path[200]; limpiarvar(path, 200); char cadena[200] = ""; //path para usar en el fopen limpiarvar(cadena, 200); //booleanos para verificar existencia bool existesize = false; bool existepath = false; bool existename = false; bool error = false; int i = 1; while (strcasecmp(comando[i].comando, "vacio") != 0){ if (strcasecmp(comando[i].comando, "-size") == 0){ i++; size = atoi(comando[i].comando); if (size >= 0) { existesize = true; } else { printf("Tamaño para el disco incorrecto debe ser mayor a cero \n"); error = true; } } else if (strcasecmp(comando[i].comando, "+unit") == 0) { i++; strcpy(unit, comando[i].comando); if (strcasecmp(unit, "m") != 0 && strcasecmp(unit, "k") != 0) { printf("Parametro de unidad incorrecto [m|k] \n"); char unit[2] = "m"; error = true; } } else if (strcasecmp(comando[i].comando, "-path") == 0) { i++; strcpy(path, comando[i].comando); if (path[0] == '\"') { int a; for (a = i + 1; a < 25; a++) { if (strcasecmp(comando[a].comando, "-size") != 0 && strcasecmp(comando[a].comando, "+unit") != 0 && strcasecmp(comando[a].comando, "-name") != 0 && strcasecmp(comando[a].comando, "vacio") != 0 && strcasecmp(comando[a].comando, "\\") != 0) { strcat(path, " "); strcat(path, comando[a].comando); } else { i = a - 1; a = 25; } } } existepath = true; } else if (strcasecmp(comando[i].comando, "-name") == 0) { i++; strcpy(name, comando[i].comando); if (name[0] == '\"') { int a; for (a = i + 1; a < 25; a++) { if (strcasecmp(comando[a].comando, "-size") != 0 && strcasecmp(comando[a].comando, "+unit") != 0 && strcasecmp(comando[a].comando, "-path") != 0 && strcasecmp(comando[a].comando, "vacio") != 0 && strcasecmp(comando[a].comando, "\\") != 0) { strcat(name, " "); strcat(name, comando[a].comando); } else { i = a - 1; a = 25; } } } char *token; char extension[50]; limpiarvar(extension,50); bool valida = false; strcpy(extension,name); token = strtok(extension, "."); while (token != NULL) { if (strcasecmp(token, "dsk\"") == 0 || strcasecmp(token, "dsk\"\n") == 0) { valida = true; } token = strtok(NULL, "."); } if(valida == false){ printf("Nombre del disco con extension incorrecta \n"); error = true; } existename = true; } i++; } if (existesize == false || existepath == false || existename == false) { printf("FALTAN PARAMETROS PARA COMPLETAR EL PROCESO DE CREACION DE DISCOS (SIZE|PATH|NAME) \n\n"); }else{ if(strcasecmp(unit,"k")==0){ if(size<10240){ printf("El tamano minimo para crear un disco es de 10mb \n"); error = true; } }else if(strcasecmp(unit,"m")==0){ if(size<10){ printf("El tamano minimo para crear un disco es de 10mb \n"); error = true; } } if (error == false) { VerificarPath(path); CrearDisco(path, unit,name, size); } else { printf("EL COMANDO CONTIENE ERRORES \n"); } } } void VerificarPath(char Path[]){ char cmd[200] = "mkdir -m 777 "; char path[200]; limpiarvar(path, 200); int slash = ContarSlash(Path); strcpy(path, Path); char** carpetas; char auxiliar[200] = ""; char pathauxiliar[200]; limpiarvar(pathauxiliar,200); DIR *dirp; if (path[0] == '\"'){ //La path trae espacios en blanco char com[200]; limpiarvar(com,200); int esp; int pos = 0; for(esp = 1; esp<200;esp++){ if(path[esp] == '\"'){ esp = 200; }else{ pathauxiliar[pos] = path[esp]; pos++; } } carpetas = SplitComando(pathauxiliar, '/'); //separar la path por cada directorio if (carpetas) //si la lista no esta vacia { int i; //for (i = 0; *(carpetas + i) ; i++) for (i = 0; i < slash-1; i++) { limpiarvar(com,200); limpiarvar(cmd,200); com[0] = '\"'; strcpy(cmd,"mkdir -m 777 "); strcat(auxiliar, "/"); strcat(auxiliar, *(carpetas + i)); strcat(com,auxiliar); strcat(com, "\""); strcat(cmd,com); if((dirp = opendir(auxiliar))== NULL){ system(cmd); //printf("No existe carpeta \n"); } //printf("%s \n",auxiliar); //if (mkdir(auxiliar, S_IRWXU) == 0) { // printf("Directorio inexistente, se ha creado la carpeta: %s \n", auxiliar); //} } free(*(carpetas + i)); } free(carpetas); } else { carpetas = SplitComando(path, '/'); //separar el comando introducido por slash if (carpetas) //si la lista no esta vacia { int i; //for (i = 0; *(carpetas + i) ; i++) for (i = 0; i < slash -1 ; i++) { strcat(auxiliar, "/"); strcat(auxiliar, *(carpetas + i)); //printf("%s \n",auxiliar); //if (mkdir(auxiliar, S_IRWXU) == 0) { // printf("Directorio inexistente, se ha creado la carpeta: %s \n", auxiliar); //} strcat(cmd, "/"); strcat(cmd, *(carpetas + i)); if((dirp = opendir(auxiliar))== NULL){ system(cmd); //printf("No existe carpeta \n"); } } free(*(carpetas + i)); //printf("\n"); } } } void VerificarPathReporte(char Path[]){ char cmd[200] = "mkdir -m 777 "; char path[200]; limpiarvar(path, 200); int slash = ContarSlash(Path); strcpy(path, Path); char** carpetas; char auxiliar[200] = ""; char pathauxiliar[200]; limpiarvar(pathauxiliar,200); DIR *dirp; if (path[0] == '\"'){ //La path trae espacios en blanco char com[200]; limpiarvar(com,200); int esp; int pos = 0; for(esp = 1; esp<200;esp++){ if(path[esp] == '\"'){ esp = 200; }else{ pathauxiliar[pos] = path[esp]; pos++; } } carpetas = SplitComando(pathauxiliar, '/'); //separar la path por cada directorio if (carpetas) //si la lista no esta vacia { int i; //for (i = 0; *(carpetas + i) ; i++) for (i = 0; i < slash-1; i++) { limpiarvar(com,200); limpiarvar(cmd,200); com[0] = '\"'; strcpy(cmd,"mkdir -m 777 "); strcat(auxiliar, "/"); strcat(auxiliar, *(carpetas + i)); strcat(com,auxiliar); strcat(com, "\""); strcat(cmd,com); if((dirp = opendir(auxiliar))== NULL){ system(cmd); //printf("No existe carpeta \n"); } //printf("%s \n",auxiliar); //if (mkdir(auxiliar, S_IRWXU) == 0) { // printf("Directorio inexistente, se ha creado la carpeta: %s \n", auxiliar); //} } free(*(carpetas + i)); } free(carpetas); } else { carpetas = SplitComando(path, '/'); //separar el comando introducido por slash if (carpetas) //si la lista no esta vacia { int i; //for (i = 0; *(carpetas + i) ; i++) for (i = 0; i < slash-1 ; i++) { strcat(auxiliar, "/"); strcat(auxiliar, *(carpetas + i)); //printf("%s \n",auxiliar); //if (mkdir(auxiliar, S_IRWXU) == 0) { // printf("Directorio inexistente, se ha creado la carpeta: %s \n", auxiliar); //} strcat(cmd, "/"); strcat(cmd, *(carpetas + i)); if((dirp = opendir(auxiliar))== NULL){ system(cmd); //printf("No existe carpeta \n"); } } free(*(carpetas + i)); //printf("\n"); } } } void CrearDisco(char cadena[], char unit[],char name[], int size){ char auxcadena[200]; limpiarvar(auxcadena, 200); char auxnombre[50]; limpiarvar(auxnombre,50); if (name[0] == '\"') { int x; int y = 0; for (x = 1; x < 50; x++) { if (name[x] == '\"') { x = 50; } else { auxnombre[y] = name[x]; y++; } } } else { strcpy(auxnombre, name); } if (cadena[0] == '\"') { int x; int y = 0; for (x = 1; x < 200; x++) { if (cadena[x] == '\"') { x = 200; } else { auxcadena[y] = cadena[x]; y++; } } } else { strcpy(auxcadena, cadena); } strcpy(cadena, auxcadena); //strcat(cadena,"/"); strcat(cadena,auxnombre); int espaciorestante; //Variable para obtener el espacio restante en el disco despues de escribir el mbr int cont; int tamanodeldisco = size; FILE *disco; struct_mbr mbr; struct_particion particion; particion.part_status = '0'; particion.part_type = 'N'; particion.part_fit = 'N'; particion.part_start = 0; particion.part_size = 0; strcpy(particion.part_name, "\0"); for (cont = 0; cont < 4; cont++) { mbr.mbr_particiones[cont] = particion; } int tamanombr = sizeof (struct_mbr); //el mbr ocupa 136bytes mbr.mbr_disk_signature = (rand() % 10); time_t hora = time(0); struct tm *tlocal = localtime(&hora); strftime(mbr.mbr_fecha_creacion, 16, "%d/%m/%y %H:%S", tlocal); disco = fopen(cadena, "rb+"); if (disco == NULL) { if (strcasecmp(unit, "m") == 0) { espaciorestante = (size * 1024 * 1024) - sizeof (mbr); tamanodeldisco = tamanodeldisco * 1024 * 1024; /*for(cont = 0; cont<(size*1024*1024);cont++){ fwrite("\0",sizeof(char),1,disco); }*/ } else if (strcasecmp(unit, "k") == 0) { espaciorestante = (size * 1024) - sizeof (mbr); tamanodeldisco = tamanodeldisco * 1024; /*for(cont = 0; cont<(size*1024);cont++){ fwrite("\0",sizeof(char),1,disco); }*/ } disco = fopen(cadena, "wb"); mbr.mbr_tamano = tamanodeldisco; fwrite(&mbr, sizeof (mbr), 1, disco); fseek(disco, sizeof (mbr) + 1, SEEK_SET); char relleno = '\0'; //variable con la que se va a rellenar el disco duro for (cont = 0; cont < espaciorestante - 1; cont++) { fwrite(&relleno, 1, 1, disco); } rewind(disco); //Regresa el puntero al inicio del archivo printf("Se creo un disco \n"); printf("Tamaño: %i bytes \n", tamanodeldisco); printf("Ruta: %s \n\n", cadena); }else{ printf("El disco ya existe\n"); } fclose(disco); } void Rmdisk(Comando comando[]){ //METODO PARA ELIMINAR DISCOS char resp[5]; //variable que almacena limpiarvar(resp, 5); char path[200]; limpiarvar(path, 200); char pathaux[200]; limpiarvar(pathaux, 200); int cont = 0; //bool para verificar si existe parametro obligatorio bool existepath = false; while (strcasecmp(comando[cont].comando, "vacio") != 0) { if (strcasecmp(comando[cont].comando, "-path") == 0) { strcpy(pathaux, comando[cont + 1].comando); if (pathaux[0] == '\"') { int a; for (a = cont + 2; a < 25; a++) { if (strcasecmp(comando[a].comando, "-size") != 0 && strcasecmp(comando[a].comando, "-unit") != 0 && strcasecmp(comando[a].comando, "vacio") != 0) { strcat(pathaux, " "); strcat(pathaux, comando[a].comando); } else { a = 25; } } } existepath = true; } cont++; } if (pathaux[0] == '\"') { int x; int y = 0; for (x = 1; x < 200; x++) { if (pathaux[x] == '\"') { x = 200; } else { path[y] = pathaux[x]; y++; } } } else { strcpy(path, pathaux); } if (existepath == true) { FILE *archivo; archivo = fopen(path, "rb"); if (archivo == NULL) { printf("El disco no existe \n\n"); } else { printf("Esta seguro que desea eliminar esta unidad: [Y/N] \n"); fgets(resp, 5, stdin); cambio(resp); if (strcasecmp(resp, "y") == 0) { if (remove(path) == 0) { printf("El disco ha sido eliminado de forma exitosa \n\n"); } else { printf("Error al tratar de eliminar disco \n\n"); } } else { printf("Eliminacion cancelada \n\n"); } fclose(archivo); } } else { printf("Error, parametros faltantes [path] o incorrectos \n\n "); } } void Fdisk(Comando comando[]) { //variables para almacenar los valores int size; //tamaño de la particion ingresada por usuario char unit[2] = "k"; //unidad en la que se tomara el tamaño [b|k|m] char pathaux[200]; // path auxiliar que se usara por si la path trae comillas limpiarvar(pathaux, 200); char path[200]; // path del disco donde se va a crear la particion limpiarvar(path, 200); char type[2] = "p"; //tipo de particion [primaria o extendida] char fit[3] = "W"; //tipo de ajustes char deletev[6]; // Se eliminara una particion ya sea Fast (solo se deja inactiva) o FULL (se borra todo y se deja con \0) limpiarvar(deletev, 6); char name[16]; //Nombre de la particion, no se debe repetir limpiarvar(name, 16); char auxname[16]; //Nombre de la particion, no se debe repetir limpiarvar(auxname, 16); int add; //Para modificar el tamaño de la particion, si es negativo se le quita y si es positivo se le agrega //booleanos para saber que existen los parametros bool existesize = false; bool existeunit = false; bool existepath = false; bool existetype = false; bool existefit = false; bool existedelete = false; bool existename = false; bool existeadd = false; bool errors = false; //Variable para saber si existe algun error en el comando int cont = 0; //contador para recorrer el vector de comandos while (strcasecmp(comando[cont].comando, "vacio") != 0) { if (strcasecmp(comando[cont].comando, "-size") == 0) { size = atoi(comando[cont + 1].comando); if (size > 0) { existesize = true; } else { printf("El parametro \"Size\" debe ser mayor a 0\n"); errors = true; //existe un error } } else if (strcasecmp(comando[cont].comando, "+unit") == 0) { strcpy(unit, comando[cont + 1].comando); if (strcasecmp(unit, "b") != 0 && strcasecmp(unit, "k") != 0 && strcasecmp(unit, "m") != 0) { printf("Parametro incorrecto unit debe ser [b|k|m] \n"); errors = true; //existe un error } else { existeunit = true; } } else if (strcasecmp(comando[cont].comando, "-path") == 0) { strcpy(pathaux, comando[cont + 1].comando); if (pathaux[0] == '\"') { int a; for (a = cont + 2; a < 25; a++) { if (strcasecmp(comando[a].comando, "-size") != 0 && strcasecmp(comando[a].comando, "+unit") != 0 && strcasecmp(comando[a].comando, "-path") != 0 && strcasecmp(comando[a].comando, "+type") != 0 && strcasecmp(comando[a].comando, "+fit") != 0 && strcasecmp(comando[a].comando, "+delete") != 0 && strcasecmp(comando[a].comando, "-name") != 0 && strcasecmp(comando[a].comando, "+add") != 0 && strcasecmp(comando[a].comando, "vacio") != 0) { strcat(pathaux, " "); strcat(pathaux, comando[a].comando); } else { a = 25; } } } if (pathaux[0] == '\"') { //Quitando las comillas de la path int x; int y = 0; for (x = 1; x < 200; x++) { if (pathaux[x] == '\"') { x = 200; } else { path[y] = pathaux[x]; y++; } } } else { strcpy(path, pathaux); } FILE *disco; disco = fopen(path, "rb"); if (disco == NULL) { //Se comprueba que el archivo exista printf("Este disco no existe \n"); errors = true; //hay un error } else { existepath = true; //la path si existe } } else if (strcasecmp(comando[cont].comando, "+type") == 0) { strcpy(type, comando[cont + 1].comando); if (strcasecmp(type, "P") != 0 && strcasecmp(type, "E") != 0 && strcasecmp(type, "L") != 0) { printf("Parametro incorrecto type debe ser [P|E|L] \n"); errors = true; //existe error } else { existetype = true; } } else if (strcasecmp(comando[cont].comando, "+fit") == 0) { strcpy(fit, comando[cont + 1].comando); if (strcasecmp(fit, "BF") != 0 && strcasecmp(fit, "FF") != 0 && strcasecmp(fit, "WF") != 0) { printf("Parametro incorrecto type debe ser [BF|FF|WF] \n"); errors = true; //existe error } else { existefit = true; } } else if (strcasecmp(comando[cont].comando, "+delete") == 0) { strcpy(deletev, comando[cont + 1].comando); if (strcasecmp(deletev, "fast") != 0 && strcasecmp(deletev, "full") != 0) { printf("Parametro incorrecto delete debe ser [FAST|FULL] \n"); errors = true; } else { existedelete = true; } } else if (strcasecmp(comando[cont].comando, "-name") == 0) { int l=0,k; strcpy(auxname, comando[cont + 1].comando); if(auxname[0] == '\"'){ int a; for (a = cont + 2; a < 25; a++) { if (strcasecmp(comando[a].comando, "-size") != 0 && strcasecmp(comando[a].comando, "+unit") != 0 && strcasecmp(comando[a].comando, "-path") != 0 && strcasecmp(comando[a].comando, "+type") != 0 && strcasecmp(comando[a].comando, "+fit") != 0 && strcasecmp(comando[a].comando, "+delete") != 0 && strcasecmp(comando[a].comando, "-name") != 0 && strcasecmp(comando[a].comando, "+add") != 0 && strcasecmp(comando[a].comando, "vacio") != 0) { strcat(auxname, " "); strcat(auxname, comando[a].comando); } else { a = 25; } } } if (auxname[0] == '\"') { //Quitando las comillas de la path int x; int y = 0; for (x = 1; x < 200; x++) { if (auxname[x] == '\"') { x = 200; } else { name[y] = auxname[x]; y++; } } } else { strcpy(name, auxname); } existename = true; } else if (strcasecmp(comando[cont].comando, "+add") == 0) { add = atoi(comando[cont + 1].comando); if (add > 0) { printf("Se agregara espacio \n"); } else { printf("Se quitara espacio \n"); } existeadd = true; } cont++; } if (errors == true){ printf("Imposible de ejecutar, existen errores en el script \n\n"); }else{ if (existepath == false || existename == false) { //SI la path o el name no vienen printf("Faltan parametros obligatorios [Path o Name] \n\n"); errors = true; } else { /***************************************/ /*MODULO DE CREACION DE UNA PARTICION*/ /***************************************/ if (existesize == true) { //Si va a crear una particion if (errors == true) { //printf("Existen errores \n"); } else { printf("Modulo de creacion de particiones \n"); CrearParticion(path, size, unit, type, fit, name); //Creara la particion en este disco } } /***************************************/ /*MODULO DE ELIMINACION DE UNA PARTICION*/ /***************************************/ else if (existedelete == true) { if (errors == true) { //printf("Existen errores \n"); } else { printf("Modulo de eliminacion de particiones \n"); FILE *disco; struct_mbr mbr; disco = fopen(path, "rb"); if (disco != NULL) { fread(&mbr, sizeof (mbr), 1, disco); printf("Fue creado: %s \n", mbr.mbr_fecha_creacion); EliminarParticion(path, deletev, name); } else { printf("No existe el disco \n"); } } } /***************************************/ /*MODULO DE AMPLIACION DE UNA PARTICION*/ /***************************************/ else if (existeadd == true) { //Si va a agregar espacio a una particion if (errors == true) { //printf("Existen errores \n"); } else { printf("Modulo de modificacion de particiones \n"); FILE *disco; struct_mbr mbr; disco = fopen(path, "rb"); if (disco != NULL) { fread(&mbr, sizeof (mbr), 1, disco); printf("Fue creado: %s \n", mbr.mbr_fecha_creacion); ModificarParticion(path, unit, add, name); } else { printf("No existe el disco \n"); } } } } } } void CrearParticion(char path[], int size, char unit[], char type[], char fit[], char Name[]) { char name[100]; limpiarvar(name, 100); strcpy(name, Name); char auxfit, auxtype; //variables para almacenar el fit y el type n forma de char int tamanoreal; //Variable para tamaño real de la particion int cantPrimarias; //numero de particiones primarias int cantExtendidas; //numero de particiones extendidas bool error = false; //booleano para verificar si existe algun error en el script /**************************/ /*CONVERSION DE VARIABLES*/ /*************************/ if (strcasecmp(fit, "BF") == 0 || strcasecmp(fit, "B") == 0) { auxfit = 'B'; //Mejor ajuste } else if (strcasecmp(fit, "FF") == 0 || strcasecmp(fit, "F") == 0) { auxfit = 'F'; //Primer ajuste } else if (strcasecmp(fit, "WF") == 0 || strcasecmp(fit, "W") == 0) { auxfit = 'W'; //Peor ajuste } if (strcasecmp(unit, "b") == 0) { tamanoreal = size; } else if (strcasecmp(unit, "k") == 0) { tamanoreal = size * 1024; } else if (strcasecmp(unit, "m") == 0) { tamanoreal = size * 1024 * 1024; } /*********************************************/ /*COMIENZAN VALIDACIONES PARA CREAR PARTICION*/ /*********************************************/ FILE *disco; FILE *nuevodisco; //el que se va a usar para sobreescribir a este [disco] struct_mbr mbr; disco = fopen(path, "rb"); if (disco != NULL) { //SI existe el disco fread(&mbr, sizeof (mbr), 1, disco); //recuperando el mbr de este disco /*printf("Fue creado: %s \n", mbr.mbr_fecha_creacion); printf("El tamaño del disco es: %i \n", mbr.mbr_tamano); printf("El id del disco es: %i \n", mbr.mbr_disk_signature);*/ cantPrimarias = CantidadParticionesPrimarias(mbr); cantExtendidas = CantidadParticionesExtendidas(mbr); int i; //variable para recorrer el vector de particiones en el mbr /*CREANDO LA PARTICION QUE SE VA A INTENTAR INSERTAR EN EL DISCO*/ struct_particion particion; //Particion que va a ser creada dentro del mbr particion.part_fit = auxfit; //Asignandole el fit strcpy(particion.part_name, name); //Asignandole el nombre particion.part_size = tamanoreal; //Asignandole el tamaño particion.part_status = '1'; //Estado de ocupado int totalparticiones = cantExtendidas + cantPrimarias; struct_particion vecparticiones[totalparticiones]; //vector para almacenar las particiones que existen actualmente en el disco int j, p, cont = 0; int espaciolibre; //variable que se utiliza para ir verificando si la partcion cabe en ese espacio if (totalparticiones > 0) { for (j = 0; j < 4; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mbr.mbr_particiones[j].part_start > 0 && mbr.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mbr.mbr_particiones[j]; cont++; } } } /**************************************/ /*ORDENANDO EL VECTOR POR BURBUJA******/ /*************************************/ if (totalparticiones > 0) { for (j = 0; j < totalparticiones; j++) { for (p = 0; p < totalparticiones - 1; p++) { if (vecparticiones[p].part_start > vecparticiones[p + 1].part_start) { struct_particion aux = vecparticiones[p]; vecparticiones[p] = vecparticiones[p + 1]; vecparticiones[p + 1] = aux; } } } } /**************************************************************************/ /***************PARA CREAR UNA PRIMARIA***********************************/ /**************************************************************************/ if (strcasecmp(type, "p") == 0) { bool errores = false; //booleano para verificar que no existe un error antes de meterla en el mbr int tamanodisponible; auxtype = 'p'; //Particion primaria particion.part_type = auxtype; if (cantPrimarias < 3) { //Hay menos de 3 particiones primarias if (cantPrimarias == 0 && cantExtendidas == 0) { //El disco esta vacio tamanodisponible = mbr.mbr_tamano - (sizeof (mbr) + 1); bool EntraParticion = false; for (i = 0; i < 3 && EntraParticion == false; i++) { if (mbr.mbr_particiones[i].part_status == '0') { particion.part_start = sizeof (mbr) + 1; particion.part_size = tamanoreal; if (tamanodisponible > tamanoreal) { //printf("Si se insertara la particion \n"); EntraParticion = true; mbr.mbr_particiones[i] = particion; /*SOBREESCRIBIENDO EL DISCO*/ int cont; nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, nuevodisco); char relleno = '\0'; //variable con la que se va a rellenar el disco duro /*for(cont = 0; cont < mbr.mbr_tamano - 1;cont++ ){ fwrite(&relleno, 1, 1 , nuevodisco); }*/ fclose(nuevodisco); printf("Particion creada con exito \n"); } else { printf("No hay espacio suficiente \n"); errores = true; break; } } } } else { //Existe al menos 1 particion /********************************************************************************/ /*COMPARANDO PARA VER SI EXISTE UN ESPACIO DEL TAMAÑO DE LA PARTICION A INSERTAR*/ /********************************************************************************/ bool SiEntro = false; //Variable para saber que si encontro un espacio con ese tamaño for (j = 0; j < totalparticiones + 1 && SiEntro == false; j++) { if (j == 0) {//Comparando el espacio libre entre la mas cercana al mbr y el mbr espaciolibre = (vecparticiones[j].part_start) - (sizeof (mbr) + 1); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion \n"); particion.part_start = sizeof (mbr) + 1; SiEntro = true; } } else if (j == totalparticiones) { //Si es la ultima particion del vector espaciolibre = mbr.mbr_tamano - (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion \n"); particion.part_start = (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1); SiEntro = true; } } else { espaciolibre = vecparticiones[j].part_start - (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion \n"); particion.part_start = vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1; SiEntro = true; } } } /********************************************/ /**COMPARANDO NOMBRES PARA EVITAR REPETIDOS*/ /*******************************************/ for (j = 0; j < totalparticiones && errores == false; j++) { if (strcasecmp(vecparticiones[j].part_name, particion.part_name) == 0) { printf("Ya existe una particion con ese nombre \n"); errores = true; } if (vecparticiones[j].part_type == 'e' || vecparticiones[j].part_type == 'E' && errores == false) { struct_ebr auxnombres; int fin = vecparticiones[j].part_size + vecparticiones[j].part_start; bool ultima = false; //booleano para saber si llego a la ultima logica for (i = vecparticiones[j].part_start; i < fin + 1 && errores == false && ultima == false; i++) { fseek(disco, i, SEEK_SET); fread(&auxnombres, sizeof (struct_ebr), 1, disco); if (strcasecmp(auxnombres.part_name, name) == 0) { printf("Ya existe una particion con ese nombre \n"); errores = true; } if (auxnombres.part_next == -1) { ultima = true; } i = auxnombres.part_start + auxnombres.part_size; } } } /*************************************************************/ /*INGRESANDO LA PARTICION EN EL VECTOR DE PARTICIONES DEL MBR*/ /*************************************************************/ if (SiEntro == true && errores == false) { //logro encontrar un espacio para esa particion y no hay errores bool ingresada = false; for (j = 0; j < 4 && ingresada == false; j++) { if (mbr.mbr_particiones[j].part_status == '0') { mbr.mbr_particiones[j] = particion; ingresada = true; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ if (ingresada == true) { //si logro ingresarla nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, nuevodisco); fclose(nuevodisco); printf("Se creo la particion exitosamente \n"); } } } } else { //Si ya existen 3 primarias printf("Este disco alcanzó el limite de particiones primarias [3] \n"); error = true; } }/**************************************************************************/ /***************PARA CREAR UNA EXTENDIDA***********************************/ /**************************************************************************/ else if (strcasecmp(type, "e") == 0) { bool errores = false; //booleano para verificar que no exista ningun error antes de insertarla en el mbr int tamanodisponible; auxtype = 'e'; //Particion extendida particion.part_type = auxtype; if (cantExtendidas == 0) { //Si no hay ninguna extendida if (cantPrimarias == 0 && cantExtendidas == 0) { //El disco esta vacio tamanodisponible = mbr.mbr_tamano - (sizeof (mbr) + 1); bool EntraParticion = false; for (i = 0; i < 4 && EntraParticion == false; i++) { if (mbr.mbr_particiones[i].part_status == '0') { particion.part_start = sizeof (mbr) + 1; particion.part_size = tamanoreal; if (tamanodisponible > tamanoreal) { //printf("Si se insertara la particion \n"); EntraParticion = true; mbr.mbr_particiones[i] = particion; struct_ebr ebrprimero; //ebr que se pondra en la particion extendida ebrprimero.part_fit = 'N'; strcpy(ebrprimero.part_name, "N"); ebrprimero.part_next = -1; //apuntador al siguiente ebr ebrprimero.part_size = sizeof (struct_ebr); ebrprimero.part_start = particion.part_start; ebrprimero.part_status = '0'; /*SOBREESCRIBIENDO EL DISCO*/ int cont; nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, nuevodisco); fseek(nuevodisco, (particion.part_start), SEEK_SET); fwrite(&ebrprimero, sizeof (struct_ebr), 1, nuevodisco); rewind(nuevodisco); char relleno = '\0'; //variable con la que se va a rellenar el disco duro /*for(cont = 0; cont < mbr.mbr_tamano - 1;cont++ ){ fwrite(&relleno, 1, 1 , nuevodisco); }*/ fclose(nuevodisco); } else { printf("No hay espacio suficiente \n"); errores = true; } } } } else { //Existe al menos 1 particion /********************************************************************************/ /*COMPARANDO PARA VER SI EXISTE UN ESPACIO DEL TAMAÑO DE LA PARTICION A INSERTAR*/ /********************************************************************************/ bool SiEntro = false; //Variable para saber que si encontro un espacio con ese tamaño for (j = 0; j < totalparticiones + 1 && SiEntro == false; j++) { if (j == 0) {//Comparando el espacio libre entre la mas cercana al mbr y el mbr espaciolibre = (vecparticiones[j].part_start) - (sizeof (mbr) + 1); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion"); particion.part_start = sizeof (mbr) + 1; SiEntro = true; } } else if (j == totalparticiones) { //Si es la ultima particion del vector espaciolibre = mbr.mbr_tamano - (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion"); particion.part_start = (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1); SiEntro = true; } } else { espaciolibre = vecparticiones[j].part_start - (vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1); if (espaciolibre >= tamanoreal) { //printf("Espacio suficiente para esta particion"); particion.part_start = vecparticiones[j - 1].part_start + vecparticiones[j - 1].part_size + 1; SiEntro = true; } } } /********************************************/ /**COMPARANDO NOMBRES PARA EVITAR REPETIDOS*/ /*******************************************/ for (j = 0; j < totalparticiones; j++) { if (strcasecmp(vecparticiones[j].part_name, particion.part_name) == 0) { printf("Ya existe una particion con ese nombre \n"); errores = true; } } /*************************************************************/ /*INGRESANDO LA PARTICION EN EL VECTOR DE PARTICIONES DEL MBR*/ /*************************************************************/ if (SiEntro == true && errores == false) { //logro encontrar un espacio para esa particion y no hay errores bool ingresada = false; for (j = 0; j < 4 && ingresada == false; j++) { if (mbr.mbr_particiones[j].part_status == '0') { mbr.mbr_particiones[j] = particion; ingresada = true; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ if (ingresada == true) { //si logro ingresarla struct_ebr ebrprimero; //ebr que se pondra en la particion extendida ebrprimero.part_fit = 'N'; strcpy(ebrprimero.part_name, "N"); ebrprimero.part_next = -1; ebrprimero.part_size = sizeof (struct_ebr); ebrprimero.part_start = particion.part_start; ebrprimero.part_status = '0'; nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, nuevodisco); fseek(nuevodisco, (particion.part_start), SEEK_SET); fwrite(&ebrprimero, sizeof (struct_ebr), 1, nuevodisco); rewind(nuevodisco); fclose(nuevodisco); printf("Se creo la particion exitosamente \n"); } } } } else { printf("Este disco alcanzó el limite de particiones extendidas [1] \n"); error = true; } }/**************************************************************************/ /************************PARA CREAR UNA LOGICA*****************************/ /**************************************************************************/ else if (strcasecmp(type, "l") == 0) { bool errornombre = false; bool errores = false; //booleano para verificar que no exista ningun error antes de insertarla int tamanodisponible; auxtype = 'l'; //Particion logica int j; particion.part_type = auxtype; struct_particion auxExtendida; struct_ebr ebr; //ebr que se usara para insertar int contLogicas = 0; //contador para saber cuantos ebr hay int i; if (cantExtendidas > 0) { //validando que ya exista una extendida donde almacemarla for (i = 0; i < 4; i++) { if (mbr.mbr_particiones[i].part_type == 'e') { auxExtendida = mbr.mbr_particiones[i]; //almacenando la extendida en una auxiliar para trabajar i = 4; } } if (tamanoreal <= auxExtendida.part_size) { //validando que el tamaño de la logica no sobrepase el tamaño de la extendida /********************************************/ /**COMPARANDO NOMBRES PARA EVITAR REPETIDOS*/ /*******************************************/ for (j = 0; j < totalparticiones && errornombre == false; j++) { if (strcasecmp(vecparticiones[j].part_name, name) == 0) { printf("Ya existe una particion con ese nombre \n"); errornombre = true; } if (vecparticiones[j].part_type == 'e' || vecparticiones[j].part_type == 'E' && errornombre == false) { struct_ebr auxnombres; int fin = vecparticiones[j].part_size + vecparticiones[j].part_start; bool ultima = false; for (i = vecparticiones[j].part_start; i < fin + 1 && errornombre == false && ultima == false; i++) { nuevodisco = fopen(path, "rb"); fseek(nuevodisco, i, SEEK_SET); fread(&auxnombres, sizeof (struct_ebr), 1, nuevodisco); if (strcasecmp(auxnombres.part_name, name) == 0) { //printf("Ya existe una particion con ese nombre \n"); errornombre = true; } if (auxnombres.part_next == -1) { ultima = true; } i = auxnombres.part_next - 1; //Se mueve i hasta donde termina la particion para leer otro bloque fclose(nuevodisco); } } } if (errornombre == false) { //Si no encontro ninguna particion con el mismo nombre bool errorespacio = false; //booleano para saber si existe espacio disponible for (j = 0; j < totalparticiones && errorespacio == false; j++) { if (vecparticiones[j].part_type == 'e' || vecparticiones[j].part_type == 'E' && errorespacio == false) { struct_ebr auxnombres; int fin = vecparticiones[j].part_size + vecparticiones[j].part_start; bool ultima = false; //para saber si entro en la ultima particion for (i = vecparticiones[j].part_start; i < fin + 1 && errorespacio == false && ultima == false; i++) { fseek(disco, i, SEEK_SET); fread(&auxnombres, sizeof (struct_ebr), 1, disco); if (auxnombres.part_next == -1) { //encontro la ultima ultima = true; } i = auxnombres.part_next - 1; contLogicas++; } } } int contposlogicas = 0; struct_ebr vecLogicas[contLogicas]; //vector donde se van a almacenar las logicas for (j = 0; j < totalparticiones; j++) { struct_ebr auxlogicas; if (vecparticiones[j].part_type == 'e' || vecparticiones[j].part_type == 'E') { int fin = vecparticiones[j].part_size + vecparticiones[j].part_start; bool ultima = false; for (i = vecparticiones[j].part_start; i < fin + 1 && ultima == false; i++) { fseek(disco, i, SEEK_SET); fread(&auxlogicas, sizeof (struct_ebr), 1, disco); vecLogicas[contposlogicas] = auxlogicas; if (auxlogicas.part_next == -1) { ultima = true; } i = auxlogicas.part_next - 1; contposlogicas++; } } } bool sientro = false; /*************************************************************/ /*Recorriendo el vector de logicas para realizar la insercion*/ /*************************************************************/ j = 0; if (contLogicas > 1) { for (j = 0; j < contLogicas && sientro == false; j++) { if (j == (contLogicas - 1)) {//Comparando el espacio libre entre la ultima y el final de la extendida espaciolibre = (auxExtendida.part_start + auxExtendida.part_size) - (vecLogicas[j].part_start + vecLogicas[j].part_size); if (espaciolibre > tamanoreal) { vecLogicas[j].part_next = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_fit = auxfit; strcpy(ebr.part_name, name); ebr.part_next = -1; ebr.part_size = tamanoreal; ebr.part_start = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_status = '1'; sientro = true; } } else { espaciolibre = (vecLogicas[j + 1].part_start) - (vecLogicas[j].part_start + vecLogicas[j].part_size + 1); if (espaciolibre > tamanoreal) { vecLogicas[j].part_next = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_fit = auxfit; strcpy(ebr.part_name, name); ebr.part_next = vecLogicas[j + 1].part_next; ebr.part_size = tamanoreal; ebr.part_start = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_status = '1'; sientro = true; } } } } else { espaciolibre = (auxExtendida.part_start + auxExtendida.part_size) - (vecLogicas[j].part_start + vecLogicas[j].part_size); if (espaciolibre > tamanoreal) { vecLogicas[j].part_next = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_fit = auxfit; strcpy(ebr.part_name, name); ebr.part_next = -1; ebr.part_size = tamanoreal; ebr.part_start = vecLogicas[j].part_start + vecLogicas[j].part_size + 1; ebr.part_status = '1'; sientro = true; } } /********************************************************/ /*Sobreescribiendo el disco despues de las validaciones*/ /*******************************************************/ if (sientro == true) { //Si encontro un espacio para la nueva particion nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, ebr.part_start, SEEK_SET); fwrite(&ebr, sizeof (struct_ebr), 1, nuevodisco); int x; for (x = 0; x < contLogicas; x++) { fseek(nuevodisco, vecLogicas[x].part_start, SEEK_SET); fwrite(&vecLogicas[x], sizeof (struct_ebr), 1, nuevodisco); } rewind(nuevodisco); fclose(nuevodisco); printf("Se creo la particion correctamente \n"); } else { printf("No se encontro un espacio disponible para crear esta particion \n"); } } else { printf("Ya existe una particion con ese nombre \n"); } } else { printf("La particion que intenta crear sobrepasa el tamaño de la extendida \n"); } } else { printf("No se puede crear una particion logica debido a que no existe una particion extendida \n"); } } } else { //Si el disco es nulo, no existe ese disco printf("No existe el disco \n"); } } void EliminarParticion(char path[], char deletev[], char name[]) { //METODO DONDE SE ELIMINAN LAS PARTICIONES FILE *disco; FILE *nuevodisco; //disco para sobreescribir struct_mbr mbr; int i; //para recorrer las particiones del mbr int cont; bool encontrada = false; //booleano para saber si encontro la particion disco = fopen(path, "rb"); if (disco != NULL){ fread(&mbr, sizeof (mbr), 1, disco); //recuperando el mbr del disco for (i = 0; i < 4 && encontrada == false; i++) { //recorriendo las particiones del mbr if (strcasecmp(mbr.mbr_particiones[i].part_name, name) == 0) { if (strcasecmp(deletev, "FULL") == 0) {//Si el formateo es full /**********************************/ /********FORMATEO FULL*************/ /**********************************/ char relleno = '\0'; int inicio = mbr.mbr_particiones[i].part_start; int fin = mbr.mbr_particiones[i].part_start + mbr.mbr_particiones[i].part_size; mbr.mbr_particiones[i].part_fit = 'W'; strcpy(mbr.mbr_particiones[i].part_name, "N"); mbr.mbr_particiones[i].part_size = 0; mbr.mbr_particiones[i].part_start = 0; mbr.mbr_particiones[i].part_status = '0'; mbr.mbr_particiones[i].part_type = 'N'; nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (mbr), 1, nuevodisco); for (cont = inicio; cont < fin + 1; cont++) { fseek(nuevodisco, cont, SEEK_SET); fwrite(&relleno, 1, 1, nuevodisco); } rewind(nuevodisco); fclose(nuevodisco); printf("Se formateo la particion %s de forma FULL exitosamente \n", name); }else{ //Formateo fast /**********************************/ /********FORMATEO FAST*************/ /**********************************/ char relleno = '\0'; int inicio = mbr.mbr_particiones[i].part_start; int fin = mbr.mbr_particiones[i].part_size + mbr.mbr_particiones[i].part_start; mbr.mbr_particiones[i].part_fit = 'W'; strcpy(mbr.mbr_particiones[i].part_name, "N"); mbr.mbr_particiones[i].part_size = 0; mbr.mbr_particiones[i].part_start = 0; mbr.mbr_particiones[i].part_status = '0'; mbr.mbr_particiones[i].part_type = 'N'; nuevodisco = fopen(path, "rb+"); fseek(nuevodisco, 0L, SEEK_SET); fwrite(&mbr, sizeof (mbr), 1, nuevodisco); /*fseek(nuevodisco, inicio, SEEK_SET); for (cont = 0; cont < fin; cont++) { fwrite(&relleno, 1, 1, nuevodisco); }*/ rewind(nuevodisco); fclose(nuevodisco); printf("Se formateo la particion %s de forma FAST exitosamente \n", name); } encontrada = true; } if (mbr.mbr_particiones[i].part_type == 'e' || mbr.mbr_particiones[i].part_type == 'E' && encontrada == false) { //ENCONTRO UNA EXTENDIDA Y NO HA ENCONTRADO LA PARTICION AUN char relleno = '\0'; int cantLogicas = 0; struct_ebr auxLogica; bool ultima = false; int j; int fin = mbr.mbr_particiones[i].part_start + mbr.mbr_particiones[i].part_size; nuevodisco = fopen(path, "rb"); /**RECORRIDO PARA SABER CUANTAS LOGICAS HAY*/ for (j = mbr.mbr_particiones[i].part_start; j < fin + 1 && ultima == false; j++) { fseek(nuevodisco, j, SEEK_SET); fread(&auxLogica, sizeof (struct_ebr), 1, nuevodisco); if (auxLogica.part_next == -1) { ultima = true; } cantLogicas++; j = auxLogica.part_next - 1; } /****************************************/ /*****GUARDANDO LAS LOGICAS EN EL VECTOR*/ /****************************************/ ultima = false; int posicionLogicas = 0; struct_ebr vecLogicas[cantLogicas]; for (j = mbr.mbr_particiones[i].part_start; j < fin + 1 && ultima == false; j++) { fseek(nuevodisco, j, SEEK_SET); fread(&auxLogica, sizeof (struct_ebr), 1, nuevodisco); vecLogicas[posicionLogicas] = auxLogica; if (auxLogica.part_next == -1) { ultima = true; } posicionLogicas++; j = auxLogica.part_next - 1; } /**validaciones de tipo de formateo*/ nuevodisco = fopen(path, "rb+"); if (strcasecmp(deletev, "FULL") == 0) { for (i = 0; i < cantLogicas; i++) { if (strcasecmp(name, vecLogicas[i].part_name) == 0) { encontrada = true; if (cantLogicas > 1) { int j; vecLogicas[i - 1].part_next = vecLogicas[i].part_next; fseek(nuevodisco, vecLogicas[i - 1].part_start, SEEK_SET); fwrite(&vecLogicas[i], sizeof (struct_ebr), 1, nuevodisco); for (cont = vecLogicas[i].part_start; cont < (vecLogicas[i].part_start + vecLogicas[i].part_size + 1); cont++) { fseek(nuevodisco, cont, SEEK_SET); fwrite(&relleno, 1, 1, nuevodisco); } rewind(nuevodisco); fclose(nuevodisco); printf("Se formateo la particion %s de forma FULL exitosamente \n", name); } } } } else { for (i = 0; i < cantLogicas; i++) { if (strcasecmp(name, vecLogicas[i].part_name) == 0) { encontrada = true; if (cantLogicas > 1) { vecLogicas[i - 1].part_next = vecLogicas[i].part_next; vecLogicas[i].part_status = '0'; fseek(nuevodisco, vecLogicas[i - 1].part_start, SEEK_SET); fwrite(&vecLogicas[i - 1], sizeof (struct_ebr), 1, nuevodisco); fseek(nuevodisco, vecLogicas[i].part_start, SEEK_SET); fwrite(&vecLogicas[i], sizeof (struct_ebr), 1, nuevodisco); rewind(nuevodisco); fclose(nuevodisco); printf("Se formateo la particion %s de forma FAST exitosamente \n", name); } } } } } } if (encontrada == false) { printf("No existe esa particion \n"); } fclose(disco); }else { //si disco es nulo //NO EXISTE DISCO PERO ESTE ELSE ESTA DE MAS } } void ModificarParticion(char path[], char unit[], int add, char name[]){ //METODO DONDE SE MODIFICAN LAS PARTICIONES int addaux = add; int tamanoreal; //Variable para tamaño real que se agregara o quitara a la particion int cantPrimarias; //numero de particiones primarias int cantExtendidas; //numero de particiones extendidas int totalParticiones; //numero total de particiones /**************************/ /*CONVERSION DE VARIABLES*/ /*************************/ if (strcasecmp(unit, "b") == 0) { tamanoreal = addaux; } else if (strcasecmp(unit, "k") == 0) { tamanoreal = addaux * 1024; } else if (strcasecmp(unit, "m") == 0) { tamanoreal = addaux * 1024 * 1024; } FILE *disco; disco = fopen(path, "rb+"); struct_mbr mbr; if (disco != NULL) { fread(&mbr, sizeof (struct_mbr), 1, disco); cantPrimarias = CantidadParticionesPrimarias(mbr); cantExtendidas = CantidadParticionesExtendidas(mbr); totalParticiones = cantExtendidas + cantPrimarias; struct_particion vecparticiones[totalParticiones]; int j, p, cont = 0; if (totalParticiones < 4) { for (j = 0; j < 3; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mbr.mbr_particiones[j].part_start > 0 && mbr.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mbr.mbr_particiones[j]; cont++; } } } else if (totalParticiones == 4) { for (j = 0; j < 4; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mbr.mbr_particiones[j].part_start > 0 && mbr.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mbr.mbr_particiones[j]; cont++; } } } /**************************************/ /*ORDENANDO EL VECTOR POR BURBUJA******/ /*************************************/ if (totalParticiones > 1) { for (j = 0; j < totalParticiones; j++) { for (p = 0; p < totalParticiones - 1; p++) { if (vecparticiones[p].part_start > vecparticiones[p + 1].part_start) { struct_particion aux = vecparticiones[p]; vecparticiones[p] = vecparticiones[p + 1]; vecparticiones[p + 1] = aux; } } } } bool encontro = false; int h; int espaciolibre; for (h = 0; h < totalParticiones; h++) { if (strcasecmp(vecparticiones[h].part_name, name) == 0) { encontro = true; if (totalParticiones == 1) { //Si solo hay una particion en el disco if (tamanoreal > 0) { //Se quiere agregar espacio espaciolibre = mbr.mbr_tamano - (vecparticiones[h].part_start + vecparticiones[h].part_size + 1); if (tamanoreal < espaciolibre) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito agrego exitosamente \n"); } else { printf("No se puede agregar espacio debido a que sobrepasa el espacio libre del disco \n"); } } else { //se quiere quitar espacio if (vecparticiones[h].part_size + tamanoreal > 0 && vecparticiones[h].part_size + tamanoreal >= 2097152) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito espacio exitosamente \n"); } else { printf("No se puede quitar espacio debido a que no cumple con el minimo de una particion \n"); } } } else { //SI HAY MAS DE UNA PARTICION if (h == totalParticiones - 1) { //la ultima particion del disco if (tamanoreal > 0) { //Se quiere agregar espacio espaciolibre = mbr.mbr_tamano - (vecparticiones[h].part_start + vecparticiones[h].part_size + 1); if (tamanoreal < espaciolibre) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito agrego exitosamente \n"); } else { printf("No se puede agregar espacio debido a que sobrepasa el espacio libre del disco \n"); } } else { //se quiere quitar espacio if (vecparticiones[h].part_size + tamanoreal > 0 && vecparticiones[h].part_size + tamanoreal >= 2097152) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito espacio exitosamente \n"); } else { printf("No se puede quitar espacio debido a que no cumple con el minimo de una particion \n"); } } } else { if (tamanoreal > 0) { //Se quiere agregar espacio espaciolibre = vecparticiones[h + 1].part_start - (vecparticiones[h].part_start + vecparticiones[h].part_size + 1); if (tamanoreal < espaciolibre) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito agrego exitosamente \n"); } else { printf("No se puede agregar espacio debido a que sobrepasa el espacio libre del disco \n"); } }else { //se quiere quitar espacio if (vecparticiones[h].part_size + tamanoreal > 0 && vecparticiones[h].part_size + tamanoreal >= 2097152) { vecparticiones[h].part_size = vecparticiones[h].part_size + tamanoreal; for (j = 0; j < 4; j++) { if (strcasecmp(vecparticiones[h].part_name, mbr.mbr_particiones[j].part_name) == 0) { mbr.mbr_particiones[j] = vecparticiones[h]; } } /***************************************/ /******ESCRIBIENDO DE NUEVO EL MBR******/ /***************************************/ fseek(disco, 0L, SEEK_SET); fwrite(&mbr, sizeof (struct_mbr), 1, disco); //fclose(disco); printf("Se quito espacio exitosamente \n"); } else { printf("No se puede quitar espacio debido a que no cumple con el minimo de una particion \n"); } } } } } else if (vecparticiones[h].part_type == 'e' || vecparticiones[h].part_type == 'E' && encontro == false) { //no lo ha encontrado y esta buscando en una particion extendida int cantLogicas = 0; int z; struct_ebr aux; for (z = vecparticiones[h].part_start; z < (vecparticiones[h].part_size + vecparticiones[h].part_start + 1); z++) { fseek(disco, z, SEEK_SET); fread(&aux, sizeof (struct_ebr), 1, disco); if (aux.part_next != -1) { z = (vecparticiones[h].part_size + vecparticiones[h].part_start + 1); } else { z = aux.part_next - 1; } if (strcasecmp(aux.part_name, name) == 0) { encontro = true; } cantLogicas++; } /*ALMACENANDO LAS LOGICAS EN UN VECTOR*/ struct_ebr vecLogicas[cantLogicas]; int posLogicas = 0; for (z = vecparticiones[h].part_start; z < (vecparticiones[h].part_size + vecparticiones[h].part_start + 1); z++) { fseek(disco, z, SEEK_SET); fread(&aux, sizeof (struct_ebr), 1, disco); if (aux.part_next != -1) { z = (vecparticiones[h].part_size + vecparticiones[h].part_start + 1); } else { z = aux.part_next - 1; } vecLogicas[posLogicas] = aux; } /*COMIENZAN VALIDACIONES PARA EL ADD SOBRE LAS LOGICAS*/ if (encontro == true) { for (z = 1; z < cantLogicas; z++) { if (strcasecmp(vecLogicas[z].part_name, name) == 0) { if (z == 1) { //es la primera particion if (cantLogicas > 2) { //si hay mas de una logica if (tamanoreal > 0) { //agregar espacio espaciolibre = vecLogicas[z + 1].part_start - (vecLogicas[z].part_start + vecLogicas[z].part_size + 1); if (espaciolibre > tamanoreal) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("No hay suficiente espacio para agrandar esta particion \n"); } } else { //quitar espacio if (vecLogicas[z].part_size + tamanoreal > 0 && vecLogicas[z].part_size + tamanoreal >= 2097152 ) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("El espacio supera el tamaño de la particion \n"); } } } else { if (tamanoreal > 0) { //agregar espacio espaciolibre = (vecparticiones[h].part_start + vecparticiones[h].part_size) - (vecLogicas[z].part_start + vecLogicas[z].part_size + 1); if (espaciolibre > tamanoreal) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("No hay suficiente espacio para agrandar esta particion \n"); } } else { //quitar espacio if (vecLogicas[z].part_size + tamanoreal > 0 && vecLogicas[z].part_size + tamanoreal >= 2097152) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("El espacio supera el tamaño de la particion \n"); } } } }else if (z == cantLogicas - 1) { //es la ultima particion if (tamanoreal > 0) { //agregar espacio espaciolibre = (vecparticiones[h].part_start + vecparticiones[h].part_size) - (vecLogicas[z].part_start + vecLogicas[z].part_size + 1); if (espaciolibre > tamanoreal) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("No hay suficiente espacio para agrandar esta particion \n"); } } else { //quitar espacio if (vecLogicas[z].part_size + tamanoreal > 0 && vecLogicas[z].part_size + tamanoreal >= 2097152) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("El espacio supera el tamaño de la particion \n"); } } } else { if (tamanoreal > 0) { //agregar espacio espaciolibre = (vecLogicas[z + 1].part_start) - (vecLogicas[z].part_start + vecLogicas[z].part_size + 1); if (espaciolibre > tamanoreal) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("No hay suficiente espacio para agrandar esta particion \n"); } } else { //quitar espacio if (vecLogicas[z].part_size + tamanoreal > 0 && vecLogicas[z].part_size + tamanoreal >= 2097152) { vecLogicas[z].part_size = vecLogicas[z].part_size + tamanoreal; fseek(disco, vecLogicas[z].part_start, SEEK_SET); fwrite(&vecLogicas[z], sizeof (struct_ebr), 1, disco); } else { printf("El espacio supera el tamaño de la particion \n"); } } } } } } } } if (encontro == false) { printf("Imposible modificar %s porque no se encuentra en el disco \n", name); } fclose(disco); } else { printf("No existe este disco \n"); } } void Mount(Comando comando[]) { char pathaux[200]; limpiarvar(pathaux, 200); char path[200]; limpiarvar(path, 200); char name[20]; limpiarvar(name, 20); char auxname[20]; limpiarvar(auxname,20); //bool banderas para saber si existe el parametro bool existepath = false; bool existename = false; bool errores = false; int cont = 0; while (strcasecmp(comando[cont].comando, "vacio") != 0) { if (strcasecmp(comando[cont].comando, "-path") == 0) { strcpy(pathaux, comando[cont + 1].comando); if (pathaux[0] == '\"') { //Path con comillas cont = cont + 2; int cont2 = cont; while (strcasecmp(comando[cont2].comando, "vacio") != 0 && strcasecmp(comando[cont].comando, "-name") != 0) { strcat(pathaux, " "); strcat(pathaux, comando[cont].comando); cont2++; cont++; } int x; int y = 0; for (x = 1; x < 200; x++) { if (pathaux[x] != '\"') { path[y] = pathaux[x]; y++; } else { x = 200; } } } else { strcpy(path, pathaux); } cont--; existepath = true; } else if (strcasecmp(comando[cont].comando, "-name") == 0) { strcpy(auxname, comando[cont + 1].comando); if(auxname[0] == '\"'){ int a; for (a = cont + 2; a < 25; a++) { if (strcasecmp(comando[a].comando, "-path") != 0 && strcasecmp(comando[a].comando, "-name") != 0 && strcasecmp(comando[a].comando, "vacio") != 0) { strcat(auxname, " "); strcat(auxname, comando[a].comando); } else { a = 25; } } } if (auxname[0] == '\"') { //Quitando las comillas de la path int x; int y = 0; for (x = 1; x < 200; x++) { if (auxname[x] == '\"') { x = 200; } else { name[y] = auxname[x]; y++; } } } else { strcpy(name, auxname); } existename = true; } cont++; } if (existename == false || existepath == false) { //Si no viene path o name printf("Lista de Montados Actualmente \n"); int x; int y; for (x = 0; x < 50; x++) { if (strcasecmp(montados[x].path, "vacio") != 0){ for (y = 0; y < 26; y++) { if(montados[x].posicion[y].estado != 0){ printf("id=%s path=%s name=%s \n",montados[x].posicion[y].id,montados[x].path,montados[x].posicion[y].nombre); } } } } } else if (existename == true || existepath == true){ FILE *disco; struct_mbr mbr; char valornumero[5]; limpiarvar(valornumero, 5); disco = fopen(path, "rb"); if (disco != NULL) { int i; fread(&mbr, sizeof (mbr), 1, disco); bool encontrada = false; //encontro la particion bool encontropath = false; //encontro en los montados esa particion for (i = 0; i < 4 && encontrada == false; i++) { if (strcasecmp(mbr.mbr_particiones[i].part_name, name) == 0) { encontrada = true; //encontro la particion con ese nombre int x; for (x = 0; x < 50; x++) { if (strcasecmp(montados[x].path, path) == 0) { //Encontro la path encontropath = true; int y; for (y = 0; y < 26; y++) { if (montados[x].posicion[y].estado == 0) { montados[x].posicion[y].estado = 1; strcpy(montados[x].posicion[y].nombre, name); time_t hora = time(0); struct tm *tlocal = localtime(&hora); strftime(montados[x].posicion[y].fecha_montado, 16, "%d/%m/%y %H:%S", tlocal); strcpy(montados[x].posicion[y].id, "vd"); montados[x].posicion[y].id[2] = letras[x]; sprintf(valornumero, "%d", (y + 1)); strcat(montados[x].posicion[y].id, valornumero); printf("SE MONTO: %s \n\n", montados[x].posicion[y].id); y = 26; x = 50; } } } else if (strcasecmp(montados[x].path, "vacio") == 0 && encontropath == false) { strcpy(montados[x].path, path); encontropath = true; int y; for (y = 0; y < 26; y++) { if (montados[x].posicion[y].estado == 0) { montados[x].posicion[y].estado = 1; strcpy(montados[x].posicion[y].nombre, name); time_t hora = time(0); struct tm *tlocal = localtime(&hora); strftime(montados[x].posicion[y].fecha_montado, 16, "%d/%m/%y %H:%S", tlocal); strcpy(montados[x].posicion[y].id, "vd"); montados[x].posicion[y].id[2] = letras[x]; sprintf(valornumero, "%d", (y + 1)); strcat(montados[x].posicion[y].id, valornumero); printf("SE MONTO: %s \n\n", montados[x].posicion[y].id); y = 26; x = 50; } } } } } else if (mbr.mbr_particiones[i].part_type == 'e' && encontrada == false) { /***********************************************************************/ /*ENCONTRO EXTENDIDA Y NO HA ENCONTRADO AUN LA PARTICION CON ESE NOMBRE*/ /***********************************************************************/ int z; bool ultima = false; struct_ebr auxLogica; int final = mbr.mbr_particiones[i].part_start + mbr.mbr_particiones[i].part_size; for (z = mbr.mbr_particiones[i].part_start; z < final + 1 && ultima == false; z++) { fseek(disco, z, SEEK_SET); fread(&auxLogica, sizeof (struct_ebr), 1, disco); if (strcasecmp(auxLogica.part_name, name) == 0) { encontrada = true; int x; for (x = 0; x < 50; x++) { if (strcasecmp(montados[x].path, path) == 0) { //Encontro la path encontropath = true; int y; for (y = 0; y < 26; y++) { if (montados[x].posicion[y].estado == 0) { montados[x].posicion[y].estado = 1; strcpy(montados[x].posicion[y].nombre, name); time_t hora = time(0); struct tm *tlocal = localtime(&hora); strftime(montados[x].posicion[y].fecha_montado, 16, "%d/%m/%y %H:%S", tlocal); strcpy(montados[x].posicion[y].id, "vd"); montados[x].posicion[y].id[2] = letras[x]; sprintf(valornumero, "%d", (y + 1)); strcat(montados[x].posicion[y].id, valornumero); printf("SE MONTO: %s \n\n", montados[x].posicion[y].id); y = 26; x = 50; } } } else if (strcasecmp(montados[x].path, "vacio") == 0 && encontropath == false) { strcpy(montados[x].path, path); encontropath = true; int y; for (y = 0; y < 26; y++) { if (montados[x].posicion[y].estado == 0) { montados[x].posicion[y].estado = 1; strcpy(montados[x].posicion[y].nombre, name); time_t hora = time(0); struct tm *tlocal = localtime(&hora); strftime(montados[x].posicion[y].fecha_montado, 16, "%d/%m/%y %H:%S", tlocal); strcpy(montados[x].posicion[y].id, "vd"); montados[x].posicion[y].id[2] = letras[x]; sprintf(valornumero, "%d", (y + 1)); strcat(montados[x].posicion[y].id, valornumero); printf("SE MONTO: %s \n\n", montados[x].posicion[y].id); y = 26; x = 50; } } } } } z = auxLogica.part_next - 1; if (auxLogica.part_next == -1) { ultima = true; } } } } if (encontrada == false) { printf("No existe una particion con ese nombre \n\n"); } }else{ printf("No existe Disco con ese nombre \n"); } } } void Umount(Comando comando[]){ int cont = 2; while (strcasecmp(comando[cont].comando, "vacio") != 0) { int x; int y; bool encontrado = false; for (x = 0; x < 50; x++) { if (strcasecmp(montados[x].path, "vacio") != 0){ for (y = 0; y < 26; y++) { if(strcasecmp(montados[x].posicion[y].id, comando[cont].comando)==0 && montados[x].posicion[y].estado != 0){ montados[x].posicion[y].estado = 0; limpiarvar(montados[x].posicion[y].id, 6); limpiarvar(montados[x].posicion[y].nombre, 16); encontrado = true; x = 50; y = 26; printf("Se desmonto %s exitosamente \n",comando[cont].comando); } } } } if(encontrado == false){ printf("No se encuentra montado %s actualmente \n",comando[cont].comando); } cont = cont + 2; } } void Reporte(Comando comando[]){ //auxiliares para almacenar valores char path[200]; //path donde saldra el reporte limpiarvar(path, 200); char id[6]; limpiarvar(id, 6); char name[20]; limpiarvar(name, 20); char pathReporte[200]; //path del disco que se va a utilizar; limpiarvar(pathReporte, 200); char pathRutaAux[200]; char pathRuta[200]; limpiarvar(pathRuta, 200); limpiarvar(pathRutaAux, 200); //Booleanos para saber que vienen todos los parametros bool existepath = false; bool existename = false; bool existeid = false; bool encontrado = false; //para verificar si esta el nodo montado int cont = 0; while (strcasecmp(comando[cont].comando, "vacio") != 0) { if (strcasecmp(comando[cont].comando, "-name") == 0) { //NOMBRE DEL TIPO REPORTE A GENERAR cont++; if (strcasecmp(comando[cont].comando, "mbr") == 0 || strcasecmp(comando[cont].comando, "disk") == 0 ) { existename = true; strcpy(name, comando[cont].comando); } else { printf("Tipo de reporte incorrecto \n"); } } else if (strcasecmp(comando[cont].comando, "-path") == 0) { //PATH DE SALIDA DEL REPORTE cont++; strcpy(path, comando[cont].comando); /******************************/ /*CAMBIAR ESTE VERIFICAR PATH*/ /******************************/ VerificarPathReporte(path); existepath = true; } else if (strcasecmp(comando[cont].comando, "-id") == 0) { //ID DEL MONTADO A UTILIZAR cont++; strcpy(id, comando[cont].comando); existeid = true; int i, j; for (i = 0; i < 50; i++) { for (j = 0; j < 26; j++) { if (strcasecmp(montados[i].posicion[j].id, id) == 0) { encontrado = true; strcpy(pathReporte, montados[i].path); j = 26; i = 50; } } } } cont++; } /*************************************************/ /*COMIENZAN VALIDACIONES PARA GENERAR EL REPORTE*/ /*************************************************/ if (existeid == true && existename == true && existepath == true) { if (encontrado == true) { FILE* disco; disco = fopen(pathReporte, "rb"); if (disco != NULL) { if (strcasecmp(name, "disk") == 0) { GenerarReporteDisk(pathReporte, path); } else if (strcasecmp(name, "mbr") == 0) { GenerarReporteMBR(pathReporte, path); } } else { printf("No existe el disco \n"); } fclose(disco); } else { printf("No se ha encontrado el id \n"); } } else { printf("Error, faltan parametros obligatorios \n"); } } void GenerarReporteMBR(char disco[], char archivosalida[]){ struct_mbr mbr; //usado para recuperar el mbr del disco char text[10000]; limpiarvar(text, 10000); FILE *dot; //archivo donde se escribe el dot FILE *rdot; //archivo del disco dot = fopen("/home/juande/Escritorio/MBR.dot", "wt+"); rdot = fopen(disco, "rb+"); if (rdot != NULL) { fseek(rdot, 0l, SEEK_SET); fread(&mbr, sizeof (struct_mbr), 1, rdot); //Recuperando el mbr del disco int cantExtendidas = CantidadParticionesExtendidas(mbr); int cantPrimarias = CantidadParticionesPrimarias(mbr); int totalparticiones = cantExtendidas + cantPrimarias; struct_particion vecparticiones[totalparticiones]; //vector para almacenar las particiones que existen actualmente en el disco int j, p, cont = 0, contador = 0; char str[15]; limpiarvar(str, 15); int espaciolibre; //variable que se utiliza para ir verificando si la partcion cabe en ese espacio if (totalparticiones > 0) { for (j = 0; j < 4; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mbr.mbr_particiones[j].part_start > 0 && mbr.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mbr.mbr_particiones[j]; cont++; } } /**************************************/ /*ORDENANDO EL VECTOR POR BURBUJA******/ /*************************************/ if (totalparticiones > 0) { for (j = 0; j < totalparticiones; j++) { for (p = 0; p < totalparticiones - 1; p++) { if (vecparticiones[p].part_start > vecparticiones[p + 1].part_start) { struct_particion aux = vecparticiones[p]; vecparticiones[p] = vecparticiones[p + 1]; vecparticiones[p + 1] = aux; } } } } fprintf(dot, "digraph G {\n nodesep=.10;\n rankdir=LR;\n node [shape=plaintext,width=.2,height=.2];\n"); /*GRAFICANDO MBR*/ fprintf(dot, "node%d [label=<<table border=\"0 \" cellborder=\"1 \" cellspacing=\"0 \" > <tr><td bgcolor=\"red\" ><b>PARAMETRO</b></td><td bgcolor=\"red\"><b>VALOR</b></td></tr> \n", contador); contador++; fprintf(dot,"<tr><td> mbr_tamano</td><td> %d </td></tr> \n", mbr.mbr_tamano); fprintf(dot,"<tr><td> mbr_fecha</td><td> %s </td></tr> \n", mbr.mbr_fecha_creacion); fprintf(dot,"<tr><td> mbr_disk_signature</td><td> %d </td></tr> \n", mbr.mbr_disk_signature); int h; for (h = 0; h < totalparticiones; h++) { fprintf(dot,"<tr><td> part_name_%d</td><td> %s </td></tr> \n",h, vecparticiones[h].part_name); //nombre fprintf(dot,"<tr><td> part_status_%d</td><td> %d </td></tr> \n",h, vecparticiones[h].part_status); //status fprintf(dot,"<tr><td> part_type_%d</td><td> %c </td></tr> \n",h, vecparticiones[h].part_type); //tipo fprintf(dot,"<tr><td> part_fit_%d</td><td> %c </td></tr> \n",h, vecparticiones[h].part_fit); //fit fprintf(dot,"<tr><td> part_start_%d</td><td> %d </td></tr> \n",h, vecparticiones[h].part_start); //inicio fprintf(dot,"<tr><td> part_size_%d</td><td> %d </td></tr> \n",h, vecparticiones[h].part_size); //tipo } fprintf(dot,"</table>>]; \n"); for (h = 0; h < totalparticiones; h++) { int i; FILE * nuevodisco; int ecount = 0; if (vecparticiones[h].part_type == 'e' || vecparticiones[h].part_type == 'E') { struct_ebr auxnombres; int fin = vecparticiones[h].part_size + vecparticiones[h].part_start; bool ultima = false; for (i = vecparticiones[h].part_start; i < fin + 1 && ultima == false; i++) { nuevodisco = fopen(disco, "rb"); fseek(nuevodisco, i, SEEK_SET); fread(&auxnombres, sizeof (struct_ebr), 1, nuevodisco); if(auxnombres.part_start != vecparticiones[h].part_start){ fprintf(dot, "node%d [label=<<table border=\"0 \" cellborder=\"1 \" cellspacing=\"0 \" > <tr><td bgcolor=\"blue\" ><b>PARAMETRO</b></td><td bgcolor=\"blue\"><b>VALOR</b></td></tr> \n", contador); contador++; fprintf(dot,"<tr><td> part_fit_%d </td><td> %c </td></tr> \n",ecount,auxnombres.part_fit); fprintf(dot,"<tr><td> part_name_%d </td><td> %s </td></tr> \n",ecount,auxnombres.part_name); fprintf(dot,"<tr><td> part_next_%d </td><td> %d </td></tr> \n",ecount,auxnombres.part_next); fprintf(dot,"<tr><td> part_size_%d </td><td> %d </td></tr> \n",ecount,auxnombres.part_size); fprintf(dot,"<tr><td> part_start_%d </td><td> %d </td></tr> \n",ecount,auxnombres.part_start); fprintf(dot,"<tr><td> part_status_%d </td><td> %c </td></tr> \n </table>>]; \n",ecount,auxnombres.part_status); } if (auxnombres.part_next == -1) { ultima = true; } i = auxnombres.part_next - 1; //Se mueve i hasta donde termina la particion para leer otro bloque fclose(nuevodisco); } } } fprintf(dot,"\n}"); fclose(dot); } } else { //printf("No existe el disco"); } char cmd [200]; char cmd2 [200]; char aux[100]; limpiarvar(cmd, 200); limpiarvar(cmd2, 200); limpiarvar(aux, 100); strcpy(aux, archivosalida); strcpy(cmd2,"gnome-open /home/juande/Escritorio/disco1.pdf "); strcat(cmd2,aux); strcpy(cmd, "dot -Tpdf /home/juande/Escritorio/MBR.dot -o "); strcat(cmd, aux); system(cmd); system(cmd2); } void GenerarReporteDisk(char nombreArchivo[], char nombreSalida[]) { int tam1, tam2, tam3, tam4; int frag1, frag2, frag3, frag4, frag5; struct_mbr mb; int count = 0; //cluster int contador = 0; //nodo char texto [10000]; limpiarvar(texto, 10000); FILE * ar; FILE * ardot; VerificarPath(nombreSalida); ardot = fopen(nombreArchivo, "rb+"); ar = fopen("/home/juande/Escritorio/disk.dot", "wt+"); char str[15]; limpiarvar(str, 15); if (ardot != NULL) { fread(&mb, sizeof (struct_mbr), 1, ardot); } else { printf("ERROR AL ABRIR EL ARCHIVO\n"); } //COMENZANDO A LEER EL ARCHIVO if (ar != NULL) { int cantExtendidas = CantidadParticionesExtendidas(mb); int cantPrimarias = CantidadParticionesPrimarias(mb); int totalparticiones = cantExtendidas + cantPrimarias; struct_particion vecparticiones[totalparticiones]; int j, p, cont = 0; if (totalparticiones < 4) { for (j = 0; j < 4; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mb.mbr_particiones[j].part_start > 0 && mb.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mb.mbr_particiones[j]; cont++; } } } else if (totalparticiones == 4) { for (j = 0; j < 4; j++) { //Verificando que particiones existen y almacenandolas en un vector if (mb.mbr_particiones[j].part_start > 0 && mb.mbr_particiones[j].part_status != '0') { vecparticiones[cont] = mb.mbr_particiones[j]; cont++; } } } /**************************************/ /*ORDENANDO EL VECTOR POR BURBUJA******/ /*************************************/ if (totalparticiones > 1) { for (j = 0; j < totalparticiones; j++) { for (p = 0; p < totalparticiones - 1; p++) { if (vecparticiones[p].part_start > vecparticiones[p + 1].part_start) { struct_particion aux = vecparticiones[p]; vecparticiones[p] = vecparticiones[p + 1]; vecparticiones[p + 1] = aux; } } } } strcpy(texto, "digraph G {\n nodesep=.10;\n rankdir=BT;\n node [shape=record];\n"); strcat(texto, "label=\"DISCO FORMATO LWH\";\n"); strcat(texto, "\nsubgraph cluster"); sprintf(str, "%d", count); strcat(texto, str); count++; strcat(texto, "{\n"); strcat(texto, "label=\"PARTICIONES\";\n"); /****************************************************** *****************GRAFICANDO PARTICIONES************** *****************************************************/ int h; for (h = totalparticiones - 1; h >= 0; h--) { if (h == 0) { bool ultima = false; tam1 = vecparticiones[h].part_start + vecparticiones[h].part_size; // printf("EL TAMANIO DEL BLOQUE PARTI1 ES:%d\n", tam1); //SI ES LA ULTIMA PARTICION frag1 = vecparticiones[h].part_start - (sizeof (struct_mbr) + 1); if (totalparticiones == 1) { ultima = true; frag5 = mb.mbr_tamano - tam1; strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag5); strcat(texto, str); strcat(texto, "\",height=1];\n"); } if (totalparticiones > 1) { frag2 = (vecparticiones[h + 1].part_start)-(tam1 + 1); if (frag2 > 0 && frag1 > 0 && ultima == false) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag1); strcat(texto, str); strcat(texto, "\",height=1];\n"); } else { if (frag2 > 0) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag2); strcat(texto, str); strcat(texto, "\",height=1];\n"); } } } strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0> NOMBRE:"); sprintf(str, "%s", vecparticiones[h].part_name); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", vecparticiones[h].part_start); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", vecparticiones[h].part_size); strcat(texto, str); strcat(texto, "\n TIPO:"); sprintf(str, "%c", vecparticiones[h].part_type); strcat(texto, str); strcat(texto, "\",height=1];\n"); if (frag1 > 0) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag1); strcat(texto, str); strcat(texto, "\",height=1];\n"); } if (vecparticiones[h].part_type == 'E' || vecparticiones[h].part_type == 'e') { struct_ebr veclogicas[50]; int logic = 0; int j; struct_ebr ebr; fseek(ardot, vecparticiones[h].part_start, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j = 0; while (j < 50) { if (ebr.part_next == -1) { if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } break; } if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } fseek(ardot, ebr.part_next, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j++; } strcat(texto, "subgraph cluster_0 {\n"); strcat(texto, "rankdir = \"RL\";\n"); strcat(texto, "label = \"PARTICIONES LOGICAS\";\n"); strcat(texto, "n_n[shape=\"box\",style=\"filled\",color=\"white\",label=\"\",width = 0.00001, heigth = 0.00001];\n"); j = logic - 1; bool primera = false; int a = 100; while (j >= 0) { if (primera == false) { strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); primera = true; } else { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EBR\"];\n"); } j--; } strcat(texto, "}\n"); } } else if (h == 1) { tam2 = vecparticiones[h].part_start + vecparticiones[h].part_size; if (totalparticiones == 2) { frag5 = mb.mbr_tamano - tam2; strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag5); strcat(texto, str); strcat(texto, "\",height=1];\n"); } strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0> NOMBRE:"); sprintf(str, "%s", vecparticiones[h].part_name); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", vecparticiones[h].part_start); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", vecparticiones[h].part_size); strcat(texto, str); strcat(texto, "\n TIPO:"); sprintf(str, "%c", vecparticiones[h].part_type); strcat(texto, str); strcat(texto, "\",height=1];\n"); frag3 = vecparticiones[h + 1].part_start - (tam2 + 1); if (frag3 > 0) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag3); strcat(texto, str); strcat(texto, "\",height=1];\n"); } if (vecparticiones[h].part_type == 'E' || vecparticiones[h].part_type == 'e') { struct_ebr veclogicas[50]; int logic = 0; int j; struct_ebr ebr; fseek(ardot, vecparticiones[h].part_start, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j = 0; while (j < 50) { if (ebr.part_next == -1) { if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } break; } if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } fseek(ardot, ebr.part_next, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j++; } strcat(texto, "subgraph cluster_0 {\n"); strcat(texto, "rankdir = \"RL\";\n"); strcat(texto, "label = \"LOGICAS\";\n"); strcat(texto, "n_n[shape=\"box\",style=\"filled\",color=\"white\",label=\"\",width = 0.00001, heigth = 0.00001];\n"); j = logic - 1; bool primera = false; int a = 100; while (j >= 0) { if (primera == false) { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); primera = true; } else { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); } j--; } } } else if (h == 2) { tam3 = vecparticiones[h].part_start + vecparticiones[h].part_size; if (totalparticiones == 3) { frag5 = mb.mbr_tamano - tam3; ; strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag5); strcat(texto, str); strcat(texto, "\",height=1];\n"); frag4 = 0; } else { frag4 = vecparticiones[h + 1].part_start - (tam3 + 1); } strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0> NOMBRE:"); sprintf(str, "%s", vecparticiones[h].part_name); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", vecparticiones[h].part_start); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", vecparticiones[h].part_size); strcat(texto, str); strcat(texto, "\n TIPO:"); sprintf(str, "%c", vecparticiones[h].part_type); strcat(texto, str); strcat(texto, "\",height=1];\n"); if (frag4 > 0) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag4); strcat(texto, str); strcat(texto, "\",height=1];\n"); } if (vecparticiones[h].part_type == 'E' || vecparticiones[h].part_type == 'e') { struct_ebr veclogicas[50]; int logic = 0; int j; struct_ebr ebr; fseek(ardot, vecparticiones[h].part_start, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j = 0; while (j < 50) { if (ebr.part_next == -1) { if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } break; } if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } fseek(ardot, ebr.part_next, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j++; } strcat(texto, "subgraph cluster_0 {\n"); strcat(texto, "rankdir = \"RL\";\n"); strcat(texto, "label = \"LOGICAS\";\n"); strcat(texto, "n_n[shape=\"box\",style=\"filled\",color=\"white\",label=\"\",width = 0.00001, heigth = 0.00001];\n"); j = logic - 1; bool primera = false; int a = 100; while (j >= 0) { if (primera == false) { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); primera = true; } else { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); } j--; } strcat(texto, "}\n"); } } else if (h == 3) { tam4 = vecparticiones[h].part_start + vecparticiones[h].part_size; frag5 = mb.mbr_tamano - tam4; if (totalparticiones == 4) { if (frag5 > 0) { strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0>"); strcat(texto, "LIBRE:\n"); sprintf(str, "%d", frag5); strcat(texto, str); strcat(texto, "\",height=1];\n"); } } strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\""); strcat(texto, "<f0> NOMBRE:"); sprintf(str, "%s", vecparticiones[h].part_name); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", vecparticiones[h].part_start); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", vecparticiones[h].part_size); strcat(texto, str); strcat(texto, "\n TIPO:"); sprintf(str, "%c", vecparticiones[h].part_type); strcat(texto, str); strcat(texto, "\",height=1];\n"); if (vecparticiones[h].part_type == 'E' || vecparticiones[h].part_type == 'e') { struct_ebr veclogicas[50]; int logic = 0; int j; struct_ebr ebr; fseek(ardot, vecparticiones[h].part_start, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j = 0; while (j < 50) { if (ebr.part_next == -1) { if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } break; } if (ebr.part_status == '1') { veclogicas[logic] = ebr; logic++; } fseek(ardot, ebr.part_next, SEEK_SET); fread(&ebr, sizeof (struct_ebr), 1, ardot); j++; } strcat(texto, "subgraph cluster_0 {\n"); strcat(texto, "rankdir = \"RL\";\n"); strcat(texto, "label = \"LOGICAS\";\n"); strcat(texto, "n_n[shape=\"box\",style=\"filled\",color=\"white\",label=\"\",width = 0.00001, heigth = 0.00001];\n"); j = logic - 1; bool primera = false; int a = 100; while (j >= 0) { if (primera == false) { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); primera = true; } else { strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"NOMBRE:\n"); sprintf(str, "%s", veclogicas[j].part_name); strcat(texto, str); strcat(texto, "\n TAMANO:"); sprintf(str, "%d", veclogicas[j].part_size); strcat(texto, str); strcat(texto, "\n INICIO:"); sprintf(str, "%d", veclogicas[j].part_start); strcat(texto, str); strcat(texto, "\n NEXT:"); sprintf(str, "%d", veclogicas[j].part_next); strcat(texto, str); strcat(texto, "\"];\n"); strcat(texto, "n_"); sprintf(str, "%d", a); a--; strcat(texto, str); strcat(texto, "_"); sprintf(str, "%d", j); strcat(texto, str); strcat(texto, "[shape=\"rectangle\",label=\"EB\"];\n"); } j--; } strcat(texto, "}\n"); } } } strcat(texto, "node"); sprintf(str, "%d", contador); strcat(texto, str); contador++; strcat(texto, "[label=\"<f0> MBR\n ID:"); sprintf(str, "%d", mb.mbr_disk_signature); strcat(texto, str); strcat(texto, "\nTAMANO:"); sprintf(str, "%d", mb.mbr_tamano); strcat(texto, str); strcat(texto, "\nFECHA:"); strcat(texto, ("%s", mb.mbr_fecha_creacion)); strcat(texto, "\", height=1];"); strcat(texto, "\n}"); strcat(texto, "\n}"); fwrite(texto, sizeof (char)*strlen(texto), 1, ar); fclose(ar); } else { printf("No existe disco\n"); } char id[5]; sprintf(id, "%d", mb.mbr_disk_signature); char cmd [200]; char aux[100]; limpiarvar(aux, 100); limpiarvar(cmd, 200); strcat(aux, nombreSalida); strcpy(cmd, "dot -Tjpg /home/juande/Escritorio/disk.dot -o "); strcat(cmd, aux); // printf("%s",cmd); system(cmd); } void Exec(Comando comando[]){ //METODO DONDE SE LEE EL ARCHIVO PARA EJECUTAR LAS INSTRUCCIONES EN OTRO METODO FILE * ar; char comand[200]; limpiarvar(comand, 200); char comandaux[200]; int contcomando = 0; limpiarvar(comandaux, 200); strcpy(comandaux, comando[2].comando); if (comandaux[0] == '\"') { int x = 3; while (strcasecmp(comando[x].comando, "vacio") != 0) { strcat(comandaux, " "); strcat(comandaux, comando[x].comando); x++; } int i; for (i = 1; i < 200; i++) { if (comandaux[i] != '\"') { comand[contcomando] = comandaux[i]; contcomando++; } else { i = 200; } } } else { strcpy(comand, comandaux); } ar = fopen(comand, "rb+"); limpiarvar(comand,200); if (ar != NULL) { while (fgets(comand, 200, ar) != NULL) { cambio(comand); char auxcadena[200]; limpiarvar(auxcadena,200); int fin = strlen(comand)-1; int asci = comand[fin]; if(comand[fin] == '\\'){ comand[fin+2] = '\0'; comand[fin+1] = '\0'; comand[fin] = '\0'; fgets(auxcadena, 200, ar); cambio(auxcadena); strcat(comand,auxcadena); } if (comand[0] == '#') { printf("Comentario: %s \n", comand); limpiarvar(comand,200); }else { printf("\n%s \n", comand); EjecutarScript(comand); limpiarvar(comand,200); } } fclose(ar); } else { printf("LA RUTA NO EXISTE\n\n"); } } void EjecutarScript(char instruccion[]){ //METODO DONDE SE EJECUTAN LOS SCRIPT DEL EXEC int i; for (i = 0; i < 25; i++) { limpiarvar(Comandos[i].comando,100); strcpy(Comandos[i].comando, "VACIO"); } int count = 0; char comando[200]; //variable donde se ira guardando cada linea de comando limpiarvar(comando, 200); strcpy(comando,instruccion); /*char** tokens, tokens2; char comando[200]; //variable donde se ira guardando cada linea de comando limpiarvar(comando, 200); strcpy(comando,instruccion); char * completo; char** variables; char * completo2; char** ssplit; //segundo split con : int count = 0; tokens = SplitComando(comando, ' '); //separando el comando por espacios en blanco if (tokens) { int i; for (i = 0; *(tokens + i); i++){ completo = *(tokens + i); variables = SplitComando(completo, ':'); if (variables) { int j; for (j = 0; *(variables + j); j++) { completo2 = *(variables + j); ssplit = SplitComando(completo2, ':'); if(ssplit){ int k; for (k = 0; *(ssplit + k); k++) { char * valor = *(ssplit + k); strcpy(comando,valor); strcpy(Comandos[count].comando,valor); count++; } free(ssplit); } } free(variables); } } free(tokens); }*/ char* token; token = strtok(comando, " "); while (token != NULL) { strcpy(Comandos[count].comando, token); count++; token = strtok(NULL, " ::"); } if (strcasecmp(Comandos[0].comando, "mkdisk") == 0) { printf("CREACION DE DISCO DURO\n"); Mkdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "rmdisk") == 0) { printf("ELIMINACION DE DISCO DURO\n"); Rmdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "fdisk") == 0) { printf("MODIFICACION DE PARTICION\n"); Fdisk(Comandos); } else if (strcasecmp(Comandos[0].comando, "exec") == 0) { printf("SE LEERA UN ARCHIVO\n"); //exec(primero->siguiente); } else if (strcasecmp(Comandos[0].comando, "mount") == 0) { printf("MONTAR PARTICION\n"); Mount(Comandos); } else if (strcasecmp(Comandos[0].comando, "umount") == 0) { printf("DESMONTAR PARTICION\n"); Umount(Comandos); } else if (strcasecmp(Comandos[0].comando, "rep") == 0) { printf("SE GENERARA UN REPORTE\n"); Reporte(Comandos); } else if (Comandos[0].comando[0] == '#') { printf("COMENTARIO\n"); }else { printf("COMANDO INVALIDO\n"); } } void InicializarMontados() { int i, j; for (i = 0; i < 50; i++) { limpiarvar(montados[i].path, 200); strcpy(montados[i].path, "vacio"); for (j = 0; j < 26; j++) { montados[i].posicion[j].estado = 0; limpiarvar(montados[i].posicion[j].id, 6); limpiarvar(montados[i].posicion[j].nombre, 16); } } } int CantidadParticionesPrimarias(struct_mbr mbr) { int cantidad = 0, i; for (i = 0; i < 4; i++) { if ((mbr.mbr_particiones[i].part_type == 'P' || mbr.mbr_particiones[i].part_type == 'p') && mbr.mbr_particiones[i].part_status == '1') { cantidad++; } } return cantidad; } int CantidadParticionesExtendidas(struct_mbr mbr) { int cantidad = 0, i; for (i = 0; i < 4; i++) { if ((mbr.mbr_particiones[i].part_type == 'E' || mbr.mbr_particiones[i].part_type == 'e') && mbr.mbr_particiones[i].part_status == '1') { cantidad++; } } return cantidad; } int ContarSlash(char path[]) { int cantidad = 0; while (*path) { if (*path == '/') { cantidad++; } path++; } return cantidad; } void cambio(char aux[]) {//METODO PARA ELIMINAR EL SALTO DE LINEA EN LOS COMANDOS int i, temp = 0; for (i = 0; i < 200 && temp == 0; i++) { if (aux[i] == '\n' || aux[i] == '\r') { aux[i] = '\0'; temp = 1; } } } void limpiarvar(char aux[], int n){ //METODO PARA LIMPIAR LOS CHAR[] PONIENDOLES '\0' int i; for (i = 0; i < n; i++) { aux[i] = '\0'; } } char** SplitComando(char* texto, const char caracter_delimitador){ //METODO QUE REALIZA UN SPLIT EN BASE AL DELIMITADOR QUE RECIBE char** cadena = 0; size_t contador = 0; char* temp = texto; char* apariciones = 0; char delimitador[2]; delimitador[0] = caracter_delimitador; delimitador[1] = 0; while (*temp) { if (caracter_delimitador == *temp) { contador++; apariciones = temp; } temp++; } contador += apariciones < (texto + strlen(texto) - 1); contador++; cadena = malloc(sizeof (char*) * contador); if (cadena) { size_t idx = 0; char* token = strtok(texto, delimitador); while (token){ if (idx < contador) *(cadena + idx++) = strdup(token); token = strtok(0, delimitador); } if (idx == contador - 1) *(cadena + idx) = 0; } return cadena; }
e05e98aa75cf802bedc7fe90c449054cb009e4fa
[ "C" ]
1
C
Juande10/-MIA-_201314412
5c02c8d61298bb344134fc6137d765999703c0f7
3c7f70cd1facd2f9e220219b538319d64d1615cc
refs/heads/main
<file_sep>rootProject.name = 'OysterApp' <file_sep>package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.example.demo.rest_template.CheckResultTemplate; import com.example.demo.rest_template.SignUpTemplate; @Service public class SignUpService { @Autowired RestTemplate restTemplate; /** 郵便番号検索API リクエストURL */ private static final String URL = "http://localhost:8082/sign-up"; // RestTemplateをコンストラクタインジェクションする public SignUpTemplate getSignUpTemplate() { return restTemplate.getForObject(URL, SignUpTemplate.class); } public CheckResultTemplate signUp(SignUpTemplate signUpTemplate) { return restTemplate.postForObject(URL, signUpTemplate, CheckResultTemplate.class); } } <file_sep>package com.example.demo.rest_template; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @JsonIgnoreProperties(ignoreUnknown = true) @Data public class CheckResultTemplate { private boolean ok; private Map<String, List<String>> errorMessages; public CheckResultTemplate() { } }
f7bbbc20678c17be9559989cd41a275fab859fe0
[ "Java", "Gradle" ]
3
Gradle
koheiKS/OysterApp
aafd7d308abd936779e6b78118266b93f490e182
8881c873d21b60c41792f620de5ba81d071e0867
refs/heads/develop
<repo_name>DigitalHistory/advanced-topics-justincapocci<file_sep>/proposal/proposal.md #Project Proposal ####My proposal for the Digital History Initiative is a website database of crowdsourced folktales primarily to facilitate interdisciplinary cooperation between anthropologists, sociologists, and other academics for whom access to more iterations of folktales would improve the scope and quality of their work. It also enables students in a variety of humanities disciplines to engage with a wide variety of first hand oral deliveries of folk-tales with personal or local significance. The goal is for this site to facilitate analysis of folktales both individually and through comparative methodology, with less of a need for the extensive field work and the ability the build off the work of previous scholars. It is based on the comparative folk-tale work such as <NAME>’s The Russian Folktale (1989) or <NAME>’ Homeric Researches (1949), which make good use of a number of folktales collected across a large range of regions and cultures, but which were still limited to the dataset collected personally by themselves or their collaborators. ####The site will allow users to post the oral accounts they recorded as well as an explanation of the context, observations on any separating elements between it and similar versions of the tale, and comments on how the tale touches on larger themes. It will also provide a way to connect the various versions as part of a larger tale type, such as the various versions of the ogre tale in Eric Csapo’s Theories of Mythology. The posting process will also involve placing tags related to the content of the folktale, such as motifs, elements, and themes that will assist searches and connecting the tale with others that contain the same tags. To further incentivize academics to contribute their recorded accounts, as well as connect the entries to examinations of their significance, they will also be able to place references with their posts to their other work on the subject so other students and scholars researching the folktale can be directed towards their works. ####Due to the nature of the initiative as a grant for a project, and the fact that a website of this nature could be theoretically maintained for as long as there is funding to maintain it, I have two alternative long-term goals for the site. The first option, which is preferable, is that after the three year period, which should provide enough time to establish the site as a useful source for the study of folktales, the funding for the maintenance of the site will be made up from partnerships with universities with large interest in folktale study and/or donations from participants. This would enable the study of folktales to continue to grow after the scope of the project is complete, and allow the site to be a useful tool in the various fields that utilize oral transmissions of folktales. The alternative is that after the three year period of crowdsourcing as many folktales as possible, the site can be converted into a kind of digital journal to be stored by academic institutions and used later. ####The first digital history method that will be utilized for this project is web design using HTML and CSS, as the effectiveness of the site will be dependant on the quality of the interface and the visual build of the site. Another method that will be utilized is the building of javascript functions which will dynamically alter and build the page based on the inputs of the user. Finally, the Oral History techniques will be relevant to building a page which incorporates an audio file with text to present a full range of information. The nature of the project is such that the content of the website is not framed and organized by the developers of the site, and thus we must insure the processes by which the site takes the audio and given information and forms a page, as well as the process by which those pages are connected to others with the same tags or under the same tale or tale type, are effective as presenting the information with very little necessary work from the user. ####My method for creating the site is to first develop the site itself, using the digital history techniques discussed previously and a team of 2 other web developers and coders. Much of the work after the building the site’s infrastructure will be to establish a starting database of accounts, and than build off this to establish it as a useful source among academics both to contribute to and utilize in their own work. The way I intend to do this is to find the work of academics who have already done or are doing field work to collect oral accounts of folk-tales, to provide the first collection of posts that will enable us to demonstrate the utility of the site and build a base of participation with it. The non-commercial nature of the site will make this part of the process easier, as bringing academics on board and utilizing their work is much easier for an academic site rather than commercial one. The long-term success of the site will be dependant on how it can help reinvigorate the study of folktales which has fallen out of popularity in the past few years, and the best way to do this is to attract academics in relevant disciplines from a wide range of regions. ####This brings up another key difficulty that we must overcome, which is that unless the site reaches out to people of varying regions, its utility will suffer greatly. If our site only acquired audio accounts from studies of Canadian Aboriginal oral tales, for example, the sites usefulness will be limited as it would only provide examples from a range that is reasonable for an academic to reach out to anyways. This is where utilizing website translation software for localization, as well as reaching out to universities internationally will be important, otherwise our site will be locked to a limited set of languages. ####This raises another problem on the development side, which is how to deal with the very diverse set of languages that would be required for this project. The best solution for this would be a mix of a translation software, a transcription software, and the encouragement for the user to provide a transcript. This is because although a transcription software combined with a translator could provide a solution, it is not ideal as running the original audio through two these two conversions would likely corrupt much of the original meaning, but without these softwares the alternatives would be to force every user to transcribe their submitted audio or retain team members to transcribe and translate the various languages. This solution would also alleviate the problem of valuing specific languages over others, which is important as key insights into the development of important folk-tales to specific cultures makes up a considerable portion of the utility of folk-tale analysis. ####We must also deal with the difficulty raised by the open nature of the site, as both malicious and mistaken actions from users can make it difficult to use the site for its primary function. Moderating content can deal with this problem to a reasonable degree, as there is not an overabundance of content that would be too much for a human moderator. It is important, however, that in moderating the content, we keep the scope of what fits the purpose of the website broad, as what we may not consider a relevant “folktale” may have use in a way we can’t anticipate, and so our efforts to moderate the content on our site should be limited to only the most irrelevant or problematic content. ####The timeline for the project will begin with a 12 week development cycle for the websites primary infrastructure, calculated based on the average web development time factoring in a small but designated team working to develop it. Within this time, we will also be reaching out to academics who have studied folktales to begin to set the stage for early participation. The goal for the first year is to have collected a reasonably large archive of multiple folktale types with multiple iterations for each. Using the work of Propp as a benchmark, we will ideally have a range of versions of the folktale types that he utilized for his hero folktales, as an example, so that the site will serve its primary function as a useful central source for a large number of folktales. The goal for the second year will be to try and integrate the site as best as possible into anthropology and sociology courses and promote the site as a useful tool to study oral accounts. ####The third year will be centred on trying to securing long term funding through partnership with universities, donations, or a combination of the two. This period is where the long term nature of the site, as either a continuing platform for research collaboration in folktales or a static collection of folktales to be preserved and utilized for study. The success of this depends largely on how well the site is integrated in both the work of anthropologists and the ability of professors to use it as part of their course work. If within about four months of the deadline, funding for the continued maintenance of the site is not secured, focus shifts from securing the longevity of the site to consolidating the entries collected into a usable format and disseminating it for academic use. ####The importance of this use is demonstrated by both the strengths and weaknesses of the field work done by scholars like Propp and Kakridis. To use Kakridis’ work on ogre tales to demonstrate this point, he was able to collect a pool of oral tales following the same story structure as the Polyphemus episode in Homer’s Odyssey, in order to place the epic work as part of a larger tradition of folktales and tracing its regional developments through a comparative analysis of the appearance of certain elements in the different versions. The scope of his examination was limited, however, by the range in which he could physically travel and the resources he could use to travel. Supplementing their own acquired accounts with a wider range of sources obtained from the site would help produce a more complete examination, provide their examination with more regional diversity, and vastly expand the scope of the potential historical implications of their findings. ####The other importance of this project is that it opens the field of examination of orally transmitted folktales to a large section of academics without the resources to undertake the kind of field work that is necessary to gather a large enough collection of tales for effective anthropological or historical comparative analysis. The nature of examining these folktales is such that more remote and local versions are key to fully understanding their development and transmission, which makes the most impactful analysis out of reach for many. Even accounts which have already been documented can only be found in a haphazard collection across various works with no real connection or organization except those drawn by the original researchers. The site thus provides a tool that gives more people access to folktales for analysis and centralizes them into a source that streamlines the process of finding these sources. ####The by-product of enabling a more effective study of folktales is that the site will jumpstart a reemergence of it as an academic practice. Comparative folktale analysis as a field has not advanced far beyond the work of Propp and his contemporaries, and this likely has to do with the relative lack of new techniques or tools that would allow more recent scholars to add to the conversation. This site would create the conditions for a collaborative effort that would enable new perspectives on folktales and their historical significance to enter the academic sphere, utilizing access to primary sources they did not have before. <file_sep>/js/maps-setup.js // initialize the variables we need // we do this here to make sure we can access them // whenever we need to -- they have 'global scope' var my_map; // this will hold the map var my_map_options; // this will hold the options we'll use to create the map var my_center = new google.maps.LatLng(45.518715,-73.581250); // center of map var my_markers = []; // we use this in the main loop below to hold the markers // this one is strange. In google maps, there is usually only one // infowindow object -- its content and position change when you click on a // marker. This is counterintuitive, but we need to live with it. var infowindow = new google.maps.InfoWindow({content:''}); var legendHTML = "<h1>Studios\:</h1>"; // I'm complicating things a bit with this next set of variables, which will help us // to make multi-colored markers var blueURL = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"; var redURL = "http://maps.google.com/mapfiles/ms/icons/red-dot.png"; var red_markers = []; var blue_markers = []; // this is for fun, if you want it. With this powerful feature you can add arbitrary // data layers to your map. It's cool. Learn more at: // https://developers.google.com/maps/documentation/javascript/datalayer#load_geojson var myGeoJSON= { "type":"FeatureCollection", "features": [{"type":"Feature", "properties":{myColor: 'red'}, "myColor" : "red", "geometry":{"type":"Polygon", "coordinates":[[[-85.60546875,49.03786794532644],[-96.6796875,40.713955826286046], [-79.62890625,37.71859032558816],[-81.2109375,49.26780455063753], [-85.60546875,49.03786794532644]]]}}, {"type":"Feature", "properties":{myColor: 'green'}, "myColor" : "green", "geometry":{"type":"Polygon", "coordinates":[[[-113.203125,58.35563036280967],[-114.78515624999999,51.944264879028765], [-101.6015625,51.944264879028765],[-112.32421875,58.263287052486035], [-113.203125,58.35563036280967]]] }}]}; /* a function that will run when the page loads. It creates the map and the initial marker. If you want to create more markers, do it here. */ function initializeMap() { my_map_options = { center: my_center, // to change this value, change my_center above zoom: 12, // higher is closer-up mapTypeId: google.maps.MapTypeId.HYBRID // you can also use TERRAIN, STREETMAP, SATELLITE }; // this one line creates the actual map my_map = new google.maps.Map(document.getElementById("map_canvas"), my_map_options); // this is an *array* that holds all the marker info var all_my_markers = [{position: new google.maps.LatLng(45.530503,-73.613894), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map to the one // located at the URL which is given by the variable blueURL, see above title: "Behaviour Interactive", window_content: "<h1>Behaviour Interactive</h1><p>Known for hit titles such as <i>Dead by Daylight</i> and <i>Far Cry 3<i/></p>" }, {position: new google.maps.LatLng(45.500609,-73.577025), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "EA Motive Studios", window_content: "<h1>EA Motive Studios</h1><p> A more recent studio created by EA, they are responsible for the recent iterations of the <i>Star Wars: Battlefront</i> series</p>" }, {position: new google.maps.LatLng(45.506213,-73.569076), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Eidos Montreal", window_content: '<h1>Eidos Montreal</h1><p>A subsidiary of Square Enix, they are the team behind the recent entries into the <i>Deus Ex</i>, <i>Tomb Raider</i> and <i> Thief</i> franchises</p>' }, {position: new google.maps.LatLng(45.530152,-73.598626), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Gameloft Montreal", window_content: '<h1>Gameloft Montreal</h1><p>A development studio specializing in mobile games, they are one of the largest mobile games studios in the industry</p>' }, {position: new google.maps.LatLng(45.502028,-73.556273), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Ludia Inc", window_content: '<h1>Ludia Inc</h1><p>A studio specializing in licensed mobile games for popular TV and movie IPs, such as <i>Jurassic Park</i> and <i>Battlestar Galactica</I><p/>' }, {position: new google.maps.LatLng(45.525995,-73.597618), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Ubisoft Montreal", window_content: '<h1>Ubisoft Montreal</h1><p>One of the first studios to be set up in Montreal, Ubisoft Montreal is known for some of the most popular video game series, including <i>Assassins\'s Creed</i>, <i>Far Cry</i>, and the Tom Clancy games</p>' }, {position: new google.maps.LatLng(45.516570,-73.559170), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Warner Brothers Games Montreal", window_content: '<h1>Warner Brothers Games Montreal</h1><p>A studio which produces game adaptations of Warner Brothers IPs, the most well known example being the Batman <i>Arkham</i> series</p> ' }, {position: new google.maps.LatLng(45.496761,-73.554729), map: my_map, icon: blueURL, // this sets the image that represents the marker in the map title: "Bethesda Games Montreal", window_content: '<h1>Bethesda Games Montreal</h1><p>A studio under Bethesda Games, a subsidiary of ZeniMax Media. Known for titles such as <i>Fallout</i> and <i>The Elder Scrolls</i></p>' }, ]; for (j = 0; j < all_my_markers.length; j++) { var marker = new google.maps.Marker({ position: all_my_markers[j].position, map: my_map, icon: all_my_markers[j].icon, title: all_my_markers[j].title, window_content: all_my_markers[j].window_content}); // this next line is ugly, and you should change it to be prettier. // be careful not to introduce syntax errors though. legendHTML += "<div class=\"pointer\" onclick=\"locateMarker(my_markers[" + j + "])\"> " + marker.window_content + "</div>"; marker.info = new google.maps.InfoWindow({content: marker.window_content}); var listener = google.maps.event.addListener(marker, 'click', function() { // if you want to allow multiple info windows, uncomment the next line // and comment out the two lines that follow it //this.info.open(this.map, this); infowindow.setContent (this.window_content); infowindow.open(my_map, this); }); my_markers.push({marker:marker, listener:listener}); if (all_my_markers[j].icon == blueURL ) { blue_markers.push({marker:marker, listener:listener}); } else if (all_my_markers[j].icon == redURL ) { red_markers.push({marker:marker, listener:listener}); } } document.getElementById("map_legend").innerHTML = legendHTML; my_map.data.addGeoJson(myGeoJSON); var romeCircle = new google.maps.Rectangle({ strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, map: my_map, bounds: { north: 45.530503, south: 45.496761, east: -73.554729, west: -73.613894 }, center: {"lat": 45.518715, "lng":-73.581250}, radius: 1000 }); my_map.data.setStyle(function (feature) { var thisColor = feature.getProperty("myColor"); return { fillColor: thisColor, strokeColor: thisColor, strokeWeight: 5 }; }); } // this hides all markers in the array // passed to it, by attaching them to // an empty object (instead of a real map) function hideMarkers (marker_array) { for (var j in marker_array) { marker_array[j].marker.setMap(null); } } // by contrast, this attaches all the markers to // a real map object, so they reappear function showMarkers (marker_array, map) { for (var j in marker_array) { marker_array[j].marker.setMap(map); } } //global variable to track state of markers var markersHidden = false; function toggleMarkers (marker_array, map) { for (var j in marker_array) { if (markersHidden) { marker_array[j].marker.setMap(map); } else { marker_array[j].marker.setMap(null); } } markersHidden = !markersHidden; } // I added this for fun. It allows you to trigger the infowindow // form outside the map. function locateMarker (marker) { console.log(marker); my_map.panTo(marker.marker.position); google.maps.event.trigger(marker.marker, 'click'); }
cb6418e73da14621890d3426aa8dd04de6670649
[ "Markdown", "JavaScript" ]
2
Markdown
DigitalHistory/advanced-topics-justincapocci
1c38774d9a040e679461becce2b204acb57cd4da
071207f01ceb5b561342a0af1ac75f009192d959
refs/heads/master
<repo_name>sudiparora/WholesaleDistribution<file_sep>/SourceCode/WDS/WDS.Entities/Entities/ContactInfo/Email.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class Email: EntityBase { public int EmailId { get; set; } public int EmailType { get; set; } public string EmailAddress { get; set; } } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/ContactInfo/Address.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class Address : EntityBase { public int AddressId { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public int AddressType { get; set; } public int CityId { get; set; } public string Pincode { get; set; } } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/ContactInfo/Phone.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class Phone: EntityBase { public int PhoneId { get; set; } public int PhoneType { get; set; } public string PhoneNumber { get; set; } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Base/SQLParameterBase.cs using WDS.DataAccess.Constants; using WDS.Shared.Infrastructure.Common; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Base { /// <summary> /// SQL Parameter base class which creates sql parameters for all the different data types. /// </summary> public class SQLParameterBase { #region NULL input parameters /// <summary> /// Creates null input parameter /// </summary> /// <param name="name"></param> /// <param name="paramType"></param> /// <returns></returns> protected static SqlParameter CreateNullParameter(string name, SqlDbType paramType) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = paramType; parameter.ParameterName = name; parameter.Value = null; parameter.Direction = ParameterDirection.Input; return parameter; } /// <summary> /// Creates null parameter for nvarchars specifying the size for the same. /// </summary> /// <param name="name"></param> /// <param name="paramType"></param> /// <param name="size"></param> /// <returns></returns> protected static SqlParameter CreateNullParameter(string name, SqlDbType paramType, int size) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = paramType; parameter.ParameterName = name; parameter.Size = size; parameter.Value = null; parameter.Direction = ParameterDirection.Input; return parameter; } #endregion #region Output parameters /// <summary> /// Creates output parameter /// </summary> /// <param name="name"></param> /// <param name="paramType"></param> /// <returns></returns> protected static SqlParameter CreateOutputParameter(string name, SqlDbType paramType) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = paramType; parameter.ParameterName = name; parameter.Direction = ParameterDirection.Output; return parameter; } /// <summary> /// Creates output parameter for nvarchar specifying the size for the same /// </summary> /// <param name="name"></param> /// <param name="paramType"></param> /// <param name="size"></param> /// <returns></returns> protected static SqlParameter CreateOutputParameter(string name, SqlDbType paramType, int size) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = paramType; parameter.Size = size; parameter.ParameterName = name; parameter.Direction = ParameterDirection.Output; return parameter; } #endregion #region Type parameters /// <summary> /// Creates input parameter for type GUID /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, Guid value) { if (value.Equals(CommonBase.Guid_NullValue)) { // If value is null then create a null parameter return CreateNullParameter(name, SqlDbType.UniqueIdentifier); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.UniqueIdentifier; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type int /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, int value) { if (value == CommonBase.Int_NullValue) { // If value is null then create a null parameter return CreateNullParameter(name, SqlDbType.Int); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.Int; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type datetime /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, DateTime? value) { if (value == CommonBase.DateTime_NullValue) { // If value is null then create a null parameter return CreateNullParameter(name, SqlDbType.DateTime); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.DateTime; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type string/varchar /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, string value) { if (value == CommonBase.String_NullValue) { // If value is null then create a null parameter return CreateNullParameter(name, SqlDbType.VarChar); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.VarChar; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type bool /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, bool value) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.Char; parameter.ParameterName = name; parameter.Value = value ? DataAccessConstants.CHAR_Y : DataAccessConstants.CHAR_N; parameter.Direction = ParameterDirection.Input; return parameter; } /// <summary> /// Creates input parameter for type string/nvarchar /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, string value, int size) { if (value == CommonBase.String_NullValue) { // If value is null then create a null parameter return CreateNullParameter(name, SqlDbType.NVarChar); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.NVarChar; parameter.Size = size; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type long /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, long value) { if (value == CommonBase.Long_NullValue) { return CreateNullParameter(name, SqlDbType.BigInt); } else { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.BigInt; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } } /// <summary> /// Creates input parameter for type char /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected static SqlParameter CreateParameter(string name, char value) { SqlParameter parameter = new SqlParameter(); parameter.SqlDbType = SqlDbType.Char; parameter.ParameterName = name; parameter.Value = value; parameter.Direction = ParameterDirection.Input; return parameter; } #endregion } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/CommonEntityParsers/LicenseParser.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; namespace WDS.DataAccess.EntityParsers { internal class LicenseParser: IEntityParser { private int ord_LicenseId; private int ord_LicenseTypeId; private int ord_LicenseNumber; private int ord_LicenseExpiryDate; public EntityBase PopulateEntity(SqlDataReader reader) { License license = new License(); if (!reader.IsDBNull(ord_LicenseId)) license.LicenseId = reader.GetInt32(ord_LicenseId); if (!reader.IsDBNull(ord_LicenseTypeId)) license.LicenseType = reader.GetInt32(ord_LicenseTypeId); if (!reader.IsDBNull(ord_LicenseNumber)) license.LicenseNumber = reader.GetString(ord_LicenseNumber); if (!reader.IsDBNull(ord_LicenseExpiryDate)) license.LicenseExpiryDate = reader.GetDateTime(ord_LicenseExpiryDate); return license; } public void PopulateOrdinals(SqlDataReader reader) { ord_LicenseId = reader.GetOrdinal(DBColumnConstants.LICENSEID); ord_LicenseTypeId = reader.GetOrdinal(DBColumnConstants.LICENSETYPE); ord_LicenseNumber = reader.GetOrdinal(DBColumnConstants.LICENSENUMBER); ord_LicenseExpiryDate = reader.GetOrdinal(DBColumnConstants.LICENSEEXPIRYDATE); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Common/EntityParserFactory.cs using WDS.DataAccess.EntityParsers; using WDS.DataAccess.Interfaces; using WDS.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Common { internal sealed class EntityParserFactory { internal IEntityParser GetParser(Type entityType) { IEntityParser parser = null; switch (entityType.Name) { case EntityConstants.ADDRESS: parser = new AddressParser(); break; case EntityConstants.PHONE: parser = new PhoneParser(); break; case EntityConstants.EMAIL: parser = new EmailParser(); break; case EntityConstants.LICENSE: parser = new LicenseParser(); break; case EntityConstants.COMPANY: parser = new CompanyParser(); break; case EntityConstants.LICENSINGINFO: parser = new LicensingInfoParser(); break; } return parser; } internal IParentEntityParser GetParentParser(Type entityType) { IParentEntityParser parser = null; //switch (entityType.Name) //{ //} return parser; } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/ContactInfoParsers/PhoneParser.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; namespace WDS.DataAccess.EntityParsers { internal class PhoneParser: IEntityParser { private int ord_PhoneId; private int ord_PhoneType; private int ord_PhoneNumber; public EntityBase PopulateEntity(SqlDataReader reader) { Phone phone = new Phone(); if (!reader.IsDBNull(ord_PhoneId)) phone.PhoneId = reader.GetInt32(ord_PhoneId); if (!reader.IsDBNull(ord_PhoneType)) phone.PhoneType = reader.GetInt32(ord_PhoneType); if (!reader.IsDBNull(ord_PhoneNumber)) phone.PhoneNumber = reader.GetString(ord_PhoneNumber); return phone; } public void PopulateOrdinals(SqlDataReader reader) { ord_PhoneId = reader.GetOrdinal(DBColumnConstants.PHONEID); ord_PhoneType = reader.GetOrdinal(DBColumnConstants.PHONETYPE); ord_PhoneNumber = reader.GetOrdinal(DBColumnConstants.PHONENUMBER); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/TestWDS/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.EntityDAC; using WDS.Entities; namespace TestWDS { class Program { static void Main(string[] args) { CompanyDAC companyDAC = new CompanyDAC(); Company company = companyDAC.GetCompanyByCompanyId(1); } } } <file_sep>/SourceCode/WDS/WDS.Desktop/ViewModels/CompanyCreationWizard/CompanyCreationWizardViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.Desktop.Base; using WDS.Desktop.Shared.Base; namespace WDS.Desktop.ViewModels { public class CompanyCreationWizardViewModel: ViewModelBase { #region Fields private ReadOnlyCollection<WizardStepViewModelBase> wizardSteps; private WizardStepViewModelBase currentStep; #endregion #region Properties public ReadOnlyCollection<WizardStepViewModelBase> WizardSteps { get { return wizardSteps; } } public WizardStepViewModelBase CurrentStep { get { return currentStep; } set { SetProperty(ref currentStep, value); } } #endregion #region CTOR public CompanyCreationWizardViewModel (CompanyCreationWelcomeViewModel welcomeVM, CompanyGeneralInformationViewModel generalInfoVM, CompanyContactInformationViewModel contactInfoVM, CompanyLicenseInformationViewModel licenseInfoVM) { List<WizardStepViewModelBase> steps = new List<WizardStepViewModelBase>(); steps.Add(welcomeVM); steps.Add(generalInfoVM); steps.Add(contactInfoVM); steps.Add(licenseInfoVM); wizardSteps = new ReadOnlyCollection<WizardStepViewModelBase>(steps); this.CurrentStep = this.WizardSteps[0]; } #endregion } } <file_sep>/SourceCode/WDS/WDS.Entities/EntityConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class EntityConstants { public const string ADDRESS = "Address"; public const string PHONE = "Phone"; public const string EMAIL = "Email"; public const string PERSON = "Person"; public const string LICENSE = "License"; public const string COMPANY = "Company"; public const string LICENSINGINFO = "LicensingInfo"; } } <file_sep>/SourceCode/WDS/WDS.Desktop/Base/WizardStepViewModelBase.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.Desktop.Shared.Base; namespace WDS.Desktop.Base { public class WizardStepViewModelBase: ViewModelBase { } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/CommonEntityParsers/PersonParser.cs using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.EntityParsers { internal class PersonParser: IParentEntityParser { private int ord_PersonId; private int ord_FirstName; private int ord_MiddleName; private int ord_LastName; private int ord_DateOfBirth; //private int ord_GenderID; //private int ord_BloodGroupID; private int ord_BirthPlace; //private int ord_NationalityID; private int ord_MotherTongue; private int ord_Religion; public EntityBase PopulateEntity(SqlDataReader reader) { Person person = new Person(); if (!reader.IsDBNull(ord_PersonId)) person.PersonId = reader.GetInt32(ord_PersonId); if (!reader.IsDBNull(ord_FirstName)) person.FirstName = reader.GetString(ord_FirstName); if (!reader.IsDBNull(ord_MiddleName)) person.MiddleName = reader.GetString(ord_MiddleName); if (!reader.IsDBNull(ord_LastName)) person.LastName = reader.GetString(ord_LastName); if (!reader.IsDBNull(ord_DateOfBirth)) person.DateOfBirth = reader.GetDateTime(ord_DateOfBirth); //if (!reader.IsDBNull(ord_GenderID)) person.GenderID = reader.GetInt32(ord_GenderID); //if (!reader.IsDBNull(ord_BloodGroupID)) person.BloodGroupID = reader.GetInt32(ord_BloodGroupID); if (!reader.IsDBNull(ord_BirthPlace)) person.BirthPlace = reader.GetString(ord_BirthPlace); //if (!reader.IsDBNull(ord_NationalityID)) person.NationalityID = reader.GetInt32(ord_NationalityID); if (!reader.IsDBNull(ord_MotherTongue)) person.MotherTongue = reader.GetString(ord_MotherTongue); if (!reader.IsDBNull(ord_Religion)) person.Religion = reader.GetString(ord_Religion); return person; } public void PopulateOrdinals(SqlDataReader reader) { ord_PersonId = reader.GetOrdinal(DBColumnConstants.PERSONID); ord_FirstName = reader.GetOrdinal(DBColumnConstants.FIRSTNAME); ord_MiddleName = reader.GetOrdinal(DBColumnConstants.MIDDLENAME); ord_LastName = reader.GetOrdinal(DBColumnConstants.LASTNAME); ord_DateOfBirth = reader.GetOrdinal(DBColumnConstants.DATEOFBIRTH); //ord_GenderID = reader.GetOrdinal("GenderID"); //ord_BloodGroupID = reader.GetOrdinal("BloodGroupID"); ord_BirthPlace = reader.GetOrdinal(DBColumnConstants.BIRTHPLACE); //ord_NationalityID = reader.GetOrdinal("NationalityID"); ord_MotherTongue = reader.GetOrdinal(DBColumnConstants.MOTHERTONGUE); ord_Religion = reader.GetOrdinal(DBColumnConstants.RELIGION); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } public EntityBase PopulateEntity(SqlDataReader reader, EntityBase entity) { Person person = (Person)entity; if (!reader.IsDBNull(ord_PersonId)) person.PersonId = reader.GetInt32(ord_PersonId); if (!reader.IsDBNull(ord_FirstName)) person.FirstName = reader.GetString(ord_FirstName); if (!reader.IsDBNull(ord_MiddleName)) person.MiddleName = reader.GetString(ord_MiddleName); if (!reader.IsDBNull(ord_LastName)) person.LastName = reader.GetString(ord_LastName); if (!reader.IsDBNull(ord_DateOfBirth)) person.DateOfBirth = reader.GetDateTime(ord_DateOfBirth); //if (!reader.IsDBNull(ord_GenderID)) person.GenderID = reader.GetInt32(ord_GenderID); //if (!reader.IsDBNull(ord_BloodGroupID)) person.BloodGroupID = reader.GetInt32(ord_BloodGroupID); if (!reader.IsDBNull(ord_BirthPlace)) person.BirthPlace = reader.GetString(ord_BirthPlace); //if (!reader.IsDBNull(ord_NationalityID)) person.NationalityID = reader.GetInt32(ord_NationalityID); if (!reader.IsDBNull(ord_MotherTongue)) person.MotherTongue = reader.GetString(ord_MotherTongue); if (!reader.IsDBNull(ord_Religion)) person.Religion = reader.GetString(ord_Religion); return person; } } } <file_sep>/SourceCode/WDS/WDS.Desktop/ViewModels/CompanyCreationWizard/CompanyGeneralInformationViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.Desktop.Base; namespace WDS.Desktop.ViewModels { public class CompanyGeneralInformationViewModel : WizardStepViewModelBase { } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/ContactInfoParsers/AddressParser.cs using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.EntityParsers { internal class AddressParser: IEntityParser { private int ord_AddressId; private int ord_AddressLine1; private int ord_AddressLine2; private int ord_AddressTypeId; private int ord_CityID; private int ord_Pincode; public EntityBase PopulateEntity(SqlDataReader reader) { Address address = new Address(); if (!reader.IsDBNull(ord_AddressId)) address.AddressId = reader.GetInt32(ord_AddressId); if (!reader.IsDBNull(ord_AddressLine1)) address.AddressLine1 = reader.GetString(ord_AddressLine1); if (!reader.IsDBNull(ord_AddressLine2)) address.AddressLine2 = reader.GetString(ord_AddressLine2); if (!reader.IsDBNull(ord_AddressTypeId)) address.AddressType = reader.GetInt32(ord_AddressTypeId); if (!reader.IsDBNull(ord_CityID)) address.CityId = reader.GetInt32(ord_CityID); if (!reader.IsDBNull(ord_Pincode)) address.Pincode = reader.GetString(ord_Pincode); return address; } public void PopulateOrdinals(SqlDataReader reader) { ord_AddressId = reader.GetOrdinal(DBColumnConstants.ADDRESSID); ord_AddressLine1 = reader.GetOrdinal(DBColumnConstants.ADDRESSLINE1); ord_AddressLine2 = reader.GetOrdinal(DBColumnConstants.ADDRESSLINE2); ord_AddressTypeId = reader.GetOrdinal(DBColumnConstants.ADDRESSTYPEID); ord_CityID = reader.GetOrdinal(DBColumnConstants.CITYID); ord_Pincode = reader.GetOrdinal(DBColumnConstants.PINCODE); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Constants/DataAccessConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Constants { internal class DataAccessConstants { internal const string CHAR_Y = "Y"; internal const string CHAR_N = "N"; internal const string DATABASECONNECTIONSTRING = "SQLDataConString"; } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Common/EntityParserHelper.cs using WDS.DataAccess.Interfaces; using WDS.Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Common { /// <summary> /// /// </summary> public class EntityParserHelper { /// <summary> /// http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx /// The .net provided lazy initialization and singleton design pattern usage /// </summary> private static readonly Lazy<EntityParserFactory> entityParserFactoryInstance = new Lazy<EntityParserFactory>(() => new EntityParserFactory()); internal static EntityParserFactory EntityParserFactoryInstance { get { return entityParserFactoryInstance.Value; } } /// <summary> /// This method gets the parser object corresponding to the entity in question and returns /// a single entity object using the data reader object passed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reader"></param> /// <returns></returns> public static EntityBase PopulateEntity<T>(SqlDataReader reader) { IEntityParser parser = EntityParserFactoryInstance.GetParser(typeof(T)); parser.PopulateOrdinals(reader); return parser.PopulateEntity(reader); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="S"></typeparam> /// <param name="reader"></param> /// <param name="entity"></param> /// <returns></returns> public static EntityBase PopulateEntity<T, S>(SqlDataReader reader, S entity) where S : T where T : EntityBase { IParentEntityParser parser = EntityParserFactoryInstance.GetParentParser(typeof(T)); parser.PopulateOrdinals(reader); return parser.PopulateEntity(reader, entity); } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/CommonEntityParsers/CompanyParser.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Common; using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; using WDS.Shared.Enums; namespace WDS.DataAccess.EntityParsers { internal class CompanyParser : IEntityParser { private int ord_CompanyID; private int ord_CompanyName; public EntityBase PopulateEntity(SqlDataReader reader) { Company company = new Company(); if (!reader.IsDBNull(ord_CompanyID)) company.CompanyId = reader.GetInt32(ord_CompanyID); if (!reader.IsDBNull(ord_CompanyName)) company.CompanyName = reader.GetString(ord_CompanyName); company.CompanyAddress = (Address)EntityParserHelper.PopulateEntity<Address>(reader); company.CompanyEmail = (Email)EntityParserHelper.PopulateEntity<Email>(reader); company.CompanyPhone = (Phone)EntityParserHelper.PopulateEntity<Phone>(reader); if (reader.NextResult()) { company.CompanyLicense = (LicensingInfo)EntityParserHelper.PopulateEntity<LicensingInfo>(reader); } return company; } public void PopulateOrdinals(SqlDataReader reader) { ord_CompanyID = reader.GetOrdinal(DBColumnConstants.COMPANYID); ord_CompanyName = reader.GetOrdinal(DBColumnConstants.COMPANYNAME); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/Common/Company.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class Company: EntityBase { public int CompanyId { get; set; } public string CompanyName { get; set; } public Address CompanyAddress { get; set; } public Phone CompanyPhone { get; set; } public Email CompanyEmail { get; set; } public LicensingInfo CompanyLicense { get; set; } } } <file_sep>/SourceCode/WDS/WDS.Desktop/ViewModels/AppShellViewModel.cs using Prism.Commands; using Prism.Interactivity.InteractionRequest; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.Desktop.Shared.Base; namespace WDS.Desktop { public class AppShellViewModel : ViewModelBase { public DelegateCommand LoadedEvent { get; set; } public InteractionRequest<IConfirmation> ConfirmationRequest { get; private set; } public AppShellViewModel() { this.LoadedEvent = new DelegateCommand(Loaded); this.ConfirmationRequest = new InteractionRequest<IConfirmation>(); } private void Loaded() { this.ConfirmationRequest.Raise(new Confirmation { Title = "coNFIR" }); } } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/Common/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class Person : EntityBase { public int PersonId { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } //public int GenderID { get; set; } //public int BloodGroupID { get; set; } public string BirthPlace { get; set; } //public int NationalityID { get; set; } public string MotherTongue { get; set; } public string Religion { get; set; } public Address AddressInfo { get; set; } //public Phone PhoneInfo { get; set; } //public Email EmailInfo { get; set; } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/CommonEntityParsers/LicensingInfoParser.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Common; using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; using WDS.Shared.Enums; namespace WDS.DataAccess.EntityParsers { internal class LicensingInfoParser: IEntityParser { public EntityBase PopulateEntity(SqlDataReader reader) { LicensingInfo licensingInfo = new LicensingInfo(); int licenseType; while (reader.Read()) { licenseType = (int)reader[DBColumnConstants.LICENSETYPE]; switch (licenseType) { case (int)LicenseType.VatNo: licensingInfo.CompanyVATNo = (License)EntityParserHelper.PopulateEntity<License>(reader); break; case (int)LicenseType.LicenseNo: licensingInfo.CompanyLicenseNo = (License)EntityParserHelper.PopulateEntity<License>(reader); break; case (int)LicenseType.MfgLicNo: licensingInfo.CompanyMfgLicNo = (License)EntityParserHelper.PopulateEntity<License>(reader); break; case (int)LicenseType.ServiceTaxNo: licensingInfo.CompanyServiceTaxNo = (License)EntityParserHelper.PopulateEntity<License>(reader); break; case (int)LicenseType.FoodLicNo: licensingInfo.CompanyFoodLicNo = (License)EntityParserHelper.PopulateEntity<License>(reader); break; } } return licensingInfo; } public void PopulateOrdinals(SqlDataReader reader) { //Left empty as this is a dummy entity, and it doesnt has any properties of itself to fill in. } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Constants/DBColumnConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Constants { internal class DBColumnConstants { internal const string ADDRESSID = "AddressID"; internal const string ADDRESSLINE1 = "AddressLine1"; internal const string ADDRESSLINE2 = "AddressLine2"; internal const string ADDRESSTYPEID = "AddressTypeID"; internal const string CITYID = "CityID"; internal const string PINCODE = "Pincode"; internal const string ENTITYID = "EntityID"; internal const string ENTITYTYPEID = "EntityTypeID"; internal const string PHONEID = "PhoneID"; internal const string PHONETYPE = "PhoneTypeID"; internal const string PHONENUMBER = "PhoneNumber"; internal const string EMAILID = "EmailID"; internal const string EMAILTYPE = "EmailTypeID"; internal const string EMAILADDRESS = "EmailAddress"; internal const string PERSONID = "PersonID"; internal const string FIRSTNAME = "FirstName"; internal const string MIDDLENAME = "MiddleName"; internal const string LASTNAME = "LastName"; internal const string DATEOFBIRTH = "DateOfBirth"; internal const string BIRTHPLACE = "BirthPlace"; internal const string MOTHERTONGUE = "MotherTongue"; internal const string RELIGION = "Religion"; internal const string LICENSEID = "LicenseID"; internal const string LICENSETYPE = "LicenseTypeID"; internal const string LICENSENUMBER = "LicenseNumber"; internal const string LICENSEEXPIRYDATE = "LicenseExpiryDate"; internal const string COMPANYID = "CompanyID"; internal const string COMPANYNAME = "CompanyName"; } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Base/DACBase.cs using WDS.DataAccess.Constants; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Base { /// <summary> /// Base class for all data access classes. /// Contains methods for returning SqlCommands and SqlConnections /// </summary> public abstract class DACBase: SQLParameterBase { protected DACBase() { } protected static string ConnectionString { get { return ConfigurationManager.ConnectionStrings[DataAccessConstants.DATABASECONNECTIONSTRING].ConnectionString; } } /// <summary> /// Returns SQL Command object /// </summary> /// <param name="sqlQuery">SQL Query</param> /// <returns></returns> protected static SqlCommand GetDbSQLCommand(string sqlQuery) { SqlCommand command = new SqlCommand(); command.Connection = GetDbConnection(); command.CommandType = CommandType.Text; command.CommandText = sqlQuery; return command; } /// <summary> /// Returns databse connection /// </summary> /// <returns></returns> protected static SqlConnection GetDbConnection() { return new SqlConnection(ConnectionString); } /// <summary> /// Returns SQL command object for stored procedure calls. /// </summary> /// <param name="sprocName">Name of stored procedure</param> /// <returns></returns> protected static SqlCommand GetDbSprocCommand(string sprocName) { SqlCommand command = new SqlCommand(sprocName); command.Connection = GetDbConnection(); command.CommandType = CommandType.StoredProcedure; return command; } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityDAC/Company/CompanyDAC.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Base; using WDS.DataAccess.Constants; using WDS.Entities; namespace WDS.DataAccess.EntityDAC { public class CompanyDAC: EntityDACBase { public Company GetCompanyByCompanyId(int companyId) { Company company = new Company(); try { SqlCommand command = GetDbSprocCommand(SPConstants.GET_COMPANY_BY_COMPANYID); command.Parameters.Add(CreateParameter(SPConstants.COMPANYID, companyId)); company = GetSingleEntity<Company>(ref command); } catch (Exception ex) { } return company; } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Interfaces/IEntityParser.cs using WDS.Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Interfaces { public interface IEntityParser { EntityBase PopulateEntity(SqlDataReader reader); void PopulateOrdinals(SqlDataReader reader); SqlParameter[] PopulateParameters(EntityBase entity); } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Constants/SPConstants.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Constants { internal class SPConstants { internal const string GET_COMPANY_BY_COMPANYID = "usp_GetCompanyByCompanyID"; internal const string COMPANYID = "@CompanyID"; } } <file_sep>/SourceCode/WDS/WDS.DataAccess/Interfaces/IParentEntityParser.cs using WDS.Entities; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.DataAccess.Interfaces { public interface IParentEntityParser : IEntityParser { EntityBase PopulateEntity(SqlDataReader reader, EntityBase entity); } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/Common/LicensingInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class LicensingInfo: EntityBase { public License CompanyVATNo { get; set; } public License CompanyLicenseNo { get; set; } public License CompanyMfgLicNo { get; set; } public License CompanyServiceTaxNo { get; set; } public License CompanyFoodLicNo { get; set; } } } <file_sep>/SourceCode/WDS/WDS.Desktop/Bootstrapper.cs using Prism.Unity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Microsoft.Practices.Unity; namespace WDS.Desktop { public class Bootstrapper: UnityBootstrapper { protected override DependencyObject CreateShell() { return this.Container.Resolve<AppShell>(); } protected override void InitializeModules() { base.InitializeModules(); App.Current.MainWindow = (AppShell)this.Shell; App.Current.MainWindow.Show(); } } } <file_sep>/SourceCode/WDS/WDS.DataAccess/EntityParsers/ContactInfoParsers/EmailParser.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using WDS.DataAccess.Constants; using WDS.DataAccess.Interfaces; using WDS.Entities; namespace WDS.DataAccess.EntityParsers { internal class EmailParser: IEntityParser { private int ord_EmailId; private int ord_EmailType; private int ord_EmailAddress; public EntityBase PopulateEntity(SqlDataReader reader) { Email email = new Email(); if (!reader.IsDBNull(ord_EmailId)) email.EmailId = reader.GetInt32(ord_EmailId); if (!reader.IsDBNull(ord_EmailType)) email.EmailType = reader.GetInt32(ord_EmailType); if (!reader.IsDBNull(ord_EmailAddress)) email.EmailAddress = reader.GetString(ord_EmailAddress); return email; } public void PopulateOrdinals(SqlDataReader reader) { ord_EmailId = reader.GetOrdinal(DBColumnConstants.EMAILID); ord_EmailType = reader.GetOrdinal(DBColumnConstants.EMAILTYPE); ord_EmailAddress = reader.GetOrdinal(DBColumnConstants.EMAILADDRESS); } public SqlParameter[] PopulateParameters(EntityBase entity) { throw new NotImplementedException(); } } } <file_sep>/SourceCode/WDS/WDS.Entities/Entities/Common/License.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { public class License: EntityBase { public int LicenseId { get; set; } public int LicenseType { get; set; } public string LicenseNumber { get; set; } public DateTime LicenseExpiryDate { get; set; } } } <file_sep>/SourceCode/WDS/WDS.Entities/Base/EntityBase.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Entities { /// <summary> /// Base class for all entities /// </summary> public abstract class EntityBase { } } <file_sep>/SourceCode/WDS/WDS.Shared/Enums/Enum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WDS.Shared.Enums { public enum LicenseType { VatNo = 1, LicenseNo = 2, MfgLicNo = 3, ServiceTaxNo = 4, FoodLicNo = 5 } }
17f343bbafb4e337b16b7c48ba2f5d3525712848
[ "C#" ]
33
C#
sudiparora/WholesaleDistribution
0e7cbcbbdcc1e48b5b635d68027405abc2e257f6
052c7bbfd89a2a72af353736dc915a88bb90c982
refs/heads/master
<file_sep>$("span").click(function(){ alert("Hello!"); }); $("a span").onclick(function () { alert("click on <a>"); return false; });
3e19ab5b61f88a21caab99641efc96ca1fff012b
[ "JavaScript" ]
1
JavaScript
TaraBerkoski/bdw-messina
399b90b4615e60fe390df0bf55fb2ecacb7c1ecd
75c97961dad26e8addb59b6b0ea589dd8e64d467
refs/heads/master
<repo_name>yeonenbVa/jiaoben<file_sep>/jiaoben.php #!/usr/bin/php -q <?php //echo phpinfo();die; //error_reporting(0); checkQuestion(); function checkQuestion($topicId = "") { $file_name1 = date("Y-m-d"); $file_name2 = date("H-i-s"); $path = "./" . $file_name1 . "-math-".$file_name2.".txt"; // file_put_contents($path, ""); if (!$topicId) { $topicList = getTopicList(); } else { $topicList[]["id"] = $topicId; } foreach ($topicList as $key => $value) { echo $value["id"] . "\n"; $topic_info = getTopicByTopicId($value["id"]); $kmap_code_list = $topic_info['kmap_code_list']; $kmap_enter_code_info = $kmap_code_list["200"]; $kmap_code = $kmap_enter_code_info['kmap_code']; $kmap_codes[$key] = $kmap_code; } $tag_listes = []; foreach ($kmap_codes as $k => $val) { $tag_codes = getKmapInfoByKmapCode($val); foreach ($tag_codes as $key => $value) { $tag_listes[] = $value["tag_code"]; } } $msg_info = "tag_codes的数量 : " . count(array_unique($tag_listes)) . "\n"; // var_dump($tag_codes_info); // echo $path; //file_put_contents($path, $tag_codes_info, FILE_APPEND); // var_dump(array_unique($tag_listes));die; $err_tag_code = []; $question_ids=[]; foreach (array_unique($tag_listes) as $key => $value) { // var_dump($key); $tag_code = $value; echo $tag_code . "\n"; $knowledge = getQuestionsByKnowledge($tag_code); if ($knowledge["code"] == 200) { foreach ($knowledge["data"] as $k => $val) { $question_ids[] = $val["id"]; } } else { $err_tag_code[] = $tag_code; } } $msg_info.= "err_tag_codes的数量 : " . count($err_tag_code) . "\n"; if (count($err_tag_code)) { $msg_info .= "err_tag_codes的错误原因 : 知识点没题\n tag_code分别是:\n"; foreach ($err_tag_code as $k) { $msg_info .= $k . "\n"; } } //file_put_contents($path, $err_tag_code_info, FILE_APPEND); $msg_info.= "question_ids的数量 : " . count(array_unique($question_ids)) . "\n"; // file_put_contents($path, $msg . FILE_APPEND); $ki = 0; $err_questions = []; foreach (array_unique($question_ids) as $key => $value) { echo $ki . "-----" . $value . "\n"; $msg = getQuestionByIdAnalyse1($value); // var_dump($question_msg);die; if ($msg) { $msg_info .= 'question_id为:' . $value . "----------" . "错误原因:" . $msg . "\n"; $err_questions[$ki][] = $value; $err_questions[$ki][] = $msg; } $ki++; // if($ki>=2000){ // break; // } } $msg_info .= "question_ids错误的数量 : " . count($err_questions); file_put_contents($path, $msg_info ,FILE_APPEND); echo 'over'; die; } function getQuestionByIdAnalyse1($question_id) { $return_data = getQuestionById($question_id); $return_data = $return_data['data']; $msg = ''; if ($return_data == false) { $msg .= "接口返回数据为null\n"; } else { if (isset($return_data['id']) == false || $return_data['id'] == false) { $msg .= "错误==试题id为null\n"; } if (isset($return_data['content']) == false || $return_data['content'] == false) { $msg .= "错误==试题内容为null\n"; } if (isset($return_data['q_type']) == false || $return_data['q_type'] == false) { $msg .= "错误==试题类型null或为空\n"; } if (isset($return_data['answer']) == false || $return_data['answer'] == false) { $msg .= "错误==试题没有正确答案\n"; } if (isset($return_data['content']) && $return_data['q_type'] == 2 && !is_numeric(strpos(htmlspecialchars_decode($return_data['content']), '##$$##'))) { $preg = "/[_]+[1-9]*[_]+/"; preg_match_all($preg, $return_data['content'], $result); $num1 = count($result[0]); $preg = "/##\\$\\$##/"; preg_match_all($preg, $return_data['content'], $result); $num2 = count($result[0]); $num = $num1 + $num2; if ($num != 0) { if (isset($return_data['answer'])) { $answer_num = count($return_data['answer']); if ($num != $answer_num) { $msg .= "错误==填空题题目的答案数和题干中的特殊替换符号数量不符合,答案是: $answer_num 个,但题干中的替换符号数为: $num\n"; } } else { $msg .= "错误==题目没有正确答案\n"; } } else { $msg .= "错误==填空题题目中没有包含填空符号 ##$$## 或者 ___*___\n"; } } if ((!isset($return_data['options']) || $return_data['options'] == null) && ($return_data['q_type'] == 1 || $return_data['q_type'] == 3)) { $msg .= "错误==选择题目没有选项\n"; } elseif (!is_array($return_data['options'])) { $msg .= "错误==选择题目选项格式不正确\n"; } if (isset($return_data['answer']) && (count($return_data['answer']) == 0)) { $msg .= "错误==题目没有正确答案\n"; } if (isset($return_data['analyze'])) { if (empty($return_data['analyze'])) { $msg .= "分布解析为null\n"; } else { foreach ($return_data['analyze'] as $k => $v) { if (isset($v['content']) && empty($v['content'])) { $msg .= "分布解析为null\n"; } else { } } } } if (isset($return_data['analyze']) && count($return_data['analyze']) <= 0) { $msg .= "错误==分布解析数据类型为空\n"; } } return $msg; } function getQuestionsByKnowledge($knowledge) { $param['knowledge'] = $knowledge; $url = "http://input-math-t.51xonline.com/v2/api/getQuestionsByKnowledge"; $return_data = rpc_request($url, $param); return $return_data; } function getQuestionById($question_id) { $param['question_id'] = $question_id; $url = "http://input-math-t.51xonline.com/v2/api/getQuestionById"; $return_data = rpc_request($url, $param); return $return_data; } function getTopicByTopicId($topicId) { if ($topicId) { $param = array(); $param['tid'] = $topicId; //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getTopicByTopicId"; $return_data = rpc_request($url, $param); if (empty($return_data)) { } return $return_data['data']; } } function rpc_request($url, $param, $method = "post", $ret_json = true) { //设置选项 $opts = array( CURLOPT_TIMEOUT => 60, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_URL => $url, //CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'], ); if ($method === 'post') { $opts[CURLOPT_POST] = 1; $opts[CURLOPT_POSTFIELDS] = $param; } //初始化并执行curl请求 $ch = curl_init(); curl_setopt_array($ch, $opts); $data = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // code 码 if ($httpCode > 399) { } curl_close($ch); if ($ret_json) { $return_data = json_decode($data, true); } return $return_data; } function getTopicList() { $param = array(); //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getTopicList"; $param['type'] = 3; $return_data = rpc_request($url, $param); // var_dump($return_data);die; if (empty($return_data)) { } return $return_data['data']; } function getKmapInfoByKmapCode($kmap_code) { $param = array(); //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getKmapInfoByKmapCode"; $param['kmap_code'] = $kmap_code; $return_data = rpc_request($url, $param); if (empty($return_data)) { } return $return_data['data']; } ?> <file_sep>/jiaoben_1.php #!/usr/bin/php -q <?php //echo phpinfo();die; //error_reporting(0); checkQuestion(); function checkQuestion($topicId = "") { $file_name1 = date("Y-m-d"); $file_name2 = date("H-i-s"); $path = "./" . $file_name1 . "-math-" . $file_name2 . ".txt"; $msg_info = ""; // file_put_contents($path, ""); $use_type = array(); $use_type[1] = '先行测试'; $use_type[2] = '高效学习'; $use_type[3] = '竞赛拓展'; $use_type[4] = '招生抓手'; $use_type[5] = '学习检测'; $standard_num = 3; if (!$topicId) { $topicList = getTopicList(); } else { $topicList[]["id"] = $topicId; } foreach ($topicList as $key => $value) { echo $value["id"] . "\n"; $tid = $value["id"]; $topic_info = getTopicByTopicId($value["id"]); $tag_code_list = []; $zhlx_list = []; $zhlx_info = []; if (isset($topic_info["kmap_code_list"]["200"])) { $tag_code_list = getKmapInfoByKmapCode($topic_info["kmap_code_list"]["200"]["kmap_code"]); } if (isset($topic_info["kmap_code_list"]["265"])) { $zhlx_list = getKmapInfoByKmapCode($topic_info["kmap_code_list"]["265"]["kmap_code"]); } foreach ($tag_code_list as $key => $value) { $tag_code_info[$key]["tag_code"] = $value["tag_code"]; } foreach ($zhlx_list as $k => $val) { $zhlx_info[$k]["tag_name"] = $val["tag_code"] . " (专题Code)"; $zhlx_info[$k]["tag_code"] = $val["tag_code"]; } $return_data["knowledge_map"] = $tag_code_info; $return_data["zhlx_map"] = $zhlx_info; foreach ($tag_code_info as $key => $val) { echo $val["tag_code"]; for ($i = 1; $i < 6; $i++) { $QuestionsByKnowledge = getQuestionsByKnowledge($val["tag_code"], $i, "", $tid); $num = count($QuestionsByKnowledge); $data_return[$key][$i]["num"] = $num; if ($i == 4) { continue; } if ($i == 3) { $data_return[$key][$i]["pass"] = 1; continue; } if ($num < $standard_num) { $msg_info .= "错误---专题id:" . $tid . ",知识点:" . $val["tag_code"] . ",用途:" . $use_type[$i] . ",题量为" . $num . ",少于要求:" . $standard_num . "<hr>"; } } } if (!empty($zhlx_info)) { foreach ($zhlx_info as $val) { echo $val["tag_code"]; $QuestionsByKnowledge = getQuestionsByKnowledge($val["tag_code"], 3, "", $tid); $num = count($QuestionsByKnowledge); $data_return[$key][$i]["num"] = $num; if ($num < $standard_num) { $msg_info .= "错误---专题id:" . $tid . ",知识点:" . $val["tag_code"] . ",用途:" . $use_type[$i] . ",题量为" . $num . ",少于要求:" . $standard_num . "<hr>"; } } } } file_put_contents($path, $msg_info, FILE_APPEND); echo 'over'; die; } function getQuestionByIdAnalyse1($question_id) { $return_data = getQuestionById($question_id); $return_data = $return_data['data']; $msg = ''; if ($return_data == false) { $msg .= "接口返回数据为null\n"; } else { if (isset($return_data['id']) == false || $return_data['id'] == false) { $msg .= "错误==试题id为null\n"; } if (isset($return_data['content']) == false || $return_data['content'] == false) { $msg .= "错误==试题内容为null\n"; } if (isset($return_data['q_type']) == false || $return_data['q_type'] == false) { $msg .= "错误==试题类型null或为空\n"; } if (isset($return_data['answer']) == false || $return_data['answer'] == false) { $msg .= "错误==试题没有正确答案\n"; } if (isset($return_data['content']) && $return_data['q_type'] == 2 && !is_numeric(strpos(htmlspecialchars_decode($return_data['content']), '##$$##'))) { $preg = "/[_]+[1-9]*[_]+/"; preg_match_all($preg, $return_data['content'], $result); $num1 = count($result[0]); $preg = "/##\\$\\$##/"; preg_match_all($preg, $return_data['content'], $result); $num2 = count($result[0]); $num = $num1 + $num2; if ($num != 0) { if (isset($return_data['answer'])) { $answer_num = count($return_data['answer']); if ($num != $answer_num) { $msg .= "错误==填空题题目的答案数和题干中的特殊替换符号数量不符合,答案是: $answer_num 个,但题干中的替换符号数为: $num\n"; } } else { $msg .= "错误==题目没有正确答案\n"; } } else { $msg .= "错误==填空题题目中没有包含填空符号 ##$$## 或者 ___*___\n"; } } if ((!isset($return_data['options']) || $return_data['options'] == null) && ($return_data['q_type'] == 1 || $return_data['q_type'] == 3)) { $msg .= "错误==选择题目没有选项\n"; } elseif (!is_array($return_data['options'])) { $msg .= "错误==选择题目选项格式不正确\n"; } if (isset($return_data['answer']) && (count($return_data['answer']) == 0)) { $msg .= "错误==题目没有正确答案\n"; } if (isset($return_data['analyze'])) { if (empty($return_data['analyze'])) { $msg .= "分布解析为null\n"; } else { foreach ($return_data['analyze'] as $k => $v) { if (isset($v['content']) && empty($v['content'])) { $msg .= "分布解析为null\n"; } else { } } } } if (isset($return_data['analyze']) && count($return_data['analyze']) <= 0) { $msg .= "错误==分布解析数据类型为空\n"; } } return $msg; } function getQuestionsByKnowledge($knowledge) { $param['knowledge'] = $knowledge; $url = "http://input-math-t.51xonline.com/v2/api/getQuestionsByKnowledge"; $return_data = rpc_request($url, $param); return $return_data; } function getQuestionById($question_id) { $param['question_id'] = $question_id; $url = "http://input-math-t.51xonline.com/v2/api/getQuestionById"; $return_data = rpc_request($url, $param); return $return_data; } function getTopicByTopicId($topicId) { if ($topicId) { $param = array(); $param['tid'] = $topicId; //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getTopicByTopicId"; $return_data = rpc_request($url, $param); if (empty($return_data)) { } return $return_data['data']; } } function rpc_request($url, $param, $method = "post", $ret_json = true) { //设置选项 $opts = array( CURLOPT_TIMEOUT => 60, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_URL => $url, //CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'], ); if ($method === 'post') { $opts[CURLOPT_POST] = 1; $opts[CURLOPT_POSTFIELDS] = $param; } //初始化并执行curl请求 $ch = curl_init(); curl_setopt_array($ch, $opts); $data = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // code 码 if ($httpCode > 399) { } curl_close($ch); if ($ret_json) { $return_data = json_decode($data, true); } return $return_data; } function getTopicList() { $param = array(); //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getTopicList"; $param['type'] = 3; $return_data = rpc_request($url, $param); // var_dump($return_data);die; if (empty($return_data)) { } return $return_data['data']; } function getKmapInfoByKmapCode($kmap_code) { $param = array(); //根据知识点获取试题. $url = "http://api-topic.51yxedu.com/math/v2/getKmapInfoByKmapCode"; $param['kmap_code'] = $kmap_code; $return_data = rpc_request($url, $param); if (empty($return_data)) { } return $return_data['data']; } ?>
7b9a539a56e9358dd6cf8dff0a06fdaed3244c10
[ "PHP" ]
2
PHP
yeonenbVa/jiaoben
3a252fc94ddf66ccb0fddd375a86a63cec97b553
9855c54b8b3632d33b14878a632c62a42271511e
refs/heads/master
<file_sep><?php namespace Stef\HtmlManipulation\Manipulators; use Stef\Manipulation\Manipulators\AbstractStringManipulator; class RemoveHtmlAttributesManipulator extends AbstractStringManipulator { protected function run($string) { $string = str_replace('&nbsp;', ' ', $string); $string = iconv('UTF-8', 'ASCII//TRANSLIT', $string); $string = html_entity_decode($string); $string = str_replace('&nbsp;', ' ', $string); // echo $string; // exit; $xmlReader = $this->createXmlReader($string); var_dump($xmlReader); // exit; $string = trim($string); $string = preg_replace("/[^a-zA-Z0-9_| -]/", ' ', $string); $string = preg_replace("/[| -]+/", '-', $string); $string = strtolower(trim($string, '-')); $string = preg_replace('/-{2,}/', ' ', $string); return $string; } protected function createXmlReader($string) { return simplexml_load_string('<root>' . trim($string) . '</root>'); } }
55191b8c3f6deb6d173969f59769b61349254611
[ "PHP" ]
1
PHP
stefanius/html-manipulation
61c2691c08cb5669234e0933e192db5cdbcaeabf
7bfaa9abd4559f253460971a8044d34d3cba0c99
refs/heads/master
<file_sep> require 'omf_common/lobject' require 'omf-sfa/am/am-rest/am_authorizer' require 'omf-sfa/am/am-rest/sam_authorizer' require 'rack' module OMF::SFA::AM::Rest class SamantSessionAuthenticator < SessionAuthenticator def initialize(app, opts = {}) @app = app @opts = opts @opts[:no_session] = (@opts[:no_session] || []).map { |s| Regexp.new(s) } if @opts[:expire_after] @@expire_after = @opts[:expire_after] end @@active = true end def call(env) req = ::Rack::Request.new(env) method = req.request_method # epikoinwnei me to rack interface kai vlepei poia methodos exei zhththei (px GET) path_info = req.path_info if method == 'GET' debug "Rest Request: " + req.inspect debug "GET REST REQUEST" body = req.body unless body.nil? debug "body = " + body.gets end raise EmptyBodyException.new if body.nil? (body = body.string) if body.is_a? StringIO if body.is_a? Tempfile tmp = body body = body.read tmp.rewind end raise EmptyBodyException.new if body.empty? content_type = req.content_type raise UnsupportedBodyFormatException.new unless content_type == 'application/json' jb = JSON.parse(body) debug "json body = " + jb.inspect account = nil if jb.kind_of? Hash account = jb['credentials']['account'].nil? ? nil : jb['credentials']['account']['name'] end debug "account name = " + account.inspect # raise UnsupportedBodyFormatException.new # req.session[:authorizer] = AMAuthorizer.create_for_rest_request(env['rack.authenticated'], env['rack.peer_cert'], req.params["account"], @opts[:am_manager]) req.session[:authorizer] = SAMAuthorizer.create_for_rest_request(env['rack.authenticated'], env['rack.peer_cert'], account, @opts[:am_manager], jb['credentials']) elsif method == 'OPTIONS' #do nothing for OPTIONS elsif env["REQUEST_PATH"] == '/mapper' req.session[:authorizer] = SAMAuthorizer.create_for_rest_request(env['rack.authenticated'], env['rack.peer_cert'], req.params["account"], @opts[:am_manager]) else debug "MISC REST REQUEST" body = req.body debug "body = " + body.gets raise EmptyBodyException.new if body.nil? (body = body.string) if body.is_a? StringIO if body.is_a? Tempfile tmp = body body = body.read tmp.rewind end raise EmptyBodyException.new if body.empty? content_type = req.content_type raise UnsupportedBodyFormatException.new unless content_type == 'application/json' jb = JSON.parse(body) account = nil if jb.kind_of? Hash account = jb['credentials']['account'].nil? ? nil : jb['credentials']['account']['name'] end req.session[:authorizer] = SAMAuthorizer.create_for_rest_request(env['rack.authenticated'], env['rack.peer_cert'], account, @opts[:am_manager], jb['credentials']) end status, headers, body = @app.call(env) # if sid # headers['Set-Cookie'] = "sid=#{sid}" ##: name2=value2; Expires=Wed, 09-Jun-2021 ] # end [status, headers, body] rescue OMF::SFA::AM::InsufficientPrivilegesException => ex body = { :error => { :reason => ex.to_s, } } warn "ERROR: #{ex}" # debug ex.backtrace.join("\n") return [401, { "Content-Type" => 'application/json', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET, PUT, POST, OPTIONS' }, JSON.pretty_generate(body)] rescue EmptyBodyException => ex body = { :error => { :reason => ex.to_s, } } warn "ERROR: #{ex}" # debug ex.backtrace.join("\n") return [400, { "Content-Type" => 'application/json', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET, PUT, POST, OPTIONS' }, JSON.pretty_generate(body)] rescue UnsupportedBodyFormatException => ex body = { :error => { :reason => ex.to_s, } } warn "ERROR: #{ex}" # debug ex.backtrace.join("\n") return [400, { "Content-Type" => 'application/json', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET, PUT, POST, OPTIONS' }, JSON.pretty_generate(body)] end end # class end # module <file_sep> require 'nokogiri' require 'time' require 'zlib' require 'base64' require 'openssl' require 'omf-sfa/am/am-rpc/abstract_rpc_service' require 'omf-sfa/am/am-rpc/am_authorizer' require 'omf-sfa/am/am-rpc/v3/am_rpc_api' require 'omf-sfa/resource/gurn' require 'yaml' #require 'omf-sfa/am/privilege_credential' #require 'omf-sfa/am/user_credential' module OMF::SFA::AM module RPC; end end module OMF::SFA::AM::RPC::V3 OL_NAMESPACE = "http://nitlab.inf.uth.gr/schema/sfa/rspec/1" $acceptable_lease_states = [SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::PENDING] class NotAuthorizedException < XMLRPC::FaultException; end class AMService < OMF::SFA::AM::RPC::AbstractService include OMF::Common::Loggable attr_accessor :authorizer #implement ServiceAPI implement OMF::SFA::AM::RPC::V3::AMServiceAPI def get_version(options = {}) debug "GetVersion" config = YAML.load_file(File.dirname(__FILE__) + '/../../../../../etc/omf-sfa/getVersion_ext_v3.yaml') @return_struct[:geni_api] = 3 @return_struct[:code][:geni_code] = 0 @return_struct[:value] = { :geni_api => 3, :geni_api_versions => { 3 => config[:url] }, :geni_request_rspec_versions => [{ :type => "geni", :version => "3", :schema => "http://www.geni.net/resources/rspec/3/request.xsd", :namespace => "http://www.geni.net/resources/rspec/3", :extensions => ["http://nitlab.inf.uth.gr/schema/sfa/rspec/1/request-reservation.xsd"] }], :geni_ad_rspec_versions => [{ :type => "geni", :version => "3", :schema => "http://www.geni.net/resources/rspec/3/ad.xsd", :namespace => "http://www.geni.net/resources/rspec/3", :extensions => ["http://nitlab.inf.uth.gr/schema/sfa/rspec/1/ad-reservation.xsd"] }], :geni_credential_types => [{ :geni_type => 'geni_sfa', :geni_version => 3, }], :omf_am => "0.1", :hostname => "http://samant.lab.netmode.ntua.gr:443", :urn => "urn:publicid:IDN+samant+authority+cm", :hrn =>"samant" } @return_struct[:value].merge!(config[:getversion]) unless config[:getversion].nil? @return_struct[:output] = '' return @return_struct end def list_resources(credentials, options) debug 'Credentials: ', credentials.inspect debug 'ListResources: Options: ', options.inspect only_available = options["geni_available"] compressed = options["geni_compressed"] slice_urn = options["geni_slice_urn"] rspec_version = options["geni_rspec_version"] if rspec_version.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "'geni_rspec_version' argument is missing." @return_struct[:value] = '' return @return_struct end unless rspec_version["type"].downcase.eql?("geni") && (!rspec_version["version"].eql?("3.0") || !rspec_version["version"].eql?("3")) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "'Version' or 'Type' of RSpecs are not the same with what 'GetVersion' returns." @return_struct[:value] = '' return @return_struct end debug 'authorizer thing!!!!' debug 'slice_urn '+ slice_urn.to_s debug 'credentials '+ credentials.to_s debug '@request '+ @request.to_s debug '@@manager '+ @manager.to_s authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) debug "!!!RPC authorizer = " + authorizer.inspect debug "!!!USER = " + authorizer.user.inspect # debug "!!!ACCOUNT = " + authorizer.account.to_s # debug "!!!ACCOUNT_URN = " + authorizer.account[:urn]
 debug "!!!ACCOUNT = " + authorizer.user.accounts.first.to_s # check also this option .... # authorizer = options[:req].session[:authorizer] if slice_urn @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "Geni version 3 no longer supports arguement 'geni_slice_urn' for list resources method, please use describe instead." @return_struct[:value] = '' return @return_struct else debug "@am_manager ?" debug @am_manager # debug authorizer.to_s # original code # resources = @manager.find_all_leases(nil, ["pending", "accepted", "active"], authorizer) # comps = @manager.find_all_components_for_account(@manager._get_nil_account, authorizer) # samant addition # debug 'ready to call find all leases....V3 !!!!' # debug '$acceptable_lease_states? ' # debug $acceptable_lease_states.to_s # $acceptable_lease_states # debug 'find_all_samant_leases' # debug authorizer # authorizer.account[:urn] # debug 'authorizer' +authorizer.account[:urn] resources = @manager.find_all_samant_leases_rpc(nil, [SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::PENDING], authorizer) comps = @manager.find_all_samant_components_for_account_rpc(nil, authorizer) if only_available debug "only_available flag is true!" comps.delete_if {|c| !c.available_now?} end # resources.concat(comps) # res = OMF::SFA::Model::Component.sfa_response_xml(resources, type: 'advertisement').to_xml comps.delete_if {|c| c.to_uri.to_s.include?"/leased"} if only_available debug "only_available selected" # TODO maybe delete also interfaces and locations as well comps.delete_if {|c| (c.kind_of?SAMANT::Uxv) && c.hasResourceStatus && (c.hasResourceStatus.to_uri == SAMANT::BOOKED.to_uri) } end resources.concat(comps) debug "edo --------------------------- " debug "1 resources: " + resources.inspect # writer to write on a string variable... filename = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Offering) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) debug "2 filename: " + filename.inspect translated = translate_omn_rspec(filename) debug "3 translated: " + translated.inspect # debug "to xml: " + translated.to_xml(:indent => 5, :encoding => 'UTF-8') # res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) # -> returns the json formatted results (more detailed, omn enriched) # TODO insert identifier to res so to distinguish advertisement from request from manifest etc. (see also am_rpc_service) end #res = OMF::SFA::Resource::OComponent.sfa_advertisement_xml(resources).to_xml # if compressed # res = Base64.encode64(Zlib::Deflate.deflate(res)) # end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = translated @return_struct[:output] = '' # puts @return_struct.to_yaml return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def translate_omn_rspec(filename) puts 'omn for translation :' + filename.to_s command_name = "java -jar ./lib/omf-sfa/am/am-rpc/omn_translator/omnlib-jar-with-dependencies.jar -o advertisement -i #{filename}" debug "call java cmd: " +command_name result = `java -jar ./lib/omf-sfa/am/am-rpc/omn_translator/omnlib-jar-with-dependencies.jar -o advertisement -i #{filename}` debug " translated " new_result = Nokogiri::XML(result) # debug " new result " + new_result.to_xml # # new_result.at('node').add_child("<ns3:lease_ref id_ref=" + new_result.at('node').next.next.attributes['id'].value + "/>") # lease_ref = Nokogiri::XML::Node.new("lease_ref", new_result) # debug " lease_ref " + lease_ref.inspect # lease_ref["id_ref"] = new_result.children.first.children[3].attributes['id'].value # lease_ref.namespace = new_result.root.namespace_definitions.find{|ns| ns.href=="http://nitlab.inf.uth.gr/schema/sfa/rspec/1"} # new_result.children.first.children[1].add_child(lease_ref) # new_result = new_result.to_xml # debug new_result #################### # fix lease ref ids lease_namespace = new_result.root.namespace_definitions.find{|ns| ns.href=="http://nitlab.inf.uth.gr/schema/sfa/rspec/1"} node_namespace = new_result.root.namespace_definitions.find{|ns| ns.href=="http://www.geni.net/resources/rspec/3"} leases = new_result.xpath("//" + lease_namespace.prefix + ":lease") if node_namespace.prefix nodes = new_result.xpath("//"+node_namespace.prefix+":node") else nodes = new_result.xpath("//xmlns:node") end for lease in leases do id_ref = lease.attributes["id"].value leased_nodes = SAMANT::Lease.find(:all, :conditions => { :hasID => id_ref} ).first.isReservationOf for node in leased_nodes do node_id = node.hasComponentID puts "node_id: " + node_id for node in nodes do if node.attr("component_id") == node_id n = node break end end lease_ref = Nokogiri::XML::Node.new("lease_ref", new_result) lease_ref["id_ref"] = id_ref lease_ref.namespace = lease_namespace n.add_child(lease_ref) end end #################### debug "Translated Advertisement" + new_result.to_s new_result.to_xml(:indent => 5, :encoding => 'UTF-8') end def translate_manifest_omn_rspec(filename) puts 'manifest omn for translation :' + filename.to_s command_name = "java -jar ./lib/omf-sfa/am/am-rpc/omn_translator/omnlib-jar-with-dependencies.jar -o manifest -i #{filename}" debug "call java cmd: " +command_name result = `java -jar ./lib/omf-sfa/am/am-rpc/omn_translator/omnlib-jar-with-dependencies.jar -o manifest -i #{filename}` debug " translated " result.gsub! 'sliver_id', 'component_id' result.gsub! 'leaseID', 'id' new_result = Nokogiri::XML(result) lease_namespace = new_result.root.namespace_definitions.find{|ns| ns.href=="http://nitlab.inf.uth.gr/schema/sfa/rspec/1"} node_namespace = new_result.root.namespace_definitions.find{|ns| ns.href=="http://www.geni.net/resources/rspec/3"} leases = new_result.xpath("//" + lease_namespace.prefix + ":lease") if node_namespace.prefix nodes = new_result.xpath("//"+node_namespace.prefix+":node") else nodes = new_result.xpath("//xmlns:node") end for lease in leases do id_ref = lease.attributes["id"].value leased_nodes = SAMANT::Lease.find(:all, :conditions => { :hasID => id_ref} ).first.isReservationOf for node in leased_nodes do node_id = node.hasComponentID puts "node_id: " + node_id for node in nodes do if node.attr("component_id") == node_id n = node break end end lease_ref = Nokogiri::XML::Node.new("lease_ref", new_result) lease_ref["id_ref"] = id_ref lease_ref.namespace = lease_namespace n.add_child(lease_ref) end end #################### debug "Translated Manifest" + new_result.to_s new_result.to_xml(:indent => 5, :encoding => 'UTF-8') end def list_resources_obsolete (credentials, options) debug 'Credentials: ', credentials.inspect debug 'ListResources: Options: ', options.inspect only_available = options["geni_available"] compressed = options["geni_compressed"] slice_urn = options["geni_slice_urn"] rspec_version = options["geni_rspec_version"] if rspec_version.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "'geni_rspec_version' argument is missing." @return_struct[:value] = '' return @return_struct end unless rspec_version["type"].downcase.eql?("geni") && (!rspec_version["version"].eql?("3.0") || !rspec_version["version"].eql?("3")) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "'Version' or 'Type' of RSpecs are not the same with what 'GetVersion' returns." @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) if slice_urn @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "Geni version 3 no longer supports arguement 'geni_slice_urn' for list resources method, please use describe instead." @return_struct[:value] = '' return @return_struct else resources = @manager.find_all_leases(nil, ["pending", "accepted", "active"], authorizer) comps = @manager.find_all_components_for_account(@manager._get_nil_account, authorizer) if only_available debug "only_available flag is true!" comps.delete_if {|c| !c.available_now?} end resources.concat(comps) res = OMF::SFA::Model::Component.sfa_response_xml(resources, type: 'advertisement').to_xml end #res = OMF::SFA::Resource::OComponent.sfa_advertisement_xml(resources).to_xml if compressed res = Base64.encode64(Zlib::Deflate.deflate(res)) end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = res @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def describe(urns, credentials, options) debug 'Describe: URNS: ', urns.inspect, ' Options: ', options.inspect if urns.nil? || urns.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Arguement 'urns' is either empty or nil." @return_struct[:value] = '' return @return_struct end compressed = options["geni_compressed"] rspec_version = options["geni_rspec_version"] if rspec_version.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "'geni_rspec_version' argument is missing." @return_struct[:value] = '' return @return_struct end unless rspec_version["type"].downcase.eql?("geni") && (!rspec_version["version"].eql?("3.0") || !rspec_version["version"].eql?("3")) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "'Version' or 'Type' of RSpecs are not the same with what 'GetVersion' returns." @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end # authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) temp_authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) debug temp_authorizer.account.inspect authorizer = OMF::SFA::AM::Rest::AMAuthorizer.new(temp_authorizer.account.name, temp_authorizer.user, @manager) # resources = [] # leases = [] # if slivers_only # urns.each do |urn| # l = @manager.find_lease({urn: urn}, authorizer) # resources << l # leases << l # l.components.each do |comp| # resources << comp if comp.account.id == authorizer.account.id # end # end # else # resources = @manager.find_all_leases(authorizer.account, ["pending", "accepted", "active"], authorizer) # leases = resources.dup # resources.concat(@manager.find_all_components_for_account(authorizer.account, authorizer)) # end resources = [] leases = [] if slivers_only urns.each do |urn| l = @manager.find_samant_lease(urn, authorizer) resources << l leases << l l.isReservationOf.each do |comp| resources << comp if comp.hasSliceID == authorizer.account[:urn] end end else resources = @manager.find_all_samant_leases(slice_urn, $acceptable_lease_states, authorizer) leases = resources.dup components = @manager.find_all_samant_components_for_account(slice_urn, authorizer) #components.collect! { |r| (r.kind_of?SAMANT::Uxv) && r.hasParent ? r.hasParent : r } # Replace child nodes with parent nodes resources.concat(components) end filename = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Offering) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) debug "2 filename: " + filename.inspect translated = translate_omn_rspec(filename) debug "3 translated: " + translated.inspect debug "4 leases: " + leases.inspect # res = OMF::SFA::Model::Component.sfa_response_xml(resources, type: 'manifest').to_xml value = {} value[:geni_rspec] = translated value[:geni_urn] = slice_urn value[:geni_slivers] = [] # TODO check how to get the leases leases.each do |lease| tmp = {} debug "5 lease: " + lease.inspect debug "uri: " + lease.to_uri.to_s lease = SAMANT::Lease.for(lease.to_uri) # tmp[:geni_allocation_status] = lease.hasStatusMessage tmp[:geni_allocation_status] = "geni_allocated" tmp[:geni_error] = "" tmp[:geni_expires] = lease.expirationTime.to_s tmp[:geni_operational_status] = "geni_pending_allocation" # TODO check returned Slice ID, should be sliver urn tmp[:geni_sliver_urn] = lease.hasSliceID value[:geni_slivers] << tmp end if compressed res = Base64.encode64(Zlib::Deflate.deflate(translated)) end debug "!!! 6: returned struct: " + value.inspect @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def describe_obsolete(urns, credentials, options) debug 'Describe: URNS: ', urns.inspect, ' Options: ', options.inspect if urns.nil? || urns.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Arguement 'urns' is either empty or nil." @return_struct[:value] = '' return @return_struct end compressed = options["geni_compressed"] rspec_version = options["geni_rspec_version"] if rspec_version.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "'geni_rspec_version' argument is missing." @return_struct[:value] = '' return @return_struct end unless rspec_version["type"].downcase.eql?("geni") && (!rspec_version["version"].eql?("3.0") || !rspec_version["version"].eql?("3")) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "'Version' or 'Type' of RSpecs are not the same with what 'GetVersion' returns." @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) resources = [] leases = [] if slivers_only urns.each do |urn| l = @manager.find_lease({urn: urn}, authorizer) resources << l leases << l l.components.each do |comp| resources << comp if comp.account.id == authorizer.account.id end end else resources = @manager.find_all_leases(authorizer.account, ["pending", "accepted", "active"], authorizer) leases = resources.dup resources.concat(@manager.find_all_components_for_account(authorizer.account, authorizer)) end res = OMF::SFA::Model::Component.sfa_response_xml(resources, type: 'manifest').to_xml value = {} value[:geni_rspec] = res value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| tmp = {} tmp[:geni_sliver_urn] = lease.urn tmp[:geni_expires] = lease.valid_until.to_s tmp[:geni_allocation_status] = lease.allocation_status tmp[:geni_operational_status] = lease.operational_status value[:geni_slivers] << tmp end if compressed res = Base64.encode64(Zlib::Deflate.deflate(res)) end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def allocate(urns, credentials, rspec_s, options) debug 'Allocate: URNs: ', urns, ' RSPEC: ', rspec_s, ' Options: ', options.inspect, "time: ", Time.now if urns.nil? || credentials.nil? || rspec_s.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'urns', 'credentials', 'rspec'" @return_struct[:value] = '' return @return_struct end if urns.kind_of? String tmp = urns urns = [] urns << tmp end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end temp_authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) debug temp_authorizer.account.inspect authorizer = OMF::SFA::AM::Rest::AMAuthorizer.new(temp_authorizer.account.name, temp_authorizer.user, @manager) rspec = Nokogiri::XML.parse(rspec_s) # resources = @manager.update_resources_from_rspec(rspec.root, true, authorizer) # debug "this is the Original rspec:" # debug rspec_s # debug "this is the Nokogiri rspec:" # debug rspec.root.name.downcase rspec_hash = rspec_xml_to_hash(rspec.root, "request") resources = @manager.update_samant_resources_from_rspec(rspec_hash, true, authorizer) debug 'RESOURCES ---- ' debug resources.inspect debug 'RESOURCES ---- ' leases_only = true resources.each do |res| if !res.kind_of? SAMANT::Lease #debug "what am i looking? " + res.inspect leases_only = false break end end debug "Leases only? " + leases_only.to_s if resources.nil? || resources.empty? || leases_only debug('Allocate failed', ":all the requested resources were unavailable for the requested DateTime.") resources.each do |res| # TODO logika to check tou PENDING xreiazetai stin periptwsi kata tin opoia to lease proupirxe @am_manager.get_scheduler.delete_samant_lease(res) # if res.hasReservationState == SAMANT::PENDING end @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "all the requested resources were unavailable for the requested DateTime." @return_struct[:value] = '' return @return_struct end # TODO uncomment to obtain rspeck, commented out because it's very time-wasting filename_output = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Manifest) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) translated = translate_manifest_omn_rspec(filename_output) debug 'translated: ' debug translated.inspect debug 'over' # # leases_only = true # resources.each do |res| # if res.resource_type != 'lease' # leases_only = false # break # end # end # # if resources.nil? || resources.empty? || leases_only # debug('CreateSliver failed', "all the requested resources were unavailable for the requested DateTime.") # # resources.each do |res| # @manager.get_scheduler.delete_lease(res) if res.status == 'pending' # end # # @return_struct[:code][:geni_code] = 7 # operation refused # @return_struct[:output] = "all the requested resources were unavailable for the requested DateTime." # @return_struct[:value] = '' # return @return_struct # else # resources.each do |res| # if res.resource_type == 'node' # res.status = 'geni_allocated' # res.save # end # end # end # res = OMF::SFA::Model::Component.sfa_response_xml(resources, {:type => 'manifest'}).to_xml # value = {} # value[:geni_rspec] = res # value[:geni_slivers] = [] # resources.each do |r| # if r.resource_type == 'lease' # tmp = {} # tmp[:geni_sliver_urn] = r.urn # tmp[:geni_expires] = r.valid_until.to_s # tmp[:geni_allocation_status] = r.status == 'accepted' || r.status == 'active' ? 'geni_allocated' : 'geni_unallocated' # value[:geni_slivers] << tmp # end # end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = translated @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::UnknownResourceException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::FormatException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def rspec_xml_to_hash(descr_el, type) debug 'rspecxml_to_hash --------' # results = Array.new resources_hash = Hash.new leases_values = Hash.new node_values = Hash.new # # :leases=>[{:client_id=>"test_lease", :valid_from=>"2017-6-20T15:58:00Z", :valid_until=>"2017-6-21T21:00:00Z"}], resources_hash[:type] = type debug descr_el.attributes.inspect debug descr_el.attribute_nodes.inspect if !descr_el.nil? && descr_el.name.downcase == 'rspec' if descr_el.namespaces.values.include?(OL_NAMESPACE) # OL_NAMESPACE = "http://nitlab.inf.uth.gr/schema/sfa/rspec/1" leases = descr_el.xpath('//ol:lease', 'ol' => OL_NAMESPACE) #<ol:lease xmlns:ol="http://nitlab.inf.uth.gr/schema/sfa/rspec/1" # debug leases.inspect # debug leases.attribute('slice_id').value # debug leases.attribute('valid_from').value # debug leases.attribute('valid_until').value # debug leases.attribute('client_id').value # leases_values[:slice_id] = leases.attribute('slice_id').value leases_values[:valid_from] = leases.attribute('valid_from').value leases_values[:valid_until] = leases.attribute('valid_until').value leases_values[:client_id] = leases.attribute('client_id').value end resources_hash[:leases] = [leases_values] # resources_hash[:leases] = Array.new {leases_values} # results.push(resources_hash) nodes = descr_el.xpath('//xmlns:node') debug "nodes inspect:" debug nodes.inspect # ----- SAMANT addition ------ lease_ref = "" nodes.children.each do |node| debug node.attribute('id_ref').inspect unless node.attribute('id_ref').nil? lease_ref = node.attribute('id_ref').value break end end resources_hash[:nodes] = [] descr_el.xpath('//xmlns:node').collect do |el| if el.kind_of?(Nokogiri::XML::Element) resources_hash[:nodes] << { :component_id => el.attribute('component_id').value, :component_manager_id => el.attribute('component_manager_id').value, :component_name => el.attribute('component_name').value, :exclusive => el.attribute('exclusive').value, :lease_ref => lease_ref } end end # ---------------------------- # node_values[:component_id] = nodes.attribute('component_id').value # node_values[:component_manager_id] = nodes.attribute('component_manager_id').value # node_values[:component_name] = nodes.attribute('component_name').value # node_values[:exclusive] = nodes.attribute('exclusive').value # node_values[:client_id] = nodes.attribute('client_id').value # # debug "node.children" # debug nodes.children.inspect # Get the list of children of this node as a NodeSet # # debug nodes.children=(:lease_ref).inspect # debug nodes.children.length # nodes.children.each do |node| # # debug node.inspect # # debug node.attributes.inspect # debug node.attribute('id_ref').inspect # unless node.attribute('id_ref').nil? # node_values[:lease_ref] = node.attribute('id_ref').value # break # end # end # resources_hash[:nodes] = [node_values] debug "resources_hash" debug resources_hash.inspect end resources_hash end def allocate_obsolete (urns, credentials, rspec_s, options) debug 'Allocate: URNs: ', urns, ' RSPEC: ', rspec_s, ' Options: ', options.inspect, "time: ", Time.now if urns.nil? || credentials.nil? || rspec_s.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'urns', 'credentials', 'rspec'" @return_struct[:value] = '' return @return_struct end if urns.kind_of? String tmp = urns urns = [] urns << tmp end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) rspec = Nokogiri::XML.parse(rspec_s) resources = @manager.update_resources_from_rspec(rspec.root, true, authorizer) leases_only = true resources.each do |res| if res.resource_type != 'lease' leases_only = false break end end if resources.nil? || resources.empty? || leases_only debug('CreateSliver failed', "all the requested resources were unavailable for the requested DateTime.") resources.each do |res| @manager.get_scheduler.delete_lease(res) if res.status == 'pending' end @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "all the requested resources were unavailable for the requested DateTime." @return_struct[:value] = '' return @return_struct else resources.each do |res| if res.resource_type == 'node' res.status = 'geni_allocated' res.save end end end res = OMF::SFA::Model::Component.sfa_response_xml(resources, {:type => 'manifest'}).to_xml value = {} value[:geni_rspec] = res value[:geni_slivers] = [] resources.each do |r| if r.resource_type == 'lease' tmp = {} tmp[:geni_sliver_urn] = r.urn tmp[:geni_expires] = r.valid_until.to_s tmp[:geni_allocation_status] = r.status == 'accepted' || r.status == 'active' ? 'geni_allocated' : 'geni_unallocated' value[:geni_slivers] << tmp end end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::UnknownResourceException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::FormatException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def provision(urns, credentials, options) debug 'Provision: URNs: ', urns, ' Options: ', options.inspect, "time: ", Time.now if urns.nil? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'credentials', 'rspec'" @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) resources = [] leases = [] if slivers_only urns.each do |urn| l = @manager.find_lease({urn: urn}, authorizer) next unless l.status == "active" resources << l leases << l l.components.each do |comp| resources << comp if comp.account.id == authorizer.account.id end end else resources = @manager.find_all_leases(authorizer.account, ["active"], authorizer) #You can provision only active leases leases = resources.dup resources.concat(@manager.find_all_components_for_account(authorizer.account, authorizer)) end if leases.nil? || leases.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "There are no active slivers for slice: '#{slice_urn}'." @return_struct[:value] = '' return @return_struct end users = options['geni_users'] || [] debug "Users: #{users.inspect}" all_keys = [] users.each do |user| gurn = OMF::SFA::Model::GURN.parse(user["urn"]) u = @manager.find_or_create_user({urn: gurn.urn}, user["keys"]) u.keys.each do |k| all_keys << k unless all_keys.include? k end unless authorizer.account.users.include?(u) authorizer.account.add_user(u) authorizer.account.save end end @liaison.configure_keys(all_keys, authorizer.account) res = OMF::SFA::Model::Component.sfa_response_xml(resources, {:type => 'manifest'}).to_xml value = {} value[:geni_rspec] = res value[:geni_slivers] = [] resources.each do |resource| if resource.resource_type == 'lease' tmp = {} tmp[:geni_sliver_urn] = resource.urn tmp[:geni_expires] = resource.valid_until.to_s tmp[:geni_allocation_status] = resource.allocation_status value[:geni_slivers] << tmp end end event_scheduler = @manager.get_scheduler.event_scheduler event_scheduler.in '10s' do debug "PROVISION STARTS #{leases.inspect}" @liaison.provision(leases, authorizer) end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::UnknownResourceException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::FormatException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def renew(urns, credentials, expiration_time, options) debug('Renew: URNs: ', urns.inspect, ' until <', expiration_time, '>') if urns.nil? || urns.empty? || credentials.nil? || expiration_time.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'credentials', 'expiration_time'" @return_struct[:value] = '' return @return_struct end if expiration_time.kind_of?(XMLRPC::DateTime) expiration_time = expiration_time.to_time else expiration_time = Time.parse(expiration_time) end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end debug('Renew', slice_urn, ' until <', expiration_time, '>') authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) leases = [] if slivers_only urns.each do |urn| l = @manager.find_lease({urn: urn}, authorizer) leases << l end else leases = @manager.find_all_leases(authorizer.account, ["accepted", "active"], authorizer) end if leases.nil? || leases.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "There are no slivers for slice: '#{slice_urn}'." @return_struct[:value] = '' return @return_struct end @manager.renew_account_until({ :urn => slice_urn }, expiration_time, authorizer) value = {} value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| lease.valid_until = Time.parse(expiration_time).utc lease.save tmp = {} tmp[:geni_sliver_urn] = lease.urn tmp[:geni_expires] = lease.valid_until.to_s tmp[:geni_allocation_status] = lease.allocation_status tmp[:geni_operational_status] = lease.operational_status value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def status(urns, credentials, options) debug('Status for ', urns.inspect, ' OPTIONS: ', options.inspect) if urns.nil? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'credentials'" @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) leases = [] if slivers_only urns.each do |urn| l = @manager.find_lease({urn: urn}, authorizer) leases << l end else leases = @manager.find_all_leases(authorizer.account, ["accepted", "active"], authorizer) end value = {} value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| tmp = {} tmp[:geni_sliver_urn] = lease.urn tmp[:geni_expires] = lease.valid_until.to_s tmp[:geni_allocation_status] = lease.allocation_status tmp[:geni_operational_status] = lease.operational_status value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end def performOperationalAction(urns, credentials, action, options) debug('performOperationalAction: URNS: ', urns.inspect, ' Action: ', action, ' Options: ', options.inspect) if urns.nil? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'credentials'" @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) resources = [] leases = [] if slivers_only urns.each do |urn| l = @manager.find_lease({urn: urn}, authorizer) next unless l.status == "active" resources << l leases << l l.components.each do |comp| resources << comp if comp.account.id == authorizer.account.id end end else resources = @manager.find_all_leases(authorizer.account, ["active"], authorizer) #You can provision only active leases leases = resources.dup resources.concat(@manager.find_all_components_for_account(authorizer.account, authorizer)) end if leases.nil? || leases.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "There are no active slivers for slice: '#{slice_urn}'." @return_struct[:value] = '' return @return_struct end code, value, output= @liaison.operational_action(leases, action, options, authorizer) @return_struct[:code][:geni_code] = code @return_struct[:value] = value @return_struct[:output] = output return @return_struct rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end # close the account and release the attached resources def delete(urns, credentials, options) debug('DeleteSliver: URNS: ', urns.inspect, ' Options: ', options.inspect) if urns.nil? || urns.empty? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'urns', 'credentials'" @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end # authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) temp_authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) debug temp_authorizer.account.inspect authorizer = OMF::SFA::AM::Rest::AMAuthorizer.new(temp_authorizer.account.name, temp_authorizer.user, @manager) value = [] @manager.close_samant_account(slice_urn, authorizer).each do |l| debug('------------- variable slice_urn----------------- : ', l.inspect) tmp = {} tmp[:geni_sliver_urn] = slice_urn tmp[:geni_allocation_status] = 'geni_unallocated' value << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end # close the account and release the attached resources def delete_obsolete(urns, credentials, options) debug('DeleteSliver: URNS: ', urns.inspect, ' Options: ', options.inspect) if urns.nil? || urns.empty? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'urns', 'credentials'" @return_struct[:value] = '' return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) value = [] if slivers_only urns.each do |urn| l = OMF::SFA::Model::Lease.first({urn: urn}) tmp = {} tmp[:geni_sliver_urn] = urn tmp[:geni_allocation_status] = 'geni_unallocated' tmp[:geni_expires] = l.valid_until value << tmp end else ac = @manager.find_account({:urn => slice_urn}, authorizer) @manager.find_all_leases(ac, ['accepted', 'active'], authorizer).each do |l| tmp = {} tmp[:geni_sliver_urn] = l.urn tmp[:geni_allocation_status] = 'geni_unallocated' tmp[:geni_expires] = l.valid_until.to_s value << tmp end account = @manager.close_account(ac, authorizer) debug "Slice '#{slice_urn}' associated with account '#{account.id}:#{account.closed_at}'" end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return @return_struct rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return @return_struct end # close the account but do not release its resources def shutdown_sliver(slice_urn, credentials, options = {}) debug 'ShutdownSliver: SLICE URN: ', slice_urn, ' Options: ', options.insp authorizer = OMF::SFA::AM::RPC::AMAuthorizer.create_for_sfa_request(slice_urn, credentials, @request, @manager) if slice_urn.nil? || credentials.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:value] = '' @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'credentials'" return @return_struct end slice_urn, slivers_only, error_code, error_msg = parse_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return @return_struct end account = @manager.close_account({ :urn => slice_urn }, authorizer) @return_struct[:code][:geni_code] = 0 @return_struct[:value] = true @return_struct[:output] = '' return @return_struct end private def initialize(opts) super @manager = opts[:manager] @liaison = opts[:liaison] @return_struct = { :code => { :geni_code => "" }, :value => '', :output => '' } end def parse_urns(urns) slice_urn = nil slivers_only = false urns.each do |urn| utype = urn_type(urn) if utype == "slice" || utype == "account" if urns.size != 1 # you can't send more than one slice urns return ['', '', 1, 'only one slice urn can be described.'] end slice_urn = urn break elsif utype == 'lease' || utype == 'sliver' unless l = OMF::SFA::Model::Lease.first({urn: urn}) return ['', '', 1, "Lease '#{urn}' does not exist."] end new_slice_urn = l.account.urn slice_urn = new_slice_urn if slice_urn.nil? if new_slice_urn != slice_urn return ['', '', 1, "All sliver urns must belong to the same slice."] end slivers_only = true else return ['', '', 1, "Only slivers or a slice can be described."] end end [slice_urn, slivers_only, 0, ''] end def urn_type(urn) urn.split('+')[-2] end end # AMService end # module <file_sep>This directory contains the implementations of various Semantically Aware as well as SFA enabled APIs and services. Semantic Aggregate Manager ================= Prerequirements --------------- You may skip this part if you already have ruby 2.0.0 and the libraries required, up and running in your system. First, install rvm: $ curl https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s stable After installation just restart your terminal and type: $ type rvm | head -n 1 If it prints "rvm is a function" then everything is fine.
 Make sure you install ruby 2.0.0 version $ rvm install 2.0.0 Install xmlsec1, which is required by the am_server $ sudo apt-get install libxmlsec1-dev xmlsec1 $ sudo apt-get install libsqlite3-dev $ gem install bundler Installation ------------ The first step is to clone the SAM repository $ git clone https://github.com/maravger/samant-sfa.git $ mv samant omf_sfa $ cd omf_sfa $ mkdir ready4translation $ export OMF_SFA_HOME=`pwd` $ bundle install Configuration ------------- This file, OMF_SFA_HOME/etc/omf-sfa/omf-sfa-am.yaml, is the central configuration file of SAM. $ cd $OMF_SFA_HOME/etc/omf-sfa $ nano omf-sfa-am.yaml change domain to omf:TESTBED_NAME* *replace TESTBED_NAME with your testbed's name. For instance, at NETMODE we use "netmode". Semantic Graph Database & Ontologies ------------------------------------ Next you have to install the openrdf-sesame adaptor: $ wget https://netix.dl.sourceforge.net/project/sesame/Sesame%204/4.1.2/openrdf-sesame-4.1.2-sdk.tar.gz Unzip the folder and deploy the openrdf-sesame.war and openrdf-workbench.war, located in the openrdf-sesame-4.1.2/war folder. For the deployment you may use Apache Tomcat or any other known alternative of your choice (for the Apache Tomcat, deploying involves copying the .war files in the /webapps folder and starting the server). Now you are ready to deploy the Semantic Graph Database. Request a copy of GraphDB 8 from here: https://ontotext.com/products/graphdb/ Unfortunately we can not provide you with a direct download link, but one will be available to you shortly after filling the required fields. Make sure to download it "as a standanlone server". When the download has finished, it is time to run the GraphDB instance. After unziping it,navigate to the downloaded folder and execute the following script. $ cd /bin $ ./graphdb -d -Xms10g -Xmx10g -p ~/pid The GraphDB Workbench is available at port 7200 of your machine. Then you will have to create a new repository. Download the default configuration file: $ wget http://graphdb.ontotext.com/free/_downloads/repo-config.ttl Change the repositoryID field to your liking and issue the following command: $ curl -X POST http://0.0.0.0:7200/rest/repositories -H 'Content-Type: multipart/form-data' -F "config=@<EMAIL>" Now you should import the respective Ontologies. Firstly, download them, in your home repository, like this: $ wget http://samant.lab.netmode.ntua.gr/omn-domain-sensor_v_2_0.ttl.txt $ wget http://samant.lab.netmode.ntua.gr/omn-domain-uxv_v_2_0.ttl.txt Next you have to import the ontologies into the newly created repository, but first you have to kill the running graphdb instance. For this purpose issue the following commands: $ kill "$(cat ~/pid)" $ ./loadrdf -f -i localSAM -v -m parallel ~/omn-domain-sensor_v_2_0.ttl ~/omn-domain-uxv_v_2_0.ttl $ ./graphdb -d -Xms10g -Xmx10g -p ~/pid The semantic repository is ready! You can see your newly created repo at localhost:7200. Now it's time to deploy the sesame adapter. Navigate to the /bin folder of your tomcat installation and issue the following commands: $ ./startup.sh Navigate to the /bin folder of the /openrdf-sesame directory and run the following: $ ./console.sh > connect http://localhost:8080/openrdf-sesame > create remote and specify the variables as in the following: Please specify values for the following variables: Sesame server location [http://localhost:8080/openrdf-sesame]: http://localhost:7200/ Remote repository ID [SYSTEM]: <graphdbrepositoryID>* Local repository ID [SYSTEM@localhost]: remoteSAM Repository title [SYSTEM repository @localhost]: samRemoteClean Repository created *Remember to change the <graphdbrepositoryID> according the one you provided above. Congratulations, your repository is now created and connected to the adapter! Relational Database ------------------- Use the Rakefile to set up the relational database, where the authorization/authentication information is being stored. $ cd $OMF_SFA_HOME $ rake db:migrate This will actually create an empty database based on the information defined on the configuration file. Certificates ------------ The directory which holds the certificates is specified in the configuration file. First we have to create a root self signed certificate for our testbed that will sign every other certificate we create. $ omf_cert.rb --email root@DOMAIN** -o root.pem --duration 50000000 create_root *please replace DOMAIN with your tesbed's domain. For instance, at NETMODE testdbed, we use "netmode.ntua.gr". Then you have to copy this file to the trusted roots directory (defined in the configuration file) $ mkdir ~/.omf $ mkdir ~/.omf/trusted_roots $ cp root.pem ~/.omf/trusted_roots Now we have to create the certificate used by am_server and copy it to the corresponding directory. Please notice that we are using the root certificate, we have just created, in --root argument. $ omf_cert.rb -o am.pem --geni_uri URI:urn:publicid:IDN+omf:TESTBED_NAME*+user+am --email am@DOMAIN** --resource-id xmpp://172.16.17.32:5269@omf:TESTBED_NAME* --resource-type am_controller --root root.pem --duration 50000000 create_resource $ cp am.pem ~/.omf/ *replace TESTBED_NAME with your testbed's name. For instance, at NETMODE we use "netmode". **once again, replace DOMAIN with your tesbed's domain. For instance, at NETMODE testdbed, we use "netmode.ntua.gr". We also have to create a user certificate (for root user) for the various scripts to use. You can use this command to create certificates for any user you wish. . $ omf_cert.rb -o user_cert.pem --geni_uri URI:urn:publicid:IDN+omf:TESTBED_NAME*+user+root --email root@DOMAIN** --user root --root root.pem --duration 50000000 create_user $ cp user_cert.pem ~/.omf/ *replace TESTBED_NAME with your testbed's name. For instance, at NETMODE we use "netmode". **once again, replace DOMAIN with your tesbed's domain. For instance, at NETMODE testdbed, we use "netmode.ntua.gr". Now open the above certificates with any text editor copy the private key at the bottom of the certificate (with the headings) create a new file (get the name of the private key from the corresponding configuration file) and paste the private key in this file. For example: $ vi user_cert.pem copy something that looks like this \-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA4Rbp2cdAsZ2147QgqnQUeA4y8KSCXYpcp+acVIBFecVT94EC D59l162wMb67tGSwSim3K59olN02A6beN46u ... aafh6gmHbDGx+j1UAo1bFtA kjYJDDXxhrU1yK/foHdT38v5TlGmSvbuubuWOskCJRoKkHfbOPlH \-----END RSA PRIVATE KEY----- $ vi user_cert.pkey and paste inside. Repeat this process for the am.pem certificate (am.pem and am.pkey). Also copy the am certificate to trusted_roots folder. $ cp am.pem ~/.omf/trusted_roots Update the configuration file OMF_SFA_HOME/etc/omf-sfa/omf-sfa-am.yaml cert_chain_file: ~/omf_sfa/am.pem private_key_file: ~/omf_sfa/am_key.pem trusted_roots: ~/.omf/trusted_roots Starting a Test SAM ------------------ To start a SAM instance (at port 443) from this directory, run the following: $ cd $OMF_SFA_HOME $ bundle exec ruby -I lib lib/omf-sfa/am/am_server.rb start for the default 8001 port, or the following for the 443 port $ rvmsudo bundle exec ruby -I lib lib/omf-sfa/am/am_server.rb start -p 443 which should result into something like: DEBUG AMScheduler: initialize_event_scheduler DEBUG AMScheduler: Initial leases: [...] DEBUG AMScheduler: add_samant_lease_events_on_event_scheduler: lease: ... DEBUG AMScheduler: Existing jobs on event scheduler: DEBUG AMScheduler: job: ... DEBUG AMScheduler: job: ... Thin web server (v1.6.0 codename Greek Yogurt) Maximum connections set to 1024 Listening on 0.0.0.0:8001, CTRL+C to stop INFO XMPP::Communicator: Connecting to '...' ... Connected to the XMPP. INFO XMPP::Communicator: Connected DEBUG XMPP::Topic: New topic: ... DEBUG Auth::CertificateStore: Registering certificate for '...' - /C=US/ST=CA/O=ACME/OU=Roadrunner/CN=xmpp://10.0.0.200@omf:netmode/type=am_controller/... DEBUG OmfRc::ResourceFactory: DEBUG XMPP::Topic: New topic: am_controller AM Resource Controller ready. DEBUG XMPP::Communicator: _create >> ... SUCCEED DEBUG XMPP::Communicator: _subscribe >> ... SUCCEED DEBUG XMPP::Communicator: _subscribe >> am_controller SUCCEED DEBUG Auth::CertificateStore: Registering certificate for '{:uuid=>"...", :geni=>"omf"}' - /C=US/ST=CA/O=ACME/OU=Roadrunner/CN=xmpp://10.0.0.200@omf:netmode/type=am_controller/... DEBUG XMPP::Topic: New topic: xmpp://[email protected] DEBUG XML::Message: Found cert for 'xmpp://[email protected] - #<OmfCommon::Auth::Certificate subj=/C=US/ST=CA/O=ACME/OU=Roadrunner/CN=xmpp://10.0.0.200@omf:netmode/type=am_controller/... DEBUG XMPP::Topic: (am_controller) register handler for 'message' DEBUG XMPP::Communicator: publish >> am_controller SUCCEED DEBUG Auth::CertificateStore: Registering certificate for '{:uuid=>"...", :geni=>"omf"}' - /C=US/ST=CA/O=ACME/OU=Roadrunner/CN=xmpp://10.0.0.200@omf:netmode/type=am_controller/... DEBUG XMPP::Topic: (am_controller) Deliver message 'inform': ... DEBUG XMPP::Topic: (am_controller) Message type '[:inform, :message, :create_succeeded, :creation_ok]' (OmfCommon::Message::XML::Message:) DEBUG XMPP::Topic: (am_controller) Distributing message to '...' DEBUG XMPP::Topic: Existing topic: xmpp://[email protected] Populate the Database --------------------- A json file that describes the resources is required. This file can contain either a single resource or more than one resources in the form of an array. A sample file is as follows. The description of each resource is in the form of filling specific values to the predefined properties of each resources. The set of the properties of each resource is defined in its model: { "resources": { "name": "netmode1", "type": "uxv", "authority": "samant", "resource_description": { "resourceId": "UxV_NETMODE1", "hasInterface": [ { "name": "uav1:wlan0", "type": "wireless_interface", "authority": "samant", "resource_description": { "hasComponentName": "uav1:wlan0", "hasRole": "experimental" } }, { "name": "uav1:eth0", "type": "wired_interface", "authority": "samant", "resource_description": { "hasComponentName": "uav1:eth0", "hasRole": "experimental" } } ], "hasUxVType": "http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UaV/" } } } To populate the database with the resources: $ curl --cert user_cert.pem --key user_cert.pkey -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST -d @jsons/cr_uxv.json -k https://localhost:443/admin/create Now let's use the REST interface again to see the data we created: $ curl --cert user_cert.pem --key user_cert.pkey -i -H "Accept: application/json" -H "Content-Type:application/json" -X GET -d @jsons/get_inf.json -k https://localhost:443/admin/getinfo Testing REST API ---------------- The most enriched way to interact with SAM is through its REST API. Start with listing all available resources: $ curl --cert certs_p12/root.p12:pass -i -H 'Accept: application/json' -H 'Content-Type:application/json' -X GET -d @jsons/LR_options.json -k https://localhost:443/samant/listresources with LR_options.json containing { "options": { "only_available": true } } Please note the -k (or --insecure) option as we are using SSL but the server by default is not using a cert signed by a public CA. Using sfi.py ============ Get Version ----------- $ sfi.py version { 'geni_ad_rspec_versions': [ { 'extensions': [ 'http://nitlab.inf.uth.gr/schema/sfa/rspec/1/ad-reservation.xsd'], 'namespace': 'http://www.geni.net/resources/rspec/3', 'schema': 'http://www.geni.net/resources/rspec/3/ad.xsd', 'type': 'geni', 'version': '3'}], 'geni_api': 3, 'geni_api_versions': { '3': 'http://nitlab.inf.uth.gr:8001/RPC3'}, 'geni_credential_types': [{ 'geni_type': 'geni_sfa', 'geni_version': 3}], 'geni_request_rspec_versions': [ { 'extensions': [ 'http://nitlab.inf.uth.gr/schema/sfa/rspec/1/request-reservation.xsd'], 'namespace': 'http://www.geni.net/resources/rspec/3', 'schema': 'http://www.geni.net/resources/rspec/3/request.xsd', 'type': 'geni', 'version': '3'}], 'omf_am': '0.1'} List Resources -------------- sfi.py resources <?xml version="1.0"?> <rspec xmlns="http://www.geni.net/resources/rspec/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ol="http://nitlab.inf.uth.gr/schema/sfa/rspec/1" xmlns:omf="http://schema.mytestbed.net/sfa/rspec/1" type="advertisement" xsi:schemaLocation="http://www.geni.net/resources/rspec/3 http://www.geni.net/resources/rspec/3/ad.xsd http://nitlab.inf.uth.gr/schema/sfa/rspec/1 http://nitlab.inf.uth.gr/schema/sfa/rspec/1/ad-reservation.xsd" generated="2017-06-27T12:20:27+03:00" expires="2017-06-27T12:30:27+03:00"> <ol:lease id="f4996b30-956c-4e46-a8c0-187707311c1b" client_id="l1" sliver_id="urn:publicid:IDN+omf:netmode+sliver+f4996b30-956c-4e46-a8c0-187707311c1b" valid_from="2010-01-08T19:00:00Z" valid_until="2017-11-08T20:00:00Z"/> <node component_id="urn:publicid:IDN+omf:nitos.outdoor+node+node001" component_manager_id="urn:publicid:IDN+omf:netmode+authority+cm" component_name="node001" exclusive="true"> <available now="false"/> <hardware_type name="PC-Grid"/> <interface component_id="urn:publicid:IDN+omf:netmode+interface+node001:if0" component_name="node001:if0" role="control"> <ip address="10.0.1.1" type="ipv4" netmask="255.255.255.0"/> </interface> <interface component_id="urn:publicid:IDN+omf:netmode+interface+node001:if1" component_name="node001:if1" role="experimental"/> <ol:lease_ref id_ref="f4996b30-956c-4e46-a8c0-187707311c1b"/> <location latitude="39.360814" longitude="22.950075"/> <sliver_type name="miniPC1"> <disk_image name="Voyage-0.9.2" os="Ubuntu" version="3.10.11-voyage"/> </sliver_type> </node> <node component_id="urn:publicid:IDN+omf:nitos.outdoor+node+node001" component_manager_id="urn:publicid:IDN+omf:netmode+authority+cm" component_name="node0134" exclusive="true"> <available now="true"/> <hardware_type name="PC-Grid"/> <interface component_id="urn:publicid:IDN+omf:netmode+interface+node001:if0" component_name="node001:if0" role="control"> <ip address="10.0.1.1" type="ipv4" netmask="255.255.255.0"/> </interface> <interface component_id="urn:publicid:IDN+omf:netmode+interface+node001:if1" component_name="node001:if1" role="experimental"/> <location latitude="39.360814" longitude="22.950075"/> </node> </rspec> Debugging hints =============== Use the following command to show the content of a cert in a human readable form: $ openssl x509 -in ~/.gcf/alice-cert.pem -text To verify certificates, use openssl to set up a simple SSL server as well as connect to it. Server: % openssl s_server -cert ~/.gcf/am-cert.pem -key ~/.gcf/am-key.pem -verify on Client: % openssl s_client -cert ~/.gcf/alice-cert.pem -key ~/.gcf/alice-key.pem % openssl s_client -connect 127.0.0.1:8001 -key ~/.gcf/alice-key.pem -cert ~/.gcf/alice-cert.pem -CAfile ~/.gcf/trusted_roots/CATedCACerts.pem <file_sep>=begin print "Hello, World!\n" puts "Hello, Ruby!"; print <<EOF This is the first way of creating here document ie. multiple line string. EOF print <<"foo" # you can stack them I said foo. foo #I said bar. #bar =end class Customer @@no_of_customers=0 #class variable, cannot be uninitialized VAR = 200 #constant def initialize(id, name, addr) #local variables @@no_of_customers += 1 @cust_id=id #instance variable, nil when uninitialized @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() puts "Total number of customers: #@@no_of_customers" end end # Create Objects cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") =begin # Call Methods cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers() =end #array ary = ["fred", 10, 3.14, "This is a string", "last element",] ary.each do |i| #puts i end #hash hsh = colors = {"red" => 345, "green" => 0x0f0, "blue" => 0x00f} hsh.each do |key, value| #print key, " is ", value, "\n" end =begin #parallel assignment a, b, c = 10, 20, 30 puts a ,b, c a, b = b, c puts a ,b, c VAR = 100 CONST = proc {' in there'} puts ::VAR #If no prefix expression is used, the main Object class is used by default. puts Customer::VAR puts CONST.call =end CONST = ' out there' class Inside_one CONST = proc { ' in there' } def where_is_my_CONST ::CONST + ' inside one' end end class Inside_two CONST = ' inside two' def where_is_my_CONST CONST end end #puts Inside_one::CONST.call + Inside_two::CONST foo=42 #puts defined? Inside_one.new.where_is_my_CONST #if-elsif-else x=0 if x > 2 then #optional puts "x is greater than 2" elsif x <= 2 and x!=0 puts "x is 1" else puts "I can't guess the number" end #unless-else unless x>2 puts "x is less than 2" else puts "x is greater than 2" end #case $age = 6 case $age when 0 .. 2 puts "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end #while loop $i = 0 $num = 5 while $i < $num do #puts("Inside the loop i = #$i" ) $i +=1 end #8a ektelestei mia fora toulaxiston $i = 0 $num = 5 begin #puts("Inside the loop i = #$i" ) $i +=1 end while $i < $num #until loop $i = 0 $num = 5 until $i > $num do #puts("Inside the loop i = #$i" ) $i +=1; end #for -> doesnt create a new scope for local variables (sto telos to i 8a exei timi 5) i=7 for i in 0..5 puts "Value of local variable is #{i}" end #sto telos to b den uparxei (0..5).each do |b| puts "Value of local variable is #{b}" end #pws xrisimopoioume to rescue begin for i in 1..5 puts "Value of local variable is #{i}" raise if i > 2 end rescue #retry end def test(a1="Ruby", a2="Perl") #puts "The programming language is #{a1}" #puts "The programming language is #{a2}" return 42, "the sun" end var = test "C", "C++" #puts var def sample (*test) #variable parameters number #puts "The number of parameters is #{test.length}" for i in 0...test.length #puts "The parameters are #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA" class Accounts def reading_charge puts "kalispera" end def Accounts.return_date puts "gamiesai" end end acc = Accounts.new #acc.reading_charge #Accounts.return_date #acc.return_date cannot acces it like that. only in a static way #modules, omadopoioun sta8eres/sunartiseis/klaseis module Trig PI = 3.141592654 def Trig.sin(x) puts "sin" end def Trig.cos(x) puts "cos" end end one = Trig.cos(5) module Week FIRST_DAY = "Sunday" def weeks_in_month puts "You have four weeks in a month" end def Week.weeks_in_year puts "You have 52 weeks in a year" end end module Week2 FIRST_DAY = "Sunday" def weeks_in_month puts "You have 32 weeks in a month" end def Week.weeks_in_year puts "You have 52 weeks in a year" end end class Decade include Week2 include Week no_of_yrs=10 def no_of_months puts Week::FIRST_DAY number=10*12 puts number end end d1 = Decade.new puts Week::FIRST_DAY Week.weeks_in_year d1.no_of_months #SOS klironomikotita, an exoume cascade twn methodwn apo 2 diaforetika modules, kaleitai auto pou egine include teleutaio, edw "Week" d1.weeks_in_month x, y, z = 12, 36, 72 puts "The value of x is #{x}." puts "The sum of x and y is #{ x + y }." puts "The average was #{ (x + y + z)/3 }." a = ["a", "b", "c"] n = [65, "66", "67"] puts a.pack("A3A3A3") #=> "a b c " puts a.pack("a3a3a3") #=> "a\000\000b\000\000c\000\000" puts n.pack("ca2a1") #=> "A666" #me to yield kalw to block pou exei idio onoma me ti sunartisi (def) kai tis parametrous pou exei dipla tis pernaw se autes tou block def test yield 5 puts "You are in the method test" yield 100 end test { |ke| puts "You are in the block #{ke}" } #You can use any Ruby object as a key or value, even an array, so following example is a valid one months = Hash[d2 = Decade.new => 100, "month" => 200] puts "#{months[d2]}" puts "#{months['month']}" time1 = Time.new puts "Current Time : " + "#{time1.usec}" if (('a'..'j') === 'c') puts "c lies in ('a'..'j')" end #print "Enter a value :" #san print #val = gets #puts "#{val+"3"}" #san println puts File.readable?("test2.txt") # => true puts File.writable?("test2.txt") # => true puts File.executable?("test2.txt") # => false puts Dir.pwd # define a class class Box # constructor method def initialize(w, h) @width, @height = w, h end # instance method by default it is public def getArea getWidth() * getHeight end # define private accessor methods def getWidth @width end def getHeight @height end # make them private private :getWidth, :getHeight # instance method to print area def printArea @area = getWidth() * getHeight puts "Big box area is : #@area" end # make it protected protected :printArea end module Marios @i = 5 module Avgeris end end module Kwstas @b = 7 attr_accessor :b end module Marios::Avgeris::Alexandros @c = 3 end class Person attr_accessor :name end person = Person.new person.name = 'Dennis' puts person.name A = Class.new def A.speak "I'm class A" end puts A.speak #=> "I'm class A" puts A.singleton_methods #=> ["speak"] class A def self.c_method 'in A#c_method' end end puts A.singleton_methods class Person end puts Person.class #=> Class class Class def loud_name "#{name.upcase}!" end end puts Person.loud_name #=> "PERSON!" matz = Object.new def matz.speak "Place your burden to machine's shoulders" end puts matz.class #=> Object opts = Hash[:resource_uri => 12334, :account => Marios] puts opts[:resource_uri] class A def initialize() @res_handler = 5 end def retu return @res_handler.to_s end end b = A.new puts b.retu puts ["a", "b", "c"].join("-") module Alpha class Five def retu return adda(10) end end module B class Six def retu return 6 end end end end #puts Alpha::B::Six.new.retu module Alpha::B class Seven def retu return 7 end def adda(i) i=i+1 end end end module Alpha::Epsilos def kak #adda(3) 7 end end puts Alpha::B::Six.new.retu class Tempo AR = 5 def ret puts "#{AR}" end end Tempo.new.ret class Bines def test i = 100 j = 10 k = 0 end end if 5 puts Bines.new.test end print "1/2/3/4/5/6/7/8/9/0".split('/')[0..-2] puts puts ['sdf', 'sdff'] R = [1, 2, 3, 4, 5] R.map do |avga| puts (avga+1).to_s end puts 9 class Patates def initialize @@param = 1 end attr_accessor :account #TODO remove this when we enable authentication on both rest and xmpp [ # ACCOUNT :can_create_account?, # () :can_view_account?, # (account) :can_renew_account?, # (account, until) :can_close_account?, # (account) # RESOURCE :can_create_resource?, # (resource_descr, type) :can_modify_resource?, # (resource_descr, type) :can_view_resource?, # (resource) :can_release_resource?, # (resource) # LEASE :can_view_lease?, # (lease) :can_modify_lease?, # (lease) :can_release_lease?, # (lease) ].each do |m| define_method(m) do |*args| # Evaluates the given block in the context of the class/module. #debug "Check permission '#{m}' (#{@permissions.inspect})" unless @permissions[m] raise InsufficientPrivilegesException.new end true end end [1, 2, 3, 4] def tria @kolos = @@param + 1 puts @kolos end end #puts patates.new.account options = {:font_size => 10, :font_family => "Arial"} #options[self] = [1,2,34] ma = (options[self] ||= [1, 2, 34]) module Tempa def pros(i) @@declarations ||= {} m = (@@declarations[self] ||= []) m << i puts #puts m puts end def api_description() @@declarations ||= {} @@declarations[self] || [] end end module Tempb extend Tempa pros 9 pros 4 pros 8 end Tempb.api_description.each do |a| print a+1 end puts s1 = Set.new [1,2] s2 = Set.new [1,2,3,4,5] s3 = s2-s1 s4 = Set.new [3,4,5] puts s3 == s4 res_descr = {} res_descr[:name] = 4 puts res_descr[:name] class Parent attr_accessor :i end p1 = Parent.new p1.i = 5 p2 = p1 p2.i = 6 puts p1.i #puts Alpha::B::Five.new.retu #puts Alpha::Epsilos.kak k = [{:name=>"node1", :hostname=>"node1"}, {:name=>"node2", :hostname=>"node2"}] # pinakas apo hash k.each do |a| puts a[:name] end puts 5 require 'spira' require 'rdf/turtle' require 'sparql/client' #require 'sparql' require 'rdf/vocab' require_relative '../../omn-models/resource' #require_relative '../../omn-models/old_populator' account = Semantic::Account.for(:nil_account) # vres ton default account sparql = SPARQL::Client.new($repository) query = sparql.construct([:s, :p, account.uri]).where([:s, :p, account.uri]) query.each_statement do |s,p,o| query2 = sparql.construct([s, :p, :o]).where([s, :p, :o]) @output = RDF::Writer.for(:ntriples).buffer do |writer| writer << query2 #$repository end end puts @output <file_sep>require 'omf-sfa/am/am-rest/rest_handler' require 'omf-sfa/am/am-rest/resource_handler' require 'omf-sfa/am/am_manager' require 'uuid' require_relative '../../omn-models/resource.rb' require_relative '../../omn-models/populator.rb' require 'pathname' module OMF::SFA::AM::Rest class SamantReasoner < RestHandler def find_handler(path, opts) debug "!!!SAMANT reasoner!!!" RDF::Util::Logger.logger.parent.level = 'off' # Worst Bug *EVER* # debug "PATH = " + path.inspect # Define method called if path.map(&:downcase).include? "uxv-endurance" opts[:resource_uri] = :endurance elsif path.map(&:downcase).include? "uxv-distance" opts[:resource_uri] = :distance elsif path.map(&:downcase).include? "uxv" opts[:resource_uri] = :uxv else raise OMF::SFA::AM::Rest::BadRequestException.new "Invalid URL." end return self end # GET: # # @param method used to select which functionality is selected # @param [Hash] options of the request # @return [String] Description of the requested resource. def on_get (method, options) if method == :endurance endurance_distance(method.to_s, options) elsif method == :distance # distance(options) endurance_distance(method.to_s, options) elsif method == :uxv uxv(options) end end def endurance_distance(method, options) path = options[:req].env["REQUEST_PATH"] # Transform path to resources path_ary = Pathname(path).each_filename.to_a # TODO consider changing :resourceId to :hasID *generally* uxv = @am_manager.find_all_samant_resources(["Uxv"], {hasID: path_ary[path_ary.index{|item| item.downcase == "uxv-" + method} + 1]}) speed = path_ary[path_ary.index{|item| item.downcase == "speed"} + 1].to_i sensor_ary = path_ary[(path_ary.index{|item| item.downcase == "sensor"} + 1)] .split(",") .map {|sensorId| @am_manager.find_all_samant_resources(["SensingDevice"], {hasID: sensorId})} .flatten unless !path_ary.index{|item| item.downcase == "sensor"} sensor_ary = [] if sensor_ary == nil netIfc_ary = path_ary[(path_ary.index{|item| item.downcase == "netifc"} + 1)] .split(",") .map {|netifcId| @am_manager.find_all_samant_resources(["WiredInterface"], {hasID: netifcId}) + @am_manager.find_all_samant_resources(["WirelessInterface"], {hasID: netifcId})} .flatten unless !path_ary.index{|item| item.downcase == "netifc"} netIfc_ary = [] if netIfc_ary == nil # debug uxv.inspect + " " + speed.to_s + " " + sensor_ary.inspect + " " + netIfc_ary.inspect # Validate if uxv actually exists if uxv.empty? @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "UxV doesn't exist. Please use the List Resources call to check the available resources." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] else uxv = uxv.first end # Validate if speed is within limits if speed > uxv.hasTopSpeed.to_i @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "This UxV's top speed is :" + uxv.hasTopSpeed @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Validate if sensors and interfaces actually exist in given uxv debug "UxV subsystem " + uxv.hasSensorSystem.hasSubSystem.inspect unless (sensor_ary.map{|sensor| sensor.uri} - uxv.hasSensorSystem.hasSubSystem.map{|sensor| sensor.uri}).empty? && (netIfc_ary.map{|ifc| ifc.uri} - uxv.hasInterface.map{|ifc| ifc.uri}).empty? @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "Some or all of the given Sensors or Network Interfaces are not compatible with the given UxV. Please use the List Resources call to check the compatibility again." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end sensor_consumption = 0 netIfc_consumption = 0 sensor_ary.map { |sensor| sensor_consumption += sensor.consumesPower.to_i } debug "Total Sensors' consumption: " + sensor_consumption.to_s + "W" netIfc_ary.map { |netIfc| netIfc_consumption += netIfc.consumesPower.to_i } debug "Total Interfaces' consumption: " + netIfc_consumption.to_s + "W" consumption = uxv.consumesPower.to_i*(speed/uxv.hasAvgSpeed.to_i.to_f) + sensor_consumption + netIfc_consumption debug "Total UxV's consumption: " + consumption.to_s + "W" endurance = uxv.battery.to_i/consumption distance = endurance*speed # Compute the total time duration (in seconds) of a specific node travelling with the specified average speed / sensors / network interfaces, using the given model endurance = (endurance.round(2)*60).to_s + " minutes" debug "Endurance:" + endurance.to_s # Compute the total distance (in meters) that a specified node can cover, having the given average speed, using the given model and based on the node's battery life distance = (distance.round(2)).to_s + " km" debug "Distance:" + distance.to_s @return_struct[:code][:geni_code] = 0 @return_struct[:value] = eval(method) @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end def uxv(options) path = options[:req].env["REQUEST_PATH"] # Transform path to resources path_ary = Pathname(path).each_filename.to_a # TODO consider changing :resourceId to :hasID *generally* uxv = @am_manager.find_all_samant_resources(["Uxv"], {hasID: path_ary[path_ary.index{|item| item.downcase == "uxv"} + 1]}).first if path_ary.index{|item| item.downcase == "sensor"} res = uxv.hasSensorSystem.hasSubSystem.map{|sensor| sensor.observes.map{|phenomena| phenomena.uri.to_s.split("#").last.chop}}.flatten elsif path_ary.index{|item| item.downcase == "sensortype"} sensorType = path_ary[path_ary.index{|item| item.downcase == "sensortype"} + 1] res = uxv.hasSensorSystem.hasSubSystem.map{|sensor| sensor.observes.map{|phenomena| phenomena.uri.to_s.split("#").last.chop.downcase}}.flatten.include? sensorType.downcase elsif path_ary.index{|item| item.downcase == "netifc"} res = uxv.hasInterface.map{|ifc| ifc.hasInterfaceType}.compact elsif path_ary.index{|item| item.downcase == "netifctype"} netifcType = path_ary[path_ary.index{|item| item.downcase == "netifctype"} + 1] res = uxv.hasInterface.map{|ifc| ifc.hasInterfaceType.downcase }.compact.include? netifcType.downcase else @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "Unknown operation requested. Please try again." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = res @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end end end<file_sep>require 'rdf/do' require 'do_sqlite3' require_relative '../omn-models/resource.rb' require_relative '../omn-models/omn' require_relative '../omn-models/lifecycle' require_relative '../omn-models/wireless' # $repository = Spira.repository = RDF::Repository.new #$repository = Spira.repository = RDF::DataObjects::Repository.new uri: "sqlite3:test.db" require_relative '../samant_models/sensor.rb' require_relative '../samant_models/uxv.rb' =begin node1 = Semantic::Node.for(:node1) athens = Semantic::Location.for(:Athens) athens.x= 58.76 athens.y = 42.97 athens.save! ip1 = Semantic::IPAddress.for(:public_ip) ip1.address = "192.168.12.1" ip1.isIPAddressOf = node1 ip1.save! ip2 = Semantic::IPAddress.for(:private_ip) ip2.address = "192.168.12.123" ip2.isIPAddressOf = node1 ip2.save! link1 = Semantic::Link.for(:link1) link1.save! interface1 = Semantic::Interface.for(:interface1) interface1.isInterfaceOf = node1 interface1.macAddress = "5e-c1-56-d9-db-2a" interface1.save! interface2 = Semantic::Interface.for(:interface2) interface2.isInterfaceOf = node1 interface2.macAddress = "5e-c1-56-d9-db-2b" interface2.save! account1 = Semantic::Account.for(:nil_account) # STUD account1.credentials = Semantic::Credentials.for(:creds1, {:id => :usrd, :password => :<PASSWORD>}) account1.save! node1.hasInterface = [interface1, interface2] node1.isAvailable = true node1.isExclusive = true node1.hasIPAddress << ip1 node1.hasIPAddress << ip2 node1.hasLocation = athens node1.hasSliceID = "urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" node1.save! n2 = Semantic::Node.for("urn:publicid:IDN+omf:nitos.outdoor+node+node0012".to_sym) n2.hasLocation = athens n2.hasComponentID = RDF::URI.new("urn:publicid:IDN+omf:nitos.outdoor+node+node0012") n2.hasSliceID = "urn:publicid:IDN+omf:netmode+account+__default__" #"urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" n2.isAvailable = true n2.isExclusive = true n2.hasInterface << interface1 n2.save! ###################################################################################### mc1 = Semantic::MicroController.for(:NiosII) mc1.hasComponentID = RDF::URI.new('CPU/A/610') mc1.hasComponentName = "Altera Nios II 32-bit" mc1.save rsc1 = Semantic::Resource.for(:StratixGX) rsc1.hasID = "FPGA111" rsc1.creator = "Altera" rsc1.isVirtualized = true rsc1.hasComponent << mc1 rsc1.hasSliceID = "urn:publicid:IDN+omf:netmode+account+__default__" rsc1.save node1.parent = rsc1 node1.save! rsc2 = Semantic::Resource.for(:Arria10) rsc2.hasID = "FPG222" rsc2.creator = "Altera" rsc2.isVirtualized = false rsc2.hasSliceID = "urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" rsc2.save rsc3 = Semantic::Resource.for(:CycloneV) rsc3.hasID = "FPG333" rsc3.creator = "Altera" rsc3.isVirtualized = true rsc3.hasSliceID = "urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" rsc3.save grp1 = Semantic::Group.for(:GroupA) grp1.hasURI = RDF::URI.new('FPGA/B/00') grp1.hasResource << rsc1 grp1.hasResource << rsc2 grp1.save st3 = Semantic::State.for(:Active) st3.hasStateName = Semantic::Active.new st3.save st2 = Semantic::State.for(:Success) st2.hasStateName = Semantic::Success.new st2.hasNext = st3 st2.save st1 = Semantic::State.for(:Pending) st1.hasStateName = Semantic::Pending.new st1.hasNext = st2 st1.save # otan to vazeis etsi krataei mono to urn:uuid:2241fb1d-87a7-44b6-acf8-381f78549153 l1 = Semantic::Lease.for("urn:uuid:2241fb1d-87a7-44b6-acf8-381f78549153".to_sym) l1.hasID = "uuid:2241fb1d-87a7-44b6-acf8-381f78549153" l1.isReservationOf << node1 l1.hasState = st1 l1.startTime = "2015-12-11T20:00:00Z" l1.expirationTime = "2017-12-11T20:00:05Z" l1.hasSliceID = "urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" l1.save! # puts "!!!!!!! L1L1L1" + l1.to_uri.inspect l2 = Semantic::Lease.for(:lease2) l2.hasID = "lease2-efgh" l2.isReservationOf << node1 l2.startTime = "2015-12-11T20:00:00Z" l2.expirationTime = "2017-12-11T20:00:05Z" l2.hasState = st2 l2.hasSliceID = "urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test" l2.save =end #l3 = Semantic::Lease.for(:lease3) #l3.hasID = "lease2-efgh" #l3.isReservationOf << rsc1 #l3.hasState = st3 #l3.hasSliceID = "urn:publicid:IDN+omf:netmode+account+__default__" #l3.save<file_sep>require 'spira' module Semantic # Preload ontology DAO = RDF::Vocabulary.new("http://www.semanticdesktop.org/ontologies/2011/10/05/dao/#") # Digital.Me Account Ontology # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### class Account < Spira::Base configure :base_uri => DAO.Account type RDF::URI.new('http://www.semanticdesktop.org/ontologies/2011/10/05/dao/#Account') # Data Properties property :type, :predicate => DAO.accountType, :type => String # Object Properties property :credentials, :predicate => DAO.hasCredentials, :type => :Credentials end class Credentials < Spira::Base configure :base_uri => DAO.Credentials type RDF::URI.new('http://www.semanticdesktop.org/ontologies/2011/10/05/dao/#Credentials') # Data Properties property :password, :predicate => DAO.password, :type => String property :id, :predicate => DAO.userID, :type => String end end<file_sep>require 'rdf' require 'omf_common/lobject' require 'omf-sfa/am' require 'nokogiri' require 'active_support/inflector' # for classify method require_relative '../omn-models/resource' require_relative '../omn-models/account' require_relative '../samant_models/anyURItype' #require_relative '../omn-models/populator' #require_relative '../samant_models/sensor.rb' #require_relative '../samant_models/uxv.rb' module OMF::SFA::AM class AMManagerException < Exception; end class UnknownResourceException < AMManagerException; end class UnavailableResourceException < AMManagerException; end class UnknownAccountException < AMManagerException; end class FormatException < AMManagerException; end class ClosedAccountException < AMManagerException; end class InsufficientPrivilegesException < AMManagerException; end class UnavailablePropertiesException < AMManagerException; end class MissingImplementationException < Exception; end class UknownLeaseException < Exception; end # Namespace used for reservation information OL_NAMESPACE = "http://nitlab.inf.uth.gr/schema/sfa/rspec/1" OL_SEMANTICNS = "http://open-multinet.info/ontology/omn-lifecycle#hasLease" RES_SEMANTICNS = "http://open-multinet.info/ontology/omn#hasResource" OMNstartTime = "http://open-multinet.info/ontology/omn-lifecycle#startTime" OMNexpirationTime = "http://open-multinet.info/ontology/omn-lifecycle#expirationTime" OMNlease = "http://open-multinet.info/ontology/omn-lifecycle#Lease/" OMNcomponentID = "http://open-multinet.info/ontology/omn-lifecycle#hasComponentID" OMNcomponentName = "http://open-multinet.info/ontology/omn-lifecycle#hasComponentName" OMNID = "http://open-multinet.info/ontology/omn-lifecycle#hasID" W3type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" W3label = "http://www.w3.org/2000/01/rdf-schema#label" # The manager is where all the AM related policies and # resource management is concentrated. Testbeds with their own # ways of dealing with resources and components should only # need to extend this class. # class AMManager < OMF::Common::LObject attr_accessor :liaison # Create an instance of this manager # # @param [Scheduler] scheduler to use for creating new resource # def initialize(scheduler) @scheduler = scheduler end # It returns the default account, normally used for admin account. def _get_nil_account() @scheduler.get_nil_account() end def get_scheduler() @scheduler end ### MANAGEMENT INTERFACE: adding and removing from the AM's control # Register a resource to be managed by this AM. # # @param [OResource] resource to be managed by this manager # def manage_resource(resource) unless resource.is_a?(OMF::SFA::Model::Resource) raise "Resource '#{resource}' needs to be of type 'Resource', but is '#{resource.class}'" end resource.account_id = _get_nil_account.id resource.save resource end # Register an array of resources to be managed by this AM. # # @param [Array] array of resources # def manage_resources(resources) resources.map {|r| manage_resource(r) } end ### ACCOUNTS: creating, finding, and releasing accounts # Return the account described by +account_descr+. Create if it doesn't exist. # # @param [Hash] properties of account # @param [Authorizer] Defines context for authorization decisions # @return [Account] The requested account # @raise [UnknownResourceException] if requested account cannot be created # @raise [InsufficientPrivilegesException] if permission is not granted # def find_or_create_account(account_descr, authorizer) debug "find_or_create_account: '#{account_descr.inspect}'" begin account = find_account(account_descr, authorizer) return account rescue UnavailableResourceException # to raise tou exception exei ginei stin find_account => an den uparxei to account raise InsufficientPrivilegesException.new unless authorizer.can_create_account? # tsek an mporei na dimiourgisei account account = OMF::SFA::Model::Account.create(account_descr) # dimiourgise to, INSERT INTO ... # Ask the corresponding RC to create an account @liaison.create_account(account) end raise UnavailableResourceException.new "Cannot create '#{account_descr.inspect}'" unless account account end # Return the account described by +account_descr+. # # @param [Hash] properties of account # @param [Authorizer] Defines context for authorization decisions # @return [Account] The requested account # @raise [UnknownResourceException] if requested account cannot be found # @raise [InsufficientPrivilegesException] if permission is not granted # def find_account(account_descr, authorizer) unless account = OMF::SFA::Model::Account.first(account_descr) # tsek an uparxei raise UnavailableResourceException.new "Unknown account '#{account_descr.inspect}'" # to rescue ginetai se autin pou tin kalei end raise InsufficientPrivilegesException.new unless authorizer.can_view_account?(account) # tsek an mporei na ton dei account # epistrepse ton end # Return all accounts visible to the requesting user # # @param [Authorizer] Defines context for authorization decisions # @return [Array<Account>] The visible accounts (maybe empty) # def find_all_accounts(authorizer) accounts = OMF::SFA::Model::Account.exclude(:name => '__default__') # gurnaei array me ola ta accounts ektos apo to default accounts.map do |a| #san tin array.each, xreiazetai gia na ektelestei to query begin raise InsufficientPrivilegesException unless authorizer.can_view_account?(a) a rescue InsufficientPrivilegesException nil end end.compact end # Renew account described by +account_descr+ hash until +expiration_time+. # # @param [Hash] properties of account or account object # @param [Time] time until account should remain valid # @param [Authorizer] Defines context for authorization decisions # @return [Account] The requested account # @raise [UnknownResourceException] if requested account cannot be found # @raise [InsufficientPrivilegesException] if permission is not granted # def renew_account_until(account_descr, expiration_time, authorizer) if account_descr.is_a?(OMF::SFA::Model::Account) # an sto description exei do8ei account account = account_descr else account = find_account(account_descr, authorizer) end raise InsufficientPrivilegesException unless authorizer.can_renew_account?(account, expiration_time) debug " new expiration time = " + expiration_time.to_s account.open if account.closed? account.valid_until = expiration_time account.save debug " new valid until = " + account.valid_until.to_s # Ask the corresponding RC to create/re-open an account @liaison.create_account(account) account end # Close the account described by +account+ hash. # # Make sure that all associated components are freed as well # # @param [Hash] properties of account # @param [Authorizer] Defines context for authorization decisions # @return [Account] The closed account # @raise [UnknownResourceException] if requested account cannot be found # @raise [UnavailableResourceException] if requested account is closed # @raise [InsufficientPrivilegesException] if permission is not granted # def close_account(account_descr, authorizer) if account_descr.is_a?(OMF::SFA::Model::Account) account = account_descr else account = find_account(account_descr, authorizer) end raise InsufficientPrivilegesException unless authorizer.can_close_account?(account) #release_all_components_for_account(account, authorizer) release_all_leases_for_account(account, authorizer) account.close @liaison.close_account(account) account end def close_samant_account(slice_descr, authorizer) # TODO A LOT OF WORK ON THIS CONCEPT release_all_samant_leases_for_account(slice_descr, authorizer) end ### USERS # Return the user described by +user_descr+. Create if it doesn't exist. # Reset its keys if an array of ssh-keys is given # # Note: This is an unprivileged operation as creating a user doesn't imply anything # else beyond opening a record. # # @param [Hash] properties of user # @return [User] The requested user # @raise [UnknownResourceException] if requested user cannot be created # def find_or_create_user(user_descr, keys = nil) debug "find_or_create_user: '#{user_descr.inspect}'" begin user = find_user(user_descr) rescue UnavailableResourceException user = OMF::SFA::Model::User.create(user_descr) end unless keys.nil? user.keys.each { |k| k.destroy } keys.each do |k| key = OMF::SFA::Model::Key.create(ssh_key: k) user.add_key(key) # dhmiourgei ssh key kai to ana8etei ston user end end raise UnavailableResourceException.new "Cannot create '#{user_descr.inspect}'" unless user user.save user end # Return the user described by +user_descr+. # # @param [Hash] properties of user # @return [User] The requested user # @raise [UnknownResourceException] if requested user cannot be found # def find_user(user_descr) unless user = OMF::SFA::Model::User.first(user_descr) # epistrefei to prwto occurence tou user stin Sequel vasi raise UnavailableResourceException.new "Unknown user '#{user_descr.inspect}'" end user end ### LEASES: creating, finding, and releasing leases # Return the lease described by +lease_descr+. # # @param [Hash] properties of lease # @param [Authorizer] Defines context for authorization decisions # @return [Lease] The requested lease # @raise [UnknownResourceException] if requested lease cannot be found # @raise [InsufficientPrivilegesException] if permission is not granted # def find_lease(lease_descr, authorizer) debug "find lease: '#{lease_descr.inspect}'" unless lease = OMF::SFA::Model::Lease.first(lease_descr) #debug "edw eimai" + lease.inspect raise UnavailableResourceException.new "Unknown lease '#{lease_descr.inspect}'" # an to lease pou dimiourgeis den uparxei gyrnaei auto end raise InsufficientPrivilegesException unless authorizer.can_view_lease?(lease) # den kserw pou einai lease end def find_samant_lease(lease_uuid, authorizer) debug "find samant lease: '#{lease_uuid}'" lease_uri = RDF::URI.new("uuid:"+lease_uuid) sparql = SPARQL::Client.new($repository) unless sparql.ask.whether([lease_uri, :p, :o]).true? debug "Lease with uuid #{lease_uuid.inspect} doesn't exist." raise UnavailableResourceException.new "Unknown lease with uuid'#{lease_uuid.inspect}'" end raise InsufficientPrivilegesException unless authorizer.can_view_lease?(lease_uuid) lease = SAMANT::Lease.for(lease_uri) debug "Lease Exists with ID = " + lease.hasID.inspect return lease end # Return the lease described by +lease_descr+. Create if it doesn't exist. # # @param [Hash] lease_descr properties of lease # @param [Authorizer] Defines context for authorization decisions # @return [Lease] The requested lease # @raise [UnknownResourceException] if requested lease cannot be created # @raise [InsufficientPrivilegesException] if permission is not granted # def find_or_create_lease(lease_descr, authorizer) debug "find_or_create_lease: '#{lease_descr.inspect}'" begin return find_lease(lease_descr, authorizer) # an uparxei epistrepse to rescue UnavailableResourceException end raise InsufficientPrivilegesException unless authorizer.can_create_resource?(lease_descr, 'lease') # am_authorizer lease = OMF::SFA::Model::Lease.create(lease_descr) # alliws dimiourgise to raise UnavailableResourceException.new "Cannot create '#{lease_descr.inspect}'" unless lease @scheduler.add_lease_events_on_event_scheduler(lease) @scheduler.list_all_event_scheduler_jobs #debug messages only lease # lease = create_resource(lease_descr, 'Lease', lease_properties, authorizer) end def find_or_create_samant_lease(lease_uuid, lease_descr, authorizer) debug "find_or_create_samant_lease: '#{lease_descr.inspect}' " + " uuid: " + lease_uuid.inspect begin return find_samant_lease(lease_uuid, authorizer) rescue UnavailableResourceException end raise InsufficientPrivilegesException unless authorizer.can_create_resource?(lease_descr, 'lease') # to lease_descr den xrisimopoieitai # CREATE LEASE lease_uri = ("uuid:" + lease_uuid).to_sym lease = SAMANT::Lease.for(lease_uri, lease_descr) lease.save! debug "new lease = " + lease.inspect #debug "new lease startTime = " + lease.startTime.inspect #debug "new lease clientId = " + lease.clientID.inspect raise UnavailableResourceException.new "Cannot create '#{lease_descr.inspect}'" unless lease @scheduler.add_samant_lease_events_on_event_scheduler(lease) @scheduler.list_all_event_scheduler_jobs lease end # Find al leases if no +account+ and +status+ is given # # @param [Account] filter the leases by account # @param [Status] filter the leases by their status ['pending', 'accepted', 'active', 'past', 'cancelled'] # @param [Authorizer] Authorization context # @return [Lease] The requested leases # def find_all_leases(account = nil, status = ['pending', 'accepted', 'active', 'past', 'cancelled'], authorizer) debug "find_all_leases: account: #{account.inspect} status: #{status}" if account.nil? leases = OMF::SFA::Model::Lease.where(status: status) # gurnaei pinaka me ola ta leases pou antistoixoun sto (default) account else leases = OMF::SFA::Model::Lease.where(account_id: account.id, status: status) end leases.map do |l| begin raise InsufficientPrivilegesException unless authorizer.can_view_lease?(l) l rescue InsufficientPrivilegesException nil end end.compact end # !!!SAMANT PROJECT ADDITION!!! # # Find all leases if +account+ and +state+ is given # # @param [Account] filter the leases by account # @param [State] filter the leases by their status ['pending', 'accepted', 'active', 'past', 'cancelled'] # @param [Authorizer] Authorization context # @return [Lease] The requested leases # def find_all_samant_leases(slice_urn = nil, state, authorizer) debug "find_all_samant_leases: account: #{authorizer.account.inspect} status: #{state.inspect}" #debug "find_all_samant_leases: authorizer: #{authorizer.inspect} " debug "authorizer urn = " + authorizer.account[:urn].inspect unless authorizer.account.nil? if state.nil? state = [SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::UNALLOCATED, SAMANT::CANCELLED, SAMANT::PENDING] end if slice_urn.nil? if state.kind_of?(Array) leases = [] state.each { |istate| leases << SAMANT::Lease.find(:all, :conditions => {:hasReservationState => istate.to_uri}) } leases.flatten! else leases = SAMANT::Lease.find(:all, :conditions => {:hasReservationState => state.to_uri}) end else # debug "slice account_urn = " + account_urn[:urn].inspect # debug "slice authorizer.account[:urn] = " + authorizer.account[:urn].inspect # TODO probably no need to check the privileges here # raise InsufficientPrivilegesException unless slice_urn == authorizer.account[:urn] || authorizer.account[:urn] == "urn:publicid:IDN+omf:netmode+account+__default__" if state.kind_of?(Array) leases = [] state.each { |istate| leases << SAMANT::Lease.find(:all, :conditions => {:hasSliceID => slice_urn, :hasReservationState => istate.to_uri}) } leases.flatten! else leases = SAMANT::Lease.find(:all, :conditions => {:hasSliceID => slice_urn, :hasReservationState => state.to_uri}) end end debug authorizer.can_view_lease? leases.map do |l| # den paizei rolo to kathe lease pou pernaw san parametro, logika typiko begin raise InsufficientPrivilegesException unless authorizer.can_view_lease?(l) l rescue InsufficientPrivilegesException nil end end end def find_all_samant_leases_rpc(account_urn = nil, state = [SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::UNALLOCATED, SAMANT::CANCELLED, SAMANT::PENDING], authorizer) debug "find_all_samant_leases: account: #{authorizer.account.inspect} status: #{state.inspect}" # debug "find_all_samant_leases: authorizer: #{authorizer.inspect} " debug "authorizer urn = " + authorizer.account[:urn].inspect unless authorizer.account.nil? if account_urn.nil? if state.kind_of?(Array) leases = [] state.each { |istate| leases << SAMANT::Lease.find(:all, :conditions => {:hasReservationState => istate.to_uri}) } leases.flatten! else leases = SAMANT::Lease.find(:all, :conditions => {:hasReservationState => state.to_uri}) end else # debug "slice account_urn = " + account_urn[:urn].inspect # debug "slice authorizer.account[:urn] = " + authorizer.account[:urn].inspect # raise InsufficientPrivilegesException unless account_urn == authorizer.account[:urn] raise InsufficientPrivilegesException unless account_urn[:urn] == authorizer.account[:urn] if state.kind_of?(Array) leases = [] state.each { |istate| leases << SAMANT::Lease.find(:all, :conditions => {:hasSliceID => account_urn[:urn], :hasReservationState => istate.to_uri}) } leases.flatten! else leases = SAMANT::Lease.find(:all, :conditions => {:hasSliceID => account_urn[:urn], :hasReservationState => state.to_uri}) end end debug 'eftasa edo!!!! ' debug authorizer.can_view_lease? debug 'telos' leases.map do |l| # den paizei rolo to kathe lease pou pernaw san parametro, logika typiko begin raise InsufficientPrivilegesException unless authorizer.can_view_lease?(l) l rescue InsufficientPrivilegesException nil end end end # Modify lease described by +lease_descr+ hash # # @param [Hash] lease properties like ":valid_from" and ":valid_until" # @param [Lease] lease to modify # @param [Authorizer] Authorization context # @return [Lease] The requested lease # def modify_lease(lease_properties, lease, authorizer) raise InsufficientPrivilegesException unless authorizer.can_modify_lease?(lease) lease.update(lease_properties) # datamapper update, resource @scheduler.update_lease_events_on_event_scheduler(lease) lease end def modify_samant_lease(lease_properties, lease, authorizer) raise InsufficientPrivilegesException unless authorizer.can_modify_samant_lease?(lease) # debug "before update: " + lease.startTime.inspect lease.update_attributes(lease_properties) # debug "after update: " + lease.startTime.inspect @scheduler.update_samant_lease_events_on_event_scheduler(lease) lease #raise OMF::SFA::AM::Rest::BadRequestException.new "MODIFIER NOT YET IMPLEMENTED" end # cancel +lease+ # # This implementation simply frees the lease record # and destroys any child components if attached to the lease # # @param [Lease] lease to release # @param [Authorizer] Authorization context # def release_lease(lease, authorizer) debug "release_lease: lease:'#{lease.inspect}' authorizer:'#{authorizer.inspect}'" raise InsufficientPrivilegesException unless authorizer.can_release_lease?(lease) @scheduler.release_lease(lease) # destroy & diagrafi apo ton event scheduler end def release_samant_lease(lease, authorizer) debug "release_samant_lease: lease:'#{lease.inspect}' authorizer:'#{authorizer.inspect}'" raise InsufficientPrivilegesException unless authorizer.can_release_samant_lease?(lease) @scheduler.release_samant_lease(lease) # destroy & diagrafi apo ton event scheduler end # Release an array of leases. # # @param [Array<Lease>] Leases to release # @param [Authorizer] Authorization context def release_leases(leases, authorizer) leases.each do |l| release_lease(l, authorizer) end end def release_samant_leases(leases, authorizer) leases.each do |l| release_samant_lease(l, authorizer) end end # This method finds all the leases of the specific account and # releases them. # # @param [Account] Account who owns the leases # @param [Authorizer] Authorization context # def release_all_leases_for_account(account, authorizer) leases = find_all_leases(account, ['accepted', 'active'], authorizer) # ola ta leases tou do8entos account release_leases(leases, authorizer) end def release_all_samant_leases_for_account(slice_urn, authorizer) leases = find_all_samant_leases(slice_urn, [SAMANT::ALLOCATED, SAMANT::PROVISIONED], authorizer)# ola ta leases tou do8entos account #debug "@@@@@release all samant leases for account, leases to release = " + leases.inspect release_samant_leases(leases, authorizer) end ### RESOURCES creating, finding, and releasing resources # Find a resource. If it doesn't exist throws +UnknownResourceException+ # If it's not visible to requester throws +InsufficientPrivilegesException+ # # @param [Hash, Resource] describing properties of the requested resource # @param [String] The type of resource we are trying to find # @param [Authorizer] Defines context for authorization decisions # @return [Resource] The resource requested # @raise [UnknownResourceException] if no matching resource can be found # @raise [FormatException] if the resource description is not Hash # @raise [InsufficientPrivilegesException] if the resource is not visible to the requester # # def find_resource(resource_descr, resource_type, authorizer, semantic = false) # h perigrafi tou dinetai eite se hash eite se model resource debug "find_resource: descr: '#{resource_descr.inspect}'" #synithws mas ta xalaei sto account_id, den prepei na einai managed apo kapoio slice, prepei na einai managed apo ton aggregate manager debug resource_type # px Location #debug "semantic = " + semantic if resource_descr.kind_of? OMF::SFA::Model::Resource resource = resource_descr # trivial? elsif resource_descr.kind_of? Hash if semantic debug "semantic attribute find" # TODO 1.DOESNT WORK FOR DECIMAL ATTRIBUTE & 2. SEARCH VIA ID sparql = SPARQL::Client.new($repository) res = eval("Semantic::#{resource_type.camelize}").find(:all, :conditions => resource_descr).first return sparql.construct([res.uri, :p, :o]).where([res.uri, :p, :o]) else resource = eval("OMF::SFA::Model::#{resource_type.camelize}").first(resource_descr) # vres to prwto pou tairiazei stin perigrafi end else raise FormatException.new "Unknown resource description type '#{resource_descr.class}' (#{resource_descr})" end unless resource raise UnknownResourceException.new "Resource '#{resource_descr.inspect}' is not available or doesn't exist" end raise InsufficientPrivilegesException unless authorizer.can_view_resource?(resource) resource end def find_samant_resource(resource_descr, resource_type, authorizer) debug "find_samant_resource: descr: '#{resource_descr.inspect}' + resource type:" + resource_type.camelize if resource_descr.kind_of? Hash # ONLY UXVs can be leased resource = SAMANT::Uxv.find(:all, :conditions => resource_descr).first unless resource debug "There is no UxV with resource description: " + resource_descr.inspect raise UnknownResourceException.new "Resource '#{resource_descr.inspect}' is not available or doesn't exist" end debug "Resource = " + resource.inspect else raise FormatException.new "Unknown resource description type '#{resource_type}' (#{resource_descr})" end raise InsufficientPrivilegesException unless authorizer.can_view_resource?(resource) resource # raise OMF::SFA::AM::Rest::BadRequestException.new "find RESOURCES NOT YET IMPLEMENTED" end # Find all the resources that fit the description. If it doesn't exist throws +UnknownResourceException+ # If it's not visible to requester throws +InsufficientPrivilegesException+ # # @param [Hash] describing properties of the requested resource # @param [String] The type of resource we are trying to find # @param [Authorizer] Defines context for authorization decisions # @return [Resource] The resource requested # @raise [UnknownResourceException] if no matching resource can be found # @raise [FormatException] if the resource description is not Hash # @raise [InsufficientPrivilegesException] if the resource is not visible to the requester # # def find_all_resources(resource_descr, resource_type, authorizer, semantic = false) debug "find_resources: descr: '#{resource_descr.inspect}'" if resource_descr.kind_of? Hash # EXW PEIRAKSEI if semantic debug "semantic attribute find" # TODO 1.DOESNT WORK FOR DECIMAL ATTRIBUTE & 2. SEARCH VIA ID & sparql = SPARQL::Client.new($repository) res = eval("Semantic::#{resource_type.camelize}").find(:all, :conditions => resource_descr) resources = [] res.each { |r| resources << sparql.construct([r.uri, :p, :o]).where([r.uri, :p, :o]) } return resources ############ else resources = eval("OMF::SFA::Model::#{resource_type.classify}").where(resource_descr) end else raise FormatException.new "Unknown resource description type '#{resource_descr.class}' (#{resource_descr})" end raise UnknownResourceException.new "Resource '#{resource_descr.inspect}' is not available or doesn't exist" if resources.nil? || resources.empty? resources.map do |r| begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end.compact end # Find all components matching the resource description that are not leased for the given timeslot. # If it doesn't exist, or is not visible to requester # throws +UnknownResourceException+. # # @param [Hash] description of components # @param [String] The type of components we are trying to find # @param [String, Time] beggining of the timeslot # @param [String, Time] ending of the timeslot # @return [Array] All availlable components # @raise [UnknownResourceException] if no matching resource can be found # def find_all_available_components(component_descr = {}, component_type, valid_from, valid_until, authorizer) debug "find_all_available_components: descr: '#{component_descr.inspect}', from: '#{valid_from}', until: '#{valid_until}'" component_descr[:account_id] = _get_nil_account.id components = find_all_resources(component_descr, component_type, authorizer) # vres ta components components = components.select do |res| @scheduler.component_available?(res, valid_from, valid_until) # des an einai available end raise UnavailableResourceException if components.empty? components end # Find a number of components matching the resource description that are not leased for the given timeslot. # If it doesn't exist, or is not visible to requester # throws +UnknownResourceException+. # # @param [Hash] description of components # @param [String] The type of components we are trying to find # @param [String, Time] beggining of the timeslot # @param [String, Time] ending of the timeslot # @param [Array] array of component uuids that are not eligible to be returned by this function # @param [Integer] number of available components to be returned by this function # @return [Array] All availlable components # @raise [UnknownResourceException] if no matching resource can be found # def find_available_components(component_descr, component_type, valid_from, valid_until, non_valid_component_uuids = [], nof_requested_components = 1, authorizer) debug "find_all_available_components: descr: '#{component_descr.inspect}', from: '#{valid_from}', until: '#{valid_until}'" component_descr[:account_id] = _get_nil_account.id components = find_all_resources(component_descr, component_type, authorizer) components.shuffle! # this randomizes the result output = [] components.each do |comp| next if non_valid_component_uuids.include?(comp.uuid) output << comp if @scheduler.component_available?(comp, valid_from, valid_until) break if output.size >= nof_requested_components end raise UnavailableResourceException if output.size < nof_requested_components output end # Find all resources for a specific account. Return the managed resources # if no account is given # # @param [Account] Account for which to find all associated resources # @param [Authorizer] Defines context for authorization decisions # @return [Array<Resource>] The resource requested # def find_all_resources_for_account(account = nil, semantic = false, authorizer) debug "find_all_resources_for_account: #{account.inspect}" if semantic #res = Semantic::Resource.where({:address => "192.168.12.1"}).first.address#account_id: account.id) #construct query debug "i m in semantic!" account = Semantic::Account.for(:nil_account) if account.nil? # vres ton default account sparql = SPARQL::Client.new($repository) res = sparql.construct([:s, :p, account.uri]).where([:s, :p, account.uri]) # query pou gyrnaei ola ta nodes pou diaxeirizetai to nil account # TODO check priviledges!! else account = _get_nil_account if account.nil? # nill account id = 2 res = OMF::SFA::Model::Resource.where(account_id: account.id) # enas pinakas me ola ta resources tou sugkekrimenou id res.map do |r| begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end.compact end res end # Find all components for a specific account. Return the managed components # if no account is given # # @param [Account] Account for which to find all associated component # @param [Authorizer] Defines context for authorization decisions # @return [Array<Component>] The component requested # def find_all_components_for_account(account = _get_nil_account, authorizer) debug "find_all_components_for_account: #{account.inspect}" res = OMF::SFA::Model::Component.where(:account_id => account.id) res.map do |r| begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end.compact end # !!!SAMANT PROJECT ADDITION!!! # # Find all components for a specific account. Return the managed components # if no account is given # # @param [Account] Account for which to find all associated component # @param [Authorizer] Defines context for authorization decisions # @return [Array<Component>] The component requested # def find_all_samant_components_for_account(slice_urn = nil, authorizer) debug "find_all_samant_components_for_account: #{slice_urn}" debug "find_all_samant_components_for_account authorizer.account[:urn]: #{ authorizer.account[:urn]}" ifr = [] # interfaces snr = [] # sensors lct = [] # locations if slice_urn.nil? res = SAMANT::Uxv.find(:all) else # raise InsufficientPrivilegesException unless slice_urn == authorizer.account[:urn] || authorizer.account[:urn] == "urn:publicid:IDN+omf:netmode+account+__default__" res = SAMANT::Uxv.find(:all, :conditions => {:hasSliceID => slice_urn}) debug "returned resources: " + res.inspect end res.map do |r| # Check for Interfaces & Sensors & Locations (Used in Rspec) snr << r.hasSensorSystem unless snr.include?(r.hasSensorSystem) ifr << r.hasInterface unless ifr.include?(r.hasInterface) lct << r.where unless lct.include?(r.where) begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end #debug "@@@@@Interfaces: " + ifr.inspect #debug "@@@@@Sensors: " + snr.inspect #debug "@@@@@Locations: " + lct.inspect res << ifr << snr << lct res.flatten! end def find_all_samant_components_for_account_rpc(account_urn = nil, authorizer) debug "find_all_samant_components_for_account: #{account_urn}" # debug "find_all_samant_components_for_account authorizer.account[:urn]: #{authorizer.account[:urn]}" res = [] ifr = [] # interfaces snr = [] lct = [] if account_urn.nil? # if authorizer.account[:urn].nil? res << SAMANT::Uxv.find(:all) else # raise InsufficientPrivilegesException unless account_urn == authorizer.account[:urn] raise InsufficientPrivilegesException unless account_urn[:urn] == authorizer.account[:urn] res << SAMANT::Uxv.find(:all, :conditions => {:hasSliceID => authorizer.account[:urn]}) end res.flatten! res.map do |r| # Check for Interfaces & Sensors & Locations (Used in Rspec) snr << r.hasSensorSystem ifr << r.hasInterface lct << r.where begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end ifr.flatten! #debug "@@@@@Interfaces: " + ifr.inspect #debug "@@@@@Sensors: " + snr.inspect #debug "@@@@@Locations: " + lct.inspect res << ifr << lct res.flatten! end def find_all_samant_resources(category = nil, description) av_classes = SAMANT.constants.select {|c| SAMANT.const_get(c).is_a? Class} debug "Available Classes = " + av_classes.inspect resources = [] if category.nil? || category.empty? av_classes.each do |av_class| resources << eval("SAMANT::#{av_class}").find(:all, :conditions => description) end else category.each do |cat_class| cat_class = cat_class.classify unless av_classes.include?(cat_class.to_sym) raise UnavailableResourceException.new "Unknown Resource Category '#{cat_class.inspect}'. Please choose one of the following '#{av_classes.inspect}'" end resources << eval("SAMANT::#{cat_class}").find(:all, :conditions => description) end end debug "returned resources: " + resources.inspect resources.flatten! end # Find all components # # @param [Hash] Properties used for filtering the components # @param [Authorizer] Defines context for authorization decisions # @return [Array<Component>] The components requested # def find_all_components(comp_descr, authorizer) # san tin apo panw me diaforetiko orisma res = OMF::SFA::Model::Component.where(comp_descr) # filtrarismena ta components res.map do |r| begin raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r) r rescue InsufficientPrivilegesException nil end end.compact end # Find or Create a resource. If an account is given in the resource description # a child resource is created. Otherwise a managed resource is created. # # @param [Hash] Describing properties of the resource # @param [String] Type to create # @param [Authorizer] Defines context for authorization decisions # @return [Resource] The resource requested # @raise [UnknownResourceException] if no resource can be created # def find_or_create_resource(resource_descr, resource_type, authorizer) debug "find_or_create_resource: resource '#{resource_descr.inspect}' type: '#{resource_type}'" unless resource_descr.is_a? Hash raise FormatException.new "Unknown resource description '#{resource_descr.inspect}'" end begin return find_resource(resource_descr, resource_type, authorizer) rescue UnknownResourceException end create_resource(resource_descr, resource_type, authorizer) end def find_or_create_samant_resource(resource_descr, resource_type, authorizer) debug "find_or_create_samant_resource: resource '#{resource_descr.inspect}' type: '#{resource_type}'" unless resource_descr.is_a? Hash raise FormatException.new "Unknown resource description '#{resource_descr.inspect}'. Please provide a GURN." end #raise OMF::SFA::AM::Rest::BadRequestException.new "CREATE RESOURCES NOT YET IMPLEMENTED" begin # searching for nodes-children (leased nodes)! Only then has a node assigned a SliceID return find_samant_resource(resource_descr, resource_type, authorizer) rescue UnknownResourceException end create_samant_resource(resource_descr, resource_type, authorizer) end # Create a resource. If an account is given in the resource description # a child resource is created. The parent resource should be already present and managed # This will provide a copy of the actual physical resource. # Otherwise a managed resource is created which belongs to the 'nil_account' # # @param [Hash] Describing properties of the requested resource # @param [String] Type to create # @param [Authorizer] Defines context for authorization decisions # @return [Resource] The resource requested # @raise [UnknownResourceException] if no resource can be created # def create_resource(resource_descr, type_to_create, authorizer) raise InsufficientPrivilegesException unless authorizer.can_create_resource?(resource_descr, type_to_create) if resource_descr[:account_id].nil? # an den dinetai account kanto paidi tou admin account resource = eval("OMF::SFA::Model::#{type_to_create.classify}").create(resource_descr) resource = manage_resource(resource) else resource = @scheduler.create_child_resource(resource_descr, type_to_create) # ??? end raise UnknownResourceException.new "Resource '#{resource_descr.inspect}' cannot be created" unless resource resource end def create_samant_resource(resource_descr, resource_type, authorizer) debug "@create_samant_resource" raise InsufficientPrivilegesException unless authorizer.can_create_samant_resource?(resource_descr, resource_type) unless resource_descr[:hasSliceID] debug "@unless" resource = eval("SAMANT::#{resource_type}").for(resource_descr[:comp_id]) resource.hasSliceID = _get_nil_account.urn resource.save! else debug "@else" resource = @scheduler.create_samant_child_resource(resource_descr, resource_type) # ??? end raise UnknownResourceException.new "Resource '#{resource_descr.inspect}' cannot be created" unless resource resource #raise OMF::SFA::AM::Rest::BadRequestException.new "create RESOURCES NOT YET IMPLEMENTED" end # Find or create a resource for an account. If it doesn't exist, # is already assigned to someone else, or cannot be created, throws +UnknownResourceException+. # # @param [Hash] describing properties of the requested resource # @param [String] Type to create if not already exist # @param [Authorizer] Defines context for authorization decisions # @return [Resource] The resource requested # @raise [UnknownResourceException] if no matching resource can be found # def find_or_create_resource_for_account(resource_descr, type_to_create, authorizer) debug "find_or_create_resource_for_account: r_descr:'#{resource_descr}' type:'#{type_to_create}' authorizer:'#{authorizer.inspect}'" resource_descr[:account_id] = authorizer.account.id find_or_create_resource(resource_descr, type_to_create, authorizer) end def find_or_create_samant_resource_for_account(resource_descr, type_to_create, authorizer) #raise OMF::SFA::AM::Rest::BadRequestException.new "CREATE RESOURCES NOT YET IMPLEMENTED" debug "find_or_create_samant_resource_for_account: r_descr:'#{resource_descr}' type:'#{type_to_create}'" # authorizer:'#{authorizer.inspect}'" debug "slice id = " + authorizer.account.urn.inspect #debug "slice id = " + resource_descr[:urns].to_s #debug "MONO = " + resource_descr.to_s resource_descr[:hasSliceID] = authorizer.account.urn find_or_create_samant_resource(resource_descr, type_to_create, authorizer) end def create_resources_from_rspec(descr_el, clean_state, authorizer) # ??? paizei na min xrisimopoieitai debug "create_resources_from_rspec: descr_el: '#{descr_el}' clean_state: '#{clean_state}' authorizer: '#{authorizer}'" resources = descr_el.children.map do |child| # xml children n = OMF::SFA::Model::Component.create_from_rspec(child, resources, self) child.create_from_rspec(authorizer) end end # Release 'resource'. # # This implementation simply frees the resource record. # # @param [Resource] Resource to release # @param [Authorizer] Authorization context # @raise [InsufficientPrivilegesException] if the resource is not allowed to be released # def release_resource(resource, authorizer) debug "release_resource: '#{resource.inspect}'" raise InsufficientPrivilegesException unless authorizer.can_release_resource?(resource) @scheduler.release_resource(resource) # datamapper -> resource -> destroy end def release_samant_resource(resource, authorizer) debug "release_samant_resource: '#{resource.inspect}'" raise InsufficientPrivilegesException unless authorizer.can_release_samant_resource?(resource) @scheduler.release_samant_resource(resource) end # Release an array of resources. # # @param [Array<Resource>] Resources to release # @param [Authorizer] Authorization context def release_resources(resources, authorizer) resources.each do |r| release_resource(r, authorizer) end end def release_samant_resources(resources, authorizer) resources.each do |r| # release only samant uxvs release_samant_resource(r, authorizer) if ((r.kind_of?SAMANT::Uxv) || (r.kind_of? SAMANT::Lease)) end end # This method finds all the components of the specific account and # detaches them. # # @param [Account] Account who owns the components # @param [Authorizer] Authorization context # def release_all_components_for_account(account, authorizer) components = find_all_components_for_account(account, authorizer) release_resources(components, authorizer) end # Update the resources described in +resource_el+. Any resource not already assigned to the # requesting account will be added. If +clean_state+ is true, the state of all described resources # is set to the state described with all other properties set to their default values. Any resources # not mentioned are released. Returns the list # of resources requested or throw an error if ANY of the requested resources isn't available. # # Find or create a resource. If it doesn't exist, is already assigned to # someone else, or cannot be created, throws +UnknownResourceException+. # # @param [Element] RSpec fragment describing resource and their properties # @param [Boolean] Set all properties not mentioned to their defaults # @param [Authorizer] Defines context for authorization decisions # @return [OResource] The resource requested # @raise [UnknownResourceException] if no matching resource can be found # @raise [FormatException] if RSpec elements are not known # # @note Throws exception if a contained resource doesn't exist, but will not roll back any # already performed modifications performed on other resources. # def update_resources_from_rspec(descr_el, clean_state, authorizer) debug "update_resources_from_rspec: descr_el:'#{descr_el}' clean_state:'#{clean_state}' authorizer:'#{authorizer}'" if !descr_el.nil? && descr_el.name.downcase == 'rspec' xsd_path = File.join(File.dirname(__FILE__), '../../../schema/rspec-v3', 'request.xsd') schema = Nokogiri::XML::Schema(File.open(xsd_path)) #TODO: make sure we pass the schema validation #res = schema.validate(descr_el.document) #raise FormatException.new("RSpec format is not valid: '#{res}'") unless res.empty? unless descr_el.xpath('//ol:*', 'ol' => OL_NAMESPACE).empty? #TODO: make proper schemas and validate them #lease_xsd_path = File.join(File.dirname(__FILE__), '../../../schema/rspec-v3', 'request-reservation.xsd') #lease_rng_path = File.join(File.dirname(__FILE__), '../../../schema/rspec-v3', 'request-reservation.rng') #lease_schema = Nokogiri::XML::Schema(File.open(lease_xsd_path)) #lease_schema = Nokogiri::XML::RelaxNG(File.open(lease_rng_path)) #TODO: make sure we pass the schema validation #res = schema.validate(descr_el.document) #raise FormatException.new("RSpec format is not valid: '#{res}'") unless res.empty? end if descr_el.namespaces.values.include?(OL_NAMESPACE) # OL_NAMESPACE = "http://nitlab.inf.uth.gr/schema/sfa/rspec/1" leases = descr_el.xpath('//ol:lease', 'ol' => OL_NAMESPACE) # leases = descr_el.xpath('/xmlns:rspec/ol:lease', 'ol' => OL_NAMESPACE, 'xmlns' => "http://www.geni.net/resources/rspec/3") leases = update_leases_from_rspec(leases, authorizer) else leases = {} end resources = leases.values # hash to array nodes = descr_el.xpath('//xmlns:node').collect do |el| #debug "create_resources_from_xml::EL: #{el.inspect}" if el.kind_of?(Nokogiri::XML::Element) # ignore any text elements #if el[:lease_name].nil? # update_resource_from_rspec(el, nil, clean_state, authorizer) #else # This node has a lease # lease = leases.find { |l| l[:name].eql?(el[:lease_name]) } #leases = el.xpath('child::ol:lease', 'ol' => OL_NAMESPACE) #leases = update_leases_from_rspec(leases, authorizer) update_resource_from_rspec(el, leases, clean_state, authorizer) #end end end.compact resources = resources.concat(nodes) #(prwta leases, meta nodes) # channel reservation channels = descr_el.xpath('/xmlns:rspec/ol:channel', 'ol' => OL_NAMESPACE, 'xmlns' => "http://www.geni.net/resources/rspec/3").collect do |el| update_resource_from_rspec(el, leases, clean_state, authorizer) end.compact resources = resources.concat(channels) # meta channels # if resources.include?(false) # a component failed to be leased because of scheduler lease_component returned false # resources.delete(false) # release_resources(resources, authorizer) # raise UnavailableResourceException.new "One or more resources failed to be allocated" # end failed_resources = [] resources.each do |res| failed_resources << res if res.kind_of? Hash end unless failed_resources.empty? resources.delete_if {|item| failed_resources.include?(item)} urns = [] failed_resources.each do |fres| puts release_resource(fres[:failed], authorizer) urns << fres[:failed].urn end release_resources(resources, authorizer) raise UnavailableResourceException.new "The resources with the following URNs: '#{urns.inspect}' failed to be allocated" end # TODO: release the unused leases. The leases we have created but we never managed # to attach them to a resource because the scheduler denied it. if clean_state # Now free any leases owned by this account but not contained in +leases+ # all_leases = Set.new(leases.values) #leases = descr_el.xpath('//ol:lease', 'ol' => OL_NAMESPACE).collect do |l| # update_leases_from_rspec(leases, authorizer) #end.compact # leases.each_value {|l| l.all_resources(all_leases)} all_leases = find_all_leases(authorizer.account, authorizer) leases_values = leases.values # ena hash pou dimiourgithike apo ta leases pou eginan update apo rspec, to array unused = all_leases.delete_if do |l| # Deletes every element of +self+ for which block evaluates to +true+. out = leases_values.select {|res| res.id == l.id} # ston out vale auta pou uparxoun sto lease_values !out.empty? # delete_if an den einai adeios o pinakas out pou proekupse (an uparxei estw ena diladi gia to opoio isxuei h isotita) end # unused = find_all_leases(authorizer.account, authorizer).to_set - all_leases unused.each do |u| release_lease(u, authorizer) end # Now free any resources owned by this account but not contained in +resources+ # rspec_resources = Set.new(resources) # resources.each {|r| r.all_resources(rspec_resources)} all_components = find_all_components_for_account(authorizer.account, authorizer) unused = all_components.delete_if do |comp| out = resources.select {|res| res.id == comp.id} !out.empty? end release_resources(unused, authorizer) end return resources else raise FormatException.new "Unknown resources description root '#{descr_el}'" end end # !!!SAMANT PROJECT ADDITION!!! def update_samant_resources_from_rspec(descr_el, clean_state, authorizer) debug "SAMANT update_resources_from_rspec: descr_el:'#{descr_el}' clean_state:'#{clean_state}'" #authorizer:'#{authorizer}'" if !descr_el.nil? if descr_el.key?(:leases) leases_el = descr_el[:leases] # TODO currently supports only one lease per request leases_el = [leases_el.first] debug "EXEI Leases: " + leases_el.inspect leases = update_samant_leases_from_rspec(leases_el, authorizer) else debug "DEN EXEI EXEI EXEI Leases: " leases = [] end debug "leases contain: " + leases.inspect resources = leases nodes = [] if descr_el.key?(:nodes) node_els = descr_el[:nodes] debug "The following UxVs found: " + node_els.inspect node_els.each { |node_el| nodes << update_samant_resource_from_rspec(node_el, resources, clean_state, authorizer) # at this stage resources == leases } else nodes end debug "Returned UxVs contain: " + nodes.compact.inspect # compact removes nil values resources = resources.concat(nodes.compact) debug "accumulated contain: " + resources.inspect failed_resources = [] resources.each do |res| failed_resources << res if res.kind_of? Hash # ta failarismena einai { failed => resource } end # Remove nil resources # TODO this shouldn't be a case resources.delete_if {|res| res.nil? } debug "failed resources = " + failed_resources.inspect unless failed_resources.empty? # delete_if - delete elements that don't match from current array and return the array resources.delete_if {|item| debug "checking resource for failed: " + item.inspect failed_resources.include?(item) } # debug "New Resources = " + resources.inspect urns = [] failed_resources.each do |fres| release_samant_resource(fres[:failed], authorizer) urns << fres[:failed].hasParent.to_uri.to_s end # TODO 1.check an prepei na gyrisw nil, 2.prepei na kanw raise to unavailable exception? # Allocate is an all or nothing request: if the aggregate cannot completely satisfy the request RSpec, it should fail the request entirely. debug "Release conflicting resources." release_samant_resources(resources, authorizer) #return resources raise UnavailableResourceException.new "The resources with the following URNs: '#{urns.inspect}' failed to be allocated. Request dropped." end # Now free any leases owned by this account but not contained in +leases+ if clean_state debug "@@@@CLEAN STATE" # all_leases = find_all_samant_leases(authorizer.account.urn, nil, authorizer) # array all_leases = find_all_samant_leases(authorizer.account.urn,[SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::PENDING] , authorizer) # array debug "all leases = " + all_leases.inspect unused = all_leases.delete_if do |l| out = leases.select {|res| res.uri == l.uri} !out.empty? end debug "unused leases: " + unused.inspect unused.each do |u| release_samant_lease(u, authorizer) end # Now free any resources owned by this account but not contained in +resources+ all_components = find_all_samant_components_for_account(authorizer.account.urn, authorizer) # Remove nil components TODO: fix error all_components.delete_if do |comp| comp.nil? end unused = all_components.delete_if do |comp| out = resources.select {|res| res.uri == comp.uri} !out.empty? end release_samant_resources(unused, authorizer) end return resources else raise FormatException.new "Unknown resources description root '#{descr_el}'" end # raise OMF::SFA::AM::Rest::BadRequestException.new "UPDATE RESOURCES NOT YET IMPLEMENTED" end # Update a single resource described in +resource_el+. The respective account is # extracted from +opts+. Any mentioned resources not already available to the requesting account # will be created. If +clean_state+ is set to true, all state of a resource not specifically described # will be reset to it's default value. Returns the resource updated. # def update_resource_from_rspec(resource_el, leases, clean_state, authorizer) # channels kai nodes, oxi leases if uuid_attr = (resource_el.attributes['uuid'] || resource_el.attributes['id']) uuid = UUIDTools::UUID.parse(uuid_attr.value) resource = find_resource({:uuid => uuid}, authorizer) # wouldn't know what to create elsif comp_id_attr = resource_el.attributes['component_id'] comp_id = comp_id_attr.value comp_gurn = OMF::SFA::Model::GURN.parse(comp_id) # get rid of "urn:publicid:IDN" #if uuid = comp_gurn.uuid # resource_descr = {:uuid => uuid} #else # resource_descr = {:name => comp_gurn.short_name} #end resource_descr = {:urn => comp_gurn.to_s} resource = find_or_create_resource_for_account(resource_descr, comp_gurn.type, authorizer) unless resource raise UnknownResourceException.new "Resource '#{resource_el.to_s}' is not available or doesn't exist" end elsif name_attr = resource_el.attributes['component_name'] # the only resource we can find by a name attribute is a group # TODO: Not sure about the 'group' assumption name = name_attr.value resource = find_or_create_resource_for_account({:name => name}, 'unknown', {}, authorizer) else raise FormatException.new "Unknown resource description '#{resource_el.attributes.inspect}" end resource.client_id = resource_el['client_id'] resource.save leases_el = resource_el.xpath('child::ol:lease_ref|child::ol:lease', 'ol' => OL_NAMESPACE) leases_el.each do |lease_el| #TODO: provide the scheduler with the resource and the lease to attach them according to its policy. # if the scheduler refuses to attach the lease to the resource, we should release both of them. # start by catching the exceptions of @scheduler lease_id = lease_el['id_ref'] || lease_el['client_id'] lease = leases[lease_id] unless lease.nil? || lease.components.include?(resource) # lease.components.first(:uuid => resource.uuid) return {failed: resource} unless @scheduler.lease_component(lease, resource) monitoring_el = resource_el.xpath('//xmlns:monitoring') unless monitoring_el.empty? oml_url = monitoring_el.first.xpath('//xmlns:oml_server').first['url'] @liaison.start_resource_monitoring(resource, lease, oml_url) end end end # if resource.group? # members = resource_el.children.collect do |el| # if el.kind_of?(Nokogiri::XML::Element) # # ignore any text elements # update_resource_from_rspec(el, clean_state, authorizer) # end # end.compact # debug "update_resource_from_rspec: Creating members '#{members}' for group '#{resource}'" # if clean_state # resource.members = members # else # resource.add_members(members) # end # else # if clean_state # # Set state to what's described in +resource_el+ ONLY # resource.create_from_xml(resource_el, authorizer) # else # resource.update_from_xml(resource_el, authorizer) # end # end sliver_type_el = resource_el.xpath('//xmlns:sliver_type') unless sliver_type_el.empty? sliver_type = OMF::SFA::Model::SliverType.first({name: sliver_type_el.first['name']}) resource.sliver_type = sliver_type # models -> node end resource.save resource rescue UnknownResourceException error "Ignoring Unknown Resource: #{resource_el}" nil end def update_samant_resource_from_rspec(resource_el, leases, clean_state, authorizer) debug "Resource Element = " + resource_el.inspect resource_descr = {} # Search chain: uuid/id -> component_id -> component_name, (uuid rarely/never used though) if uuid_attr = (resource_el[:uuid] || resource_el[:id]) # rarely used probably cut out # TODO RECONSIDER: NOT EVEN USED IN ORIGINAL OMF_SFA debug "UUID exists: " + uuid_attr.inspect + ", but do nothing." elsif comp_id = resource_el[:component_id] # most cases comp_gurn = OMF::SFA::Model::GURN.parse(comp_id) classtype = comp_gurn.type.to_s.upcase # TODO RECONSIDER: plain string as range for hasComponentID resource_descr[:hasComponentID] = Spira::Types::AnyURI.serialize(comp_gurn.to_s) # resource_descr[:hasUxVType] = comp_gurn.type.to_s.upcase # TODO use when triplestore populated accordingly debug "classtype = " + classtype resource = find_or_create_samant_resource_for_account(resource_descr, classtype, authorizer) unless resource raise UnknownResourceException.new "Resource '#{resource_el.to_s}' is not available or doesn't exist" end elsif comp_name = resource_el[:component_name] resource_descr = {:hasComponentName => comp_name} resource = find_or_create_samant_resource_for_account(resource_descr, nil, authorizer) else raise FormatException.new "Unknown resource description" end debug "AM I THE CHILD? " + resource.uri.to_s # NAI EINAI # TODO maybe assign the client_ID to child lease_id = resource_el[:lease_ref] debug "Lease ref = " + lease_id lease = leases.select {|lease| lease.clientID == lease_id}.first debug "Lease selected = " + lease.inspect unless lease.nil? return {failed: resource} unless @scheduler.lease_samant_component(lease, resource) end resource.save resource rescue UnknownResourceException error "Ignoring Unknown Resource: #{resource_el}" nil end # Update the leases described in +leases+. Any lease not already assigned to the # requesting account will be added. If +clean_state+ is true, the state of all described leases # is set to the state described with all other properties set to their default values. Any leases # not mentioned are canceled. Returns the list # of leases requested or throw an error if ANY of the requested leases isn't available. # # @param [Element] RSpec fragment describing leases and their properties # @param [Authorizer] Defines context for authorization decisions # @return [Hash{String => Lease}] The leases requested # @raise [UnknownResourceException] if no matching lease can be found # @raise [FormatException] if RSpec elements are not known # def update_leases_from_rspec(leases, authorizer) debug "update_leases_from_rspec: leases:'#{leases.inspect}' authorizer:'#{authorizer.inspect}'" leases_hash = {} unless leases.empty? leases.each do |lease| l = update_lease_from_rspec(lease, authorizer) leases_hash.merge!(l) end end leases_hash end def update_samant_leases_from_rspec(leases, authorizer) debug "update_samant_leases_from_rspec: leases:'#{leases.inspect}'" # authorizer:'#{authorizer.inspect}'" leases_arry = [] unless leases.empty? leases.each do |lease| l = update_samant_lease_from_rspec(lease, authorizer) leases_arry << l end end debug "leases array: " + leases_arry.inspect leases_arry end # Create or Modify leases through RSpecs # # When a UUID is provided, then the corresponding lease is modified. Otherwise a new # lease is created with the properties described in the RSpecs. # # @param [Nokogiri::XML::Node] RSpec fragment describing lease and its properties # @param [Authorizer] Defines context for authorization decisions # @return [Lease] The requested lease # @raise [UnavailableResourceException] if no matching resource can be found or created # @raise [FormatException] if RSpec elements are not known # def update_lease_from_rspec(lease_el, authorizer) if (lease_el[:valid_from].nil? || lease_el[:valid_until].nil?) raise UnavailablePropertiesException.new "Cannot create lease without ':valid_from' and 'valid_until' properties" end lease_properties = {:valid_from => Time.parse(lease_el[:valid_from]).utc, :valid_until => Time.parse(lease_el[:valid_until]).utc} begin # an uparxei raise UnavailableResourceException unless UUID.validate(lease_el[:id]) # mporei na min yparxei kan to lease id (synithws den yparxei) lease = find_lease({:uuid => lease_el[:id]}, authorizer) # vres to me uuid if lease.valid_from != lease_properties[:valid_from] || lease.valid_until != lease_properties[:valid_until] # update sti diarkeia lease = modify_lease(lease_properties, lease, authorizer) return { lease_el[:id] => lease } else return { lease_el[:id] => lease } end rescue UnavailableResourceException # an den uparxei, ftiaxto lease_descr = {account_id: authorizer.account.id, valid_from: lease_el[:valid_from], valid_until: lease_el[:valid_until]} lease = find_or_create_lease(lease_descr, authorizer) lease.client_id = lease_el[:client_id] lease.save return { (lease_el[:client_id] || lease_el[:id]) => lease } end end def update_samant_lease_from_rspec(lease_el, authorizer) # Check for errors if (lease_el[:valid_from].nil? || lease_el[:valid_until].nil?) raise UnavailablePropertiesException.new "Cannot create lease without ':valid_from' and 'valid_until' properties" else begin lease_properties = {:startTime => Time.parse(lease_el[:valid_from]).utc, :expirationTime => Time.parse(lease_el[:valid_until]).utc} debug "Lease time properties: " + lease_properties.inspect if (Time.now >= lease_properties[:expirationTime]) || lease_properties[:startTime] >= lease_properties[:expirationTime] raise ArgumentError end rescue ArgumentError raise UnavailablePropertiesException.new "Cannot create lease with given time/date (invalid) properties." end end begin raise UnavailableResourceException unless UUID.validate(lease_el[:id]) # NOT GIVEN EVERYTIME lease = find_samant_lease(lease_el[:id], authorizer) if lease.startTime != lease_properties[:startTime] || lease.expirationTime != lease_properties[:expirationTime] debug "found with different properties!" lease = modify_samant_lease(lease_properties, lease, authorizer) return lease else debug "found with same properties!" return lease end rescue UnavailableResourceException lease_uuid = SecureRandom.uuid # Create some random valid uuid for the newcoming lease lease_descr = {:hasSliceID => authorizer.account[:urn], :startTime => Time.parse(lease_el[:valid_from]), :expirationTime => Time.parse(lease_el[:valid_until]), :hasID => lease_uuid, :clientID => lease_el[:client_id]} debug "Lease Doesn't Exist. Create with Descr: " + lease_descr.inspect + " uuid: " + lease_uuid.inspect #raise OMF::SFA::AM::UnavailableResourceException.new 'BREAKPOINT' lease = find_or_create_samant_lease(lease_uuid, lease_descr, authorizer) return lease # raise OMF::SFA::AM::Rest::BadRequestException.new "UPDATE LEASES NOT YET IMPLEMENTED" end end def renew_samant_lease(lease, leased_components, authorizer, new_expiration_time) debug "Checking Lease (prior): " + lease.expirationTime.inspect unless new_expiration_time > lease.expirationTime raise OMF::SFA::AM::UnavailableResourceException.new "New Expiration Time cannot be prior to former Expiration Time." end old_lease_properties = {:startTime => lease.startTime, :expirationTime => lease.expirationTime} new_lease_properties = {:startTime => lease.startTime, :expirationTime => new_expiration_time} # check only during the difference lease.startTime = lease.expirationTime + 1.second lease.expirationTime = new_expiration_time debug "Checking Lease (updated): from " + lease.startTime.inspect + " to " + lease.expirationTime.inspect renewal_success = true leased_components.each do |component| unless @scheduler.lease_samant_component(lease, component) debug "One Fail!" renewal_success = false break end end debug "Checking Lease (updated): " + lease.expirationTime.inspect unless renewal_success modify_samant_lease(old_lease_properties, lease, authorizer) debug "Checking Lease (cancelling): " + lease.expirationTime.inspect raise OMF::SFA::AM::UnavailableResourceException.new "Could not renew sliver due to unavailability of resources during that time." end modify_samant_lease(new_lease_properties, lease, authorizer) # also updates the event scheduler end end # class end # OMF::SFA::AM <file_sep>require 'omf-sfa/models/component' require 'omf-sfa/models/cmc' require 'omf-sfa/models/sliver_type' module OMF::SFA::Model class Node < Component one_to_many :interfaces one_to_many :cpus one_to_many :usb_devices many_to_one :cmc many_to_one :location many_to_one :sliver_type plugin :nested_attributes nested_attributes :interfaces, :cpus, :cmc, :location, :sliver_type, :usb_devices sfa_class 'node' sfa :client_id, :attribute => true sfa :sliver_id, :attribute => true sfa :hardware_type, :attr_value => 'name' sfa :availability, :attr_value => 'now', :attr_name => 'available' # <available now="true"> sfa :sliver_type, :inline => true sfa :interfaces, :inline => true, :has_many => true sfa :exclusive, :attribute => true sfa :location, :inline => true sfa :boot_state, :attribute => true sfa :monitored, :attribute => true sfa :services sfa :monitoring def services return nil if self.account.id == OMF::SFA::Model::Account.where(name: '__default__').first.id gateway = self.parent.gateway el = "<login authentication=\"ssh-keys\" hostname=\"#{gateway}\" port=\"22\" username=\"#{self.account.name}\"/>" Nokogiri::XML(el).child end def availability self.available_now? end attr_accessor :monitoring def monitoring return nil unless @monitoring el = "<oml_info oml_url=\"#{@monitoring[:oml_url]}\" domain=\"#{@monitoring[:domain]}\">" Nokogiri::XML(el).child end def sliver_id return nil if self.parent.nil? return nil if self.leases.nil? || self.leases.empty? self.leases.first.urn end def before_save self.available = true if self.available.nil? super end def self.exclude_from_json sup = super [:sliver_type_id, :cmc_id, :location_id].concat(sup) end def self.include_nested_attributes_to_json sup = super [:interfaces, :cpus, :cmc, :location, :sliver_type, :leases, :usb_devices].concat(sup) end def self.can_be_managed? true end end end <file_sep>require 'data_objects' require 'rdf/do' require 'do_sqlite3' $repository = Spira.repository = RDF::DataObjects::Repository.new uri: "sqlite3:./test.db" require_relative '../samant_models/sensor.rb' require_relative '../samant_models/uxv.rb' # Repopulate triplestore RDF::Util::Logger.logger.parent.level = 'off' auv1MultiSensor = SAMANT::System.for("urn:auv+multi+sensor".to_sym) auv1MultiSensor.save point11 = SAMANT::Point.for("urn:point11".to_sym) point11.pos = "45.256 -71.92" point11.save point21 = SAMANT::Point.for("urn:point21".to_sym) point21.pos = "55.356 31.92" point21.save point31 = SAMANT::Point.for("urn:point31".to_sym) point31.pos = "-65.356 41.92" point31.save uav1Point3D = SAMANT::Point3D.for("urn:uav+point3D".to_sym) uav1Point3D.lat = 55.701 uav1Point3D.long = 12.552 uav1Point3D.alt = 34.556 uav1Point3D.save ugv1Point3D = SAMANT::Point3D.for("urn:ugv+point3D".to_sym) ugv1Point3D.lat = 30.701 ugv1Point3D.long = 23.552 ugv1Point3D.alt = 65.556 ugv1Point3D.save auv1Point3D = SAMANT::Point3D.for("urn:auv+point3D".to_sym) auv1Point3D.lat = 21.701 auv1Point3D.long = 93.552 auv1Point3D.alt = 85.556 auv1Point3D.save uavLinearRing = SAMANT::LinearRing.for("urn:uav+linear+ring".to_sym) uavLinearRing.posList << "45.256 -110.45" uavLinearRing.posList << "46.46 -109.48" uavLinearRing.posList << "43.84 -109.86" uavLinearRing.posList << "45.256 -110.45" uavLinearRing.save ugvLinearRing = SAMANT::LinearRing.for("urn:ugv+linear+ring".to_sym) ugvLinearRing.posList << "43.256 110.45" ugvLinearRing.posList << "43.46 109.48" ugvLinearRing.posList << "44.84 109.86" ugvLinearRing.posList << "43.256 110.45" ugvLinearRing.save auvLinearRing = SAMANT::LinearRing.for("urn:ugv+linear+ring".to_sym) auvLinearRing.posList << "-42.256 110.45" auvLinearRing.posList << "-42.46 109.48" auvLinearRing.posList << "-42.84 109.86" auvLinearRing.posList << "-42.256 110.45" auvLinearRing.save uavPolygon = SAMANT::Polygon.for("urn:uav+polygon".to_sym) uavPolygon.exterior = uavLinearRing uavPolygon.save ugvPolygon = SAMANT::Polygon.for("urn:ugv+polygon".to_sym) ugvPolygon.exterior = ugvLinearRing ugvPolygon.save auvPolygon = SAMANT::Polygon.for("urn:auv+polygon".to_sym) auvPolygon.exterior = auvLinearRing auvPolygon.save dimitrisSettings = SAMANT::UserSettings.for("urn:dimitris+user+settings".to_sym) dimitrisSettings.hasUserRole = SAMANT::AUTHORITYUSER dimitrisSettings.hasPreferences = "preferences1" dimitrisSettings.isUpdated = "2015-11-11 03:00:00" dimitrisSettings.save nikosSettings = SAMANT::UserSettings.for("urn:nikos+user+settings".to_sym) nikosSettings.hasUserRole = SAMANT::EXPERIMENTER nikosSettings.hasPreferences = "preferences2" nikosSettings.isUpdated = "2013-11-11 03:00:00" nikosSettings.save mariosSettings = SAMANT::UserSettings.for("urn:marios+user+settings".to_sym) mariosSettings.hasUserRole = SAMANT::TESTBEDMANAGER mariosSettings.hasPreferences = "preferences3" mariosSettings.isUpdated = "2012-11-11 03:00:00" mariosSettings.save uavHealthInformation = SAMANT::HealthInformation.for("urn:uav+health+information+test".to_sym) uavHealthInformation.hasGeneralHealthStatus = SAMANT::GENERALOK uavHealthInformation.isUpdated = "2016-11-11 04:00:00" uavHealthInformation.save ugvHealthInformation = SAMANT::HealthInformation.for("urn:ugv+health+information+test".to_sym) ugvHealthInformation.hasGeneralHealthStatus = SAMANT::GENERALCRITICAL ugvHealthInformation.isUpdated = "2017-10-10 04:00:00" ugvHealthInformation.save auvHealthInformation = SAMANT::HealthInformation.for("urn:auv+health+information+test".to_sym) auvHealthInformation.hasGeneralHealthStatus = SAMANT::GENERALWARNING auvHealthInformation.isUpdated = "2015-9-9 04:00:00" auvHealthInformation.save uavTestbed = SAMANT::Testbed.for("urn:UaV+testbed".to_sym) uavTestbed.hasHealthStatus = SAMANT::OK uavTestbed.hasHealthInformation = uavHealthInformation uavTestbed.where = point11 uavTestbed.where = uavPolygon uavTestbed.hasName = "UaVTestbed" uavTestbed.hasStatusMessage = "functional" uavTestbed.hasDescription = "descr1" uavTestbed.hasTestbedID = "UaV24455" uavTestbed.hasUavSupport = true uavTestbed.hasUgvSupport = false uavTestbed.hasUsvSupport = false uavTestbed.save ugvTestbed = SAMANT::Testbed.for("urn:UgV+testbed".to_sym) ugvTestbed.hasHealthStatus = SAMANT::WARNING ugvTestbed.hasHealthInformation = ugvHealthInformation ugvTestbed.where = point21 ugvTestbed.where = uavPolygon ugvTestbed.hasName = "UgVTestbed" ugvTestbed.hasStatusMessage = "alert" ugvTestbed.hasDescription = "descr2" ugvTestbed.hasTestbedID = "UgV28980" ugvTestbed.hasUavSupport = false ugvTestbed.hasUgvSupport = true ugvTestbed.hasUsvSupport = false ugvTestbed.save auvTestbed = SAMANT::Testbed.for("urn:AuV+testbed".to_sym) auvTestbed.hasHealthStatus = SAMANT::WARNING auvTestbed.hasHealthInformation = auvHealthInformation auvTestbed.where = point31 auvTestbed.where = auvPolygon auvTestbed.hasName = "AuVTestbed" auvTestbed.hasStatusMessage = "hehe" auvTestbed.hasDescription = "descr3" auvTestbed.hasTestbedID = "AuV39050" auvTestbed.hasUavSupport = false auvTestbed.hasUgvSupport = false auvTestbed.hasUsvSupport = true auvTestbed.save uav1ExpResConf = SAMANT::ExperimentResourceConfig.for("urn:uav1+exp+resource+config".to_sym) uav1ExpResConf.hasExperimentResourceConfigID = "UaV1ExpResConfID" uav1ExpResConf.hasExperimentResourceConfigParamValue = 4.5 uav1ExpResConf.save ugv1ExpResConf = SAMANT::ExperimentResourceConfig.for("urn:ugv1+exp+resource+config".to_sym) ugv1ExpResConf.hasExperimentResourceConfigID = "UgV1ExpResConfID" ugv1ExpResConf.hasExperimentResourceConfigParamValue = 10.5 ugv1ExpResConf.save auv1ExpResConf = SAMANT::ExperimentResourceConfig.for("urn:auv1+exp+resource+config".to_sym) auv1ExpResConf.hasExperimentResourceConfigID = "AuV1ExpResConfID" auv1ExpResConf.hasExperimentResourceConfigParamValue = 13.5 auv1ExpResConf.save uav1ConfigParameters = SAMANT::ConfigParameters.for("urn:uav1+config+parameters+test".to_sym) uav1ConfigParameters.hasExperimentResourceConfig = uav1ExpResConf uav1ConfigParameters.hasName = "UaV1ConfigParameters" uav1ConfigParameters.hasDescription = "descr-a" uav1ConfigParameters.hasConfigParametersID = "UaV1ConfParamID" uav1ConfigParameters.hasConfigParametersMinValue = 3.0 uav1ConfigParameters.hasConfigParametersMaxValue = 4.0 # uav1ConfigParameters.resourceId = "UaV1Id" uav1ConfigParameters.save ugv1ConfigParameters = SAMANT::ConfigParameters.for("urn:ugv1+config+parameters+test".to_sym) ugv1ConfigParameters.hasExperimentResourceConfig = ugv1ExpResConf ugv1ConfigParameters.hasName = "UgV1ConfigParameters" ugv1ConfigParameters.hasDescription = "descr-b" ugv1ConfigParameters.hasConfigParametersID = "UgV1ConfParamID" ugv1ConfigParameters.hasConfigParametersMinValue = 2.0 ugv1ConfigParameters.hasConfigParametersMaxValue = 5.0 # ugv1ConfigParameters.resourceId = "UgV1Id" ugv1ConfigParameters.save auv1ConfigParameters = SAMANT::ConfigParameters.for("urn:auv1+config+parameters+test".to_sym) auv1ConfigParameters.hasExperimentResourceConfig = auv1ExpResConf auv1ConfigParameters.hasName = "Auv1ConfigParameters" auv1ConfigParameters.hasDescription = "descr-c" auv1ConfigParameters.hasConfigParametersID = "AuV1ConfParamID" auv1ConfigParameters.hasConfigParametersMinValue = 1.0 auv1ConfigParameters.hasConfigParametersMaxValue = 6.0 # auv1ConfigParameters.resourceId = "AuV1Id" auv1ConfigParameters.save uav1Lease = SAMANT::Lease.for("urn:uav1+lease+test".to_sym) uav1Lease.hasReservationState = SAMANT::UNALLOCATED uav1Lease.startTime = Time.parse("2016-04-01 23:00:00 +0300") uav1Lease.expirationTime = Time.parse("2017-03-15 23:00:00 +0300") uav1Lease.hasID = "UaV1LeaseID" uav1Lease.save ugv1Lease = SAMANT::Lease.for("urn:ugv1+lease+test".to_sym) ugv1Lease.hasReservationState = SAMANT::ALLOCATED ugv1Lease.startTime = Time.parse("2016-05-02 23:00:00 +0300") ugv1Lease.expirationTime = Time.parse("2017-04-16 23:00:00 +0300") ugv1Lease.hasID = "UgV1LeaseID" ugv1Lease.save auv1Lease = SAMANT::Lease.for("urn:auv1+lease+test".to_sym) auv1Lease.hasReservationState = SAMANT::PROVISIONED auv1Lease.startTime = Time.parse("2016-06-03 23:00:00 +0300") auv1Lease.expirationTime = Time.parse("2017-05-17 23:00:00 +0300") auv1Lease.hasID = "AuV1LeaseID" auv1Lease.save uav1HealthInformation = SAMANT::HealthInformation.for("urn:uav1+health+information+test".to_sym) uav1HealthInformation.hasGeneralHealthStatus = SAMANT::GENERALOK uav1HealthInformation.isUpdated = "2016-12-12 04:00:00" uav1HealthInformation.save ugv1HealthInformation = SAMANT::HealthInformation.for("urn:ugv1+health+information+test".to_sym) ugv1HealthInformation.hasGeneralHealthStatus = SAMANT::GENERALUNKNOWN ugv1HealthInformation.isUpdated = "2017-12-12 04:00:00" ugv1HealthInformation.save auv1HealthInformation = SAMANT::HealthInformation.for("urn:auv1+health+information+test".to_sym) auv1HealthInformation.hasGeneralHealthStatus = SAMANT::GENERALWARNING auv1HealthInformation.isUpdated = "2015-12-12 04:00:00" auv1HealthInformation.save ifr1 = SAMANT::WiredInterface.for("urn:uuid:interface+1+wired+uav1:eth0".to_sym) ifr1.hasComponentID = "urn:uuid:interface+1+wired+uav1:eth0" ifr1.hasComponentName = "uav1:eth0" ifr1.hasRole = "experimental" ifr2 = SAMANT::WirelessInterface.for("urn:uuid:interface+2+wireless+ugv1:bt0".to_sym) ifr2.hasComponentID = "urn:uuid:interface+2+wireless+ugv1:bt0" ifr2.hasComponentName = "ugv1:bt0" ifr2.hasRole = "experimental" ifr3 = SAMANT::WirelessInterface.for("urn:uuid:interface+3+wireless+auv1:ble0".to_sym) ifr3.hasComponentID = "urn:uuid:interface+3+wireless+auv1:ble0" ifr3.hasComponentName = "auv1:ble0" ifr3.hasRole = "experimental" uav1 = SAMANT::Uxv.for("urn:UaV1".to_sym) uav1.hasHealthStatus = SAMANT::SHUTDOWN uav1.isResourceOf = uavTestbed uav1.hasResourceStatus = SAMANT::BOOKED uav1.where << uav1Point3D uav1.hasConfigParameters = uav1ConfigParameters uav1.hasHealthInformation = uav1HealthInformation uav1.hasUxVType = SAMANT::UAV uav1.hasSensorSystem = auv1MultiSensor uav1.hasLease << uav1Lease uav1.resourceId = "UaV1_FLEXUS" uav1.hasName = "UaV1" uav1.hasStatusMessage = "UaVsaysHello" uav1.hasDescription = "abcd" uav1.hasInterface << ifr1 ifr1.isInterfaceOf = uav1 ifr1.save # add sensors to UxV uaV1MultiSensor_list = SAMANT::System.find(:all, :conditions => { :hasID => "UaV1MS345"} ) uaV1MultiSensor = uaV1MultiSensor_list[0] uav1.hasSensorSystem = uaV1MultiSensor uav1.save uavTestbed.hasResource << uav1 uavTestbed.save ugv1 = SAMANT::Uxv.for("urn:UgV1".to_sym) ugv1.hasHealthStatus = SAMANT::OK ugv1.isResourceOf = ugvTestbed ugv1.hasResourceStatus = SAMANT::SLEEPMODE ugv1.where << ugv1Point3D ugv1.hasConfigParameters = ugv1ConfigParameters ugv1.hasHealthInformation = ugv1HealthInformation ugv1.hasUxVType = SAMANT::UGV ugv1.hasSensorSystem = auv1MultiSensor ugv1.hasLease << ugv1Lease ugv1.resourceId = "UgV1_VENAC" ugv1.hasName = "UgV1" ugv1.hasStatusMessage = "UgVsaysHello" ugv1.hasDescription = "abcde" ugv1.hasInterface << ifr2 ifr2.isInterfaceOf = ugv1 ifr2.save # add sensors to UxV ugv1MultiSensor_list = SAMANT::System.find(:all, :conditions => { :hasID => "UgV1MS345"} ) ugv1MultiSensor = ugv1MultiSensor_list[0] ugv1.hasSensorSystem = ugv1MultiSensor ugv1.save ugvTestbed.hasResource << ugv1 ugvTestbed.save auv1 = SAMANT::Uxv.for("urn:AuV1".to_sym) auv1.hasHealthStatus = SAMANT::WARNING auv1.isResourceOf = auvTestbed auv1.hasResourceStatus = SAMANT::RELEASED auv1.where << auv1Point3D auv1.hasConfigParameters = auv1ConfigParameters auv1.hasHealthInformation = auv1HealthInformation auv1.hasUxVType = SAMANT::AUV auv1.hasSensorSystem = auv1MultiSensor auv1.hasLease << auv1Lease auv1.resourceId = "AuV1_ALTUS" auv1.hasName = "AuV1" auv1.hasStatusMessage = "AuVsaysHello" auv1.hasDescription = "abcdef" auv1.hasInterface << ifr3 ifr3.isInterfaceOf = auv1 ifr3.save # add sensors to UxV auv1MultiSensor_list = SAMANT::System.find(:all, :conditions => { :hasID => "UaV1MS345"} ) auv1MultiSensor = auv1MultiSensor_list[0] auv1.hasSensorSystem = auv1MultiSensor auv1.save auvTestbed.hasResource << auv1 auvTestbed.save dimitris = SAMANT::Person.for("urn:ddechouniotis".to_sym) dimitris.hasUserSettings = dimitrisSettings dimitris.usesTestbed = uavTestbed dimitris.hasEmail = "<EMAIL>" dimitris.hasFirstName = "Dimitris" dimitris.hasSurname = "Dechouniotis" dimitris.hasPassword = "<PASSWORD>" dimitris.hasUserName = "dimitris" dimitris.hasUserID = "userid1" dimitris.isSuperUser = false dimitris.lastLogin = "2016-11-11 03:00:00" dimitris.save nikos = SAMANT::Person.for("urn:nkalatzis".to_sym) nikos.hasUserSettings = nikosSettings nikos.usesTestbed = ugvTestbed nikos.hasEmail = "<EMAIL>" nikos.hasFirstName = "Nikos" nikos.hasSurname = "Kalatzis" nikos.hasPassword = "<PASSWORD>" nikos.hasUserName = "nikos" nikos.hasUserID = "userid2" nikos.isSuperUser = false nikos.lastLogin = "2016-12-12 03:00:00" nikos.save marios = SAMANT::Person.for("urn:mavgeris".to_sym) marios.hasUserSettings = mariosSettings marios.usesTestbed = auvTestbed marios.hasEmail = "<EMAIL>" marios.hasFirstName = "Marios" marios.hasSurname = "Avgeris" marios.hasPassword = "<PASSWORD>" marios.hasUserName = "nikos" marios.hasUserID = "userid3" marios.isSuperUser = true marios.lastLogin = "2016-10-10 03:00:00" marios.save<file_sep>require 'omf-sfa/am/am-rest/rest_handler' require 'omf-sfa/am/am-rest/resource_handler' require 'omf-sfa/am/am_manager' require 'uuid' require_relative '../../omn-models/resource.rb' require_relative '../../omn-models/populator.rb' #require 'data_objects' #require 'rdf/do' #require 'do_sqlite3' #$repository = Spira.repository = RDF::DataObjects::Repository.new uri: "sqlite3:./test.db" #require_relative '../../samant_models/sensor.rb' #require_relative '../../samant_models/uxv.rb' module OMF::SFA::AM::Rest # Assume PENDING = pending, ALLOCATED = accepted, PROVISIONED = active, RPC compatibility mappings $acceptable_lease_states = [SAMANT::ALLOCATED, SAMANT::PROVISIONED, SAMANT::PENDING] class SamantHandler < RestHandler def find_handler(path, opts) debug "!!!SAMANT handler!!!" RDF::Util::Logger.logger.parent.level = 'off' # Worst Bug *EVER* # debug "PATH = " + path.inspect # Define method called if path.map(&:downcase).include? "getversion" opts[:resource_uri] = :getversion elsif path.map(&:downcase).include? "listresources" opts[:resource_uri] = :listresources elsif path.map(&:downcase).include? "describe" opts[:resource_uri] = :describe elsif path.map(&:downcase).include? "status" opts[:resource_uri] = :status elsif path.map(&:downcase).include? "allocate" opts[:resource_uri] = :allocate elsif path.map(&:downcase).include? "renew" opts[:resource_uri] = :renew elsif path.map(&:downcase).include? "provision" opts[:resource_uri] = :provision elsif path.map(&:downcase).include? "delete" opts[:resource_uri] = :delete elsif path.map(&:downcase).include? "shutdown" opts[:resource_uri] = :shutdown else raise OMF::SFA::AM::Rest::BadRequestException.new "Invalid URL." end return self end # GET: # # @param method used to select which functionality is selected # @param [Hash] options of the request # @return [String] Description of the requested resource. def on_get (method, options) if method == :getversion get_version elsif method == :listresources list_resources(options) elsif method == :describe d_scribe(options) elsif method == :status status(options) end end # POST: # # @param function used to select which functionality is selected # @param [Hash] options of the request # @return [String] Description of the requested resource. def on_post (method, options) if method == :allocate allocate(options) elsif method == :provision provision(options) end end def on_put(method,options) if method == :renew renew(options) end end def on_delete (method, options) if method == :delete delete(options) elsif method == :shutdown shutdown(options) end end # GetVersion: # Return the version of the GENI Aggregate API # supported by this aggregate. def get_version() # TODO Nothing implemented yet for GetVersion call raise OMF::SFA::AM::Rest::BadRequestException.new "getversion NOT YET IMPLEMENTED" end # ListResources: # Return information about available resources # or resources allocated to a slice. def list_resources(options) #debug "options = " + options.inspect body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect debug 'ListResources: Options: ', params.inspect only_available = params[:only_available] slice_urn = params[:slice_urn] authorizer = options[:req].session[:authorizer] # debug "!!!authorizer = " + authorizer.inspect debug "!!!USER = " + authorizer.user.inspect debug "!!!ACCOUNT = " + authorizer.account.inspect # debug "!!!ACCOUNT_URN = " + authorizer.account[:urn] # debug "!!!ACCOUNT = " + authorizer.user.accounts.first.inspect if slice_urn @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = "Geni version 3 no longer supports arguement 'geni_slice_urn' for list resources method, please use describe instead." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] else resources = @am_manager.find_all_samant_leases(nil, $acceptable_lease_states, authorizer) comps = @am_manager.find_all_samant_components_for_account(nil, authorizer) # child nodes should not be included in listresources comps.delete_if {|c| ((c.nil?)||(c.to_uri.to_s.include?"/leased"))} if only_available debug "only_available selected" # TODO maybe delete also interfaces and locations as well comps.delete_if {|c| (c.kind_of?SAMANT::Uxv) && c.hasResourceStatus && (c.hasResourceStatus.to_uri == SAMANT::BOOKED.to_uri) } end resources.concat(comps) #debug "the resources: " + resources.inspect # TODO uncomment to obtain rspeck, commented out because it's very time-wasting #used_for_side_effect = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Offering) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) start = Time.now debug "START CREATING JSON" res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) # -> returns the json formatted results (more detailed, omn enriched) debug "END CREATING JSON. total time = " + (Time.now-start).to_s end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = res @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Describe: # Return information about resources allocated to *one* slice or *many* slivers belonging to *one_slice*. def d_scribe(options) body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect urns = params[:urns] debug 'Describe: URNS: ', urns.inspect, ' Options: ', params.inspect credentials = body[:credentials] if urns.nil? || urns.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Argument 'urns' is either empty or nil." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # SLICE == ACCOUNT / SLIVER == LEASE # Must provide full slice URN, e.g /urn:publicid:IDN+omf:netmode+account+__default__ slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end authorizer = options[:req].session[:authorizer] raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first # debug authorizer.inspect resources = [] leases = [] if slivers_only urns.each do |urn| l = @am_manager.find_samant_lease(urn, authorizer) # TODO maybe check thoroughly if slice_urn of slivers is the same as the authenticated user's resources << l leases << l l.isReservationOf.each do |comp| resources << comp if comp.hasSliceID == authorizer.account[:urn] end end else resources = @am_manager.find_all_samant_leases(slice_urn, $acceptable_lease_states, authorizer) leases = resources.dup components = @am_manager.find_all_samant_components_for_account(slice_urn, authorizer) #components.collect! { |r| (r.kind_of?SAMANT::Uxv) && r.hasParent ? r.hasParent : r } # Replace child nodes with parent nodes resources.concat(components) end # TODO uncomment to obtain rspeck, commented out because it's very time-wasting # used_for_side_effect = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Offering) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) # -> returns the json formatted results (more detailed, omn enriched) value = {} value[:omn_rspec] = res value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| tmp = {} tmp[:geni_sliver_urn] = lease.to_uri.to_s tmp[:geni_expires] = lease.expirationTime.to_s tmp[:geni_allocation_status] = if lease.hasReservationState.uri == SAMANT::ALLOCATED.uri then "geni_allocated" elsif lease.hasReservationState.uri == SAMANT::PROVISIONED.uri then "geni_provisioned" else "geni_unallocated" end tmp[:geni_operational_status] = "NO_INFO" # lease.isReservationOf.hasResourceStatus.to_s # TODO Match geni_operational_status with an ontology concept value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Allocate: # Allocate resources as described in a request RSpec argument to a slice with the # named URN. On success, one or more slivers are allocated, containing resources # satisfying the request, and assigned to the given slice. Allocated slivers are # held for an aggregate-determined period. def allocate(options) body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect urns = params[:urns] rspec = body[:rspec] credentials = body[:credentials] debug 'Allocate: URNs: ', urns, ' RSPEC: ', rspec, ' Options: ', params.inspect, "time: ", Time.now if urns.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "The following arguments is missing: 'urns'" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end if urns.kind_of? String tmp = urns urns = [] urns << tmp end slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end authorizer = options[:req].session[:authorizer] # raise OMF::SFA::AM::InsufficientPrivilegesException.new unless authorizer.account[:urn] == urns.first raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first resources = @am_manager.update_samant_resources_from_rspec(rspec, true, authorizer) debug "returned resources = " + resources.inspect leases_only = true resources.each do |res| if !res.kind_of? SAMANT::Lease #debug "what am i looking? " + res.inspect leases_only = false break end end debug "Leases only? " + leases_only.to_s if resources.nil? || resources.empty? || leases_only debug('Allocate failed', ":all the requested resources were unavailable for the requested DateTime.") unless resources.nil? || resources.empty? resources.each do |res| # TODO logika to check tou PENDING xreiazetai stin periptwsi kata tin opoia to lease proupirxe @am_manager.get_scheduler.delete_samant_lease(res) # if res.hasReservationState == SAMANT::PENDING end end @return_struct[:code][:geni_code] = 7 # operation refused @return_struct[:output] = "all the requested resources were unavailable for the requested DateTime." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # TODO uncomment to obtain rspeck, commented out because it's very time-wasting #used_for_side_effect = OMF::SFA::AM::Rest::ResourceHandler.rspecker(resources, :Manifest) # -> creates the advertisement rspec file inside /ready4translation (less detailed, sfa enabled) res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) # -> returns the json formatted results (more detailed, omn enriched) value = {} value[:geni_rspec] = res value[:geni_slivers] = [] resources.each do |r| if r.is_a? SAMANT::Lease tmp = {} tmp[:geni_sliver_urn] = r.to_uri.to_s tmp[:geni_expires] = r.expirationTime.to_s tmp[:geni_allocation_status] = if r.hasReservationState.uri == SAMANT::ALLOCATED.uri then "geni_allocated" else "geni_unallocated" end value[:geni_slivers] << tmp end end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::UnknownResourceException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::FormatException => e debug('CreateSliver Exception', e.to_s) @return_struct[:code][:geni_code] = 4 # Bad Version @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Provision: # Request that the named geni_allocated slivers be made geni_provisioned, # instantiating or otherwise realizing the resources, such that they have # a valid geni_operational_status and may possibly be made geni_ready for # experimenter use. This operation is synchronous, but may start a longer process. def provision(options) # TODO Nothing implemented yet for Provision call raise OMF::SFA::AM::Rest::BadRequestException.new "Provision NOT YET IMPLEMENTED" end # Renew: # Request that the named slivers be renewed, with their expiration # extended. If possible, the aggregate should extend the slivers to # the requested expiration time, or to a sooner time if policy limits # apply. This method applies to slivers that are geni_allocated or to # slivers that are geni_provisioned, though different policies may apply # to slivers in the different states, resulting in much shorter max # expiration times for geni_allocated slivers. def renew(options) body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect urns = params[:urns] expiration_time = params[:valid_until] credentials = body[:credentials] debug('Renew: URNs: ', urns.inspect, ' until <', expiration_time, '>') if urns.nil? || urns.empty? || expiration_time.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "Some of the following arguments are missing: 'slice_urn', 'expiration_time'" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end expiration_time = Time.parse(expiration_time).utc slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end debug('Renew ', slice_urn, ' until <', expiration_time, '>') authorizer = options[:req].session[:authorizer] # raise OMF::SFA::AM::InsufficientPrivilegesException.new unless authorizer.account[:urn] == urns.first raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first leases = [] if slivers_only urns.each do |urn| l = @am_manager.find_samant_lease(urn, authorizer) # TODO maybe check thoroughly if slice_urn of slivers is the same as the authenticated user's leases << l end else leases = @am_manager.find_all_samant_leases(slice_urn, $acceptable_lease_states, authorizer) end debug "Leases contain: " + leases.inspect if leases.nil? || leases.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "There are no slivers for slice: '#{slice_urn}'." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # TODO: currently only one lease renewal supported leased_components = @am_manager.find_all_samant_components_for_account(slice_urn, authorizer) leased_components.delete_if {|c| !c.to_uri.to_s.include?"/leased"} # TODO FIX must return only child uxv nodes debug "Leased Components: " + leased_components.inspect value = {} value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| @am_manager.renew_samant_lease(lease, leased_components, authorizer, expiration_time) tmp = {} tmp[:geni_sliver_urn] = lease.to_uri.to_s tmp[:geni_expires] = lease.expirationTime.to_s tmp[:geni_allocation_status] = if lease.hasReservationState.uri == SAMANT::ALLOCATED.uri then "geni_allocated" elsif lease.hasReservationState.uri == SAMANT::PROVISIONED.uri then "geni_provisioned" else "geni_unallocated" end tmp[:geni_operational_status] = "NO_INFO" # lease.isReservationOf.hasResourceStatus.to_s # TODO Match geni_operational_status with an ontology concept value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Status: # Get the status of a sliver or slivers belonging to # a single slice at the given aggregate. def status(options) body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect urns = params[:urns] debug('Status for ', urns.inspect, ' OPTIONS: ', params.inspect) credentials = body[:credentials] if urns.nil? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "The following argument is missing: 'slice_urn'" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end authorizer = options[:req].session[:authorizer] raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first leases = [] if slivers_only urns.each do |urn| l = @am_manager.find_samant_lease(urn, authorizer) leases << l end else leases = @am_manager.find_all_samant_leases(slice_urn, [SAMANT::ALLOCATED, SAMANT::PROVISIONED], authorizer) end value = {} value[:geni_urn] = slice_urn value[:geni_slivers] = [] leases.each do |lease| tmp = {} tmp[:geni_sliver_urn] = lease.to_uri.to_s tmp[:geni_expires] = lease.expirationTime.to_s tmp[:geni_allocation_status] = if lease.hasReservationState.uri == SAMANT::ALLOCATED.uri then "geni_allocated" else "geni_provisioned" end tmp[:geni_operational_status] = "NO INFO" value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::InsufficientPrivilegesException => e @return_struct[:code][:geni_code] = 3 @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Delete a sliver by stopping it if it is still running, and then # deallocating the resources associated with it. This call will # stop and deallocate all resources associated with the given # slice URN. # (close the account and release the attached resources) def delete(options) body, format = parse_body(options) params = body[:options] #debug "Body & Format = ", opts.inspect + ", " + format.inspect urns = params[:urns] debug('DeleteSliver: URNS: ', urns.inspect) credentials = body[:credentials] slice_urn, slivers_only, error_code, error_msg = parse_samant_urns(urns) if error_code != 0 @return_struct[:code][:geni_code] = error_code @return_struct[:output] = error_msg @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end authorizer = options[:req].session[:authorizer] raise OMF::SFA::AM::InsufficientPrivilegesException.new unless credentials[:account][:name] == urns.first value = [] if slivers_only # NOT SURE IF EVER APPLIED urns.each do |urn| l = @am_manager.find_samant_lease(urn, authorizer) tmp = {} tmp[:geni_sliver_urn] = urn tmp[:geni_allocation_status] = 'geni_unallocated' tmp[:geni_expires] = l.expirationTime.to_s value << tmp end else leases = @am_manager.find_all_samant_leases(slice_urn, [SAMANT::ALLOCATED, SAMANT::PENDING], authorizer) debug "leases = " + leases.inspect if leases.nil? || leases.empty? @return_struct[:code][:geni_code] = 1 # Bad Arguments @return_struct[:output] = "There are no slivers for slice: '#{slice_urn}'." @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end leases.each do |l| tmp = {} tmp[:geni_sliver_urn] = l.to_uri tmp[:geni_allocation_status] = 'geni_unallocated' tmp[:geni_expires] = l.expirationTime.to_s value << tmp end end # TODO: ELABORATE @am_manager.close_samant_account(slice_urn, authorizer) debug "Slice '#{slice_urn}' deleted." @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] rescue OMF::SFA::AM::UnavailableResourceException => e @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = e.to_s @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end # Perform an emergency shut down of a sliver. This operation is # intended for administrative use. The sliver is shut down but # remains available for further forensics. # (close the account but do not release its resources) def shutdown(options) # TODO Nothing implemented yet for Provision call raise OMF::SFA::AM::Rest::BadRequestException.new "Shutdown NOT YET IMPLEMENTED" end def parse_samant_urns(urns) slice_urn = nil slivers_only = false urns.each do |urn| utype = urn_type(urn) if utype == "slice" || utype == "account" if urns.size != 1 # you can't send more than one slice urns return ['', '', 1, 'only one slice urn can be described.'] end slice_urn = urn break elsif utype == 'lease' || utype == 'sliver' lease_urn = RDF::URI.new(urn) sparql = SPARQL::Client.new($repository) unless sparql.ask.whether([lease_urn, :p, :o]).true? return ['', '', 1, "Lease '#{urn}' does not exist."] end lease = SAMANT::Lease.for(lease_urn) debug "Lease Exists with ID = " + lease.hasID.inspect new_slice_urn = lease.hasSliceID slice_urn = new_slice_urn if slice_urn.nil? if new_slice_urn != slice_urn return ['', '', 1, "All sliver urns must belong to the same slice."] end slivers_only = true else return ['', '', 1, "Only slivers or a slice can be described."] end end [slice_urn, slivers_only, 0, ''] end def urn_type(urn) urn.split('+')[-2] end end end<file_sep>require 'spira' module Semantic # Preload ontology OmnComponent = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-component#") # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### class OmnComponent < Spira::Base configure :base_uri => OmnComponent type RDF::URI.new('http://open-multinet.info/ontology/omn-component#') # Data Properties property :cores, :predicate => OmnComponent.hasCores, :type => Integer property :model, :predicate => OmnComponent.hasModelType, :type => String end class Cpu < OmnComponent configure :base_uri => OmnComponent.CPU type RDF::URI.new('http://open-multinet.info/ontology/omn-component#CPU') end class MemoryComponent < OmnComponent configure :base_uri => OmnComponent.MemoryComponent type RDF::URI.new('http://open-multinet.info/ontology/omn-component#MemoryComponent') end class ProcessingComponent < OmnComponent configure :base_uri => OmnComponent.ProcessingComponent type RDF::URI.new('http://open-multinet.info/ontology/omn-component#ProcessingComponent') end class StorageComponent < OmnComponent configure :base_uri => OmnComponent.StorageComponent type RDF::URI.new('http://open-multinet.info/ontology/omn-component#StorageComponent') end end<file_sep>module OMF; module SFA VERSION = "6.0.0.pre.1" end; end <file_sep>require 'omf-sfa/models/component' require 'omf-sfa/models/usb_device' module OMF::SFA::Model class LteDongle < UsbDevice # sfa_class 'lte_dongle', :can_be_referred => true, :expose_id => false # def self.exclude_from_json # sup = super # [:node_id].concat(sup) # end # def self.include_nested_attributes_to_json # sup = super # [].concat(sup) # end end end <file_sep>Sequel.migration do up do add_column :nodes, :status, String end down do drop_column :nodes, :status end end <file_sep>require 'omf-sfa/models/component' require 'omf-sfa/models/ip' require 'omf-sfa/models/epc' module OMF::SFA::Model class ENodeB < Component many_to_one :control_ip, class: Ip many_to_one :pgw_ip, class: Ip many_to_one :mme_ip, class: Ip many_to_one :epc many_to_one :cmc plugin :nested_attributes nested_attributes :control_ip, :pgw_ip, :mme_ip, :epc, :cmc sfa_class 'e_node_b', :can_be_referred => true, :expose_id => false def self.exclude_from_json sup = super [:control_ip_id, :pgw_ip_id, :mme_ip_id, :epc_id, :cmc_id].concat(sup) end def self.include_nested_attributes_to_json sup = super [:leases, :control_ip, :pgw_ip, :mme_ip, :epc, :cmc].concat(sup) end def self.can_be_managed? true end end end <file_sep>require 'omf-sfa/models/resource' require 'omf-sfa/models/component' module OMF::SFA::Model class Lease < Resource many_to_many :components, :left_key=>:lease_id, :right_key=>:component_id, :join_table=>:components_leases extend OMF::SFA::Model::Base::ClassMethods include OMF::SFA::Model::Base::InstanceMethods sfa_add_namespace :ol, 'http://nitlab.inf.uth.gr/schema/sfa/rspec/1' sfa_class 'lease', :namespace => :ol, :can_be_referred => true sfa :valid_from, :attribute => true sfa :valid_until, :attribute => true sfa :client_id, :attribute => true sfa :sliver_id, :attribute => true def self.include_nested_attributes_to_json sup = super [:components].concat(sup) end def before_save self.status = 'pending' if self.status.nil? self.name = self.uuid if self.name.nil? self.valid_until = Time.parse(self.valid_until) if self.valid_until.kind_of? String self.valid_from = Time.parse(self.valid_from) if self.valid_from.kind_of? String # Get rid of the milliseconds self.valid_from = Time.at(self.valid_from.to_i) unless valid_from.nil? self.valid_until = Time.at(self.valid_until.to_i) unless valid_until.nil? super self.urn = GURN.create(self.name, :type => 'sliver').to_s if GURN.parse(self.urn).type == 'lease' end def sliver_id self.urn end def active? return false if self.status == 'cancelled' || self.status == 'past' t_now = Time.now t_now >= self.valid_from && t_now < self.valid_until end def to_hash values.reject! { |k, v| v.nil?} values[:components] = [] self.components.each do |component| next if ((self.status == 'active' || self.status == 'accepted') && component.account.id == 2) values[:components] << component.to_hash_brief end values[:account] = self.account ? self.account.to_hash_brief : nil excluded = self.class.exclude_from_json values.reject! { |k, v| excluded.include?(k)} values end def to_hash_brief values[:account] = self.account.to_hash_brief unless self.account.nil? super end def allocation_status return "geni_unallocated" if self.status == 'pending' || self.status == 'cancelled' return "geni_allocated" unless self.status == 'active' ret = 'geni_provisioned' self.components.each do |comp| next if comp.parent.nil? if comp.resource_type == 'node' && comp.status != 'geni_provisioned' ret = 'geni_allocated' break end end ret end def operational_status case self.status when 'pending' "geni_failed" when 'accepted' "geni_pending_allocation" when "active" "geni_ready" when 'cancelled' "geni_unallocated" when 'passed' "geni_unallocated" else self.status end end end end <file_sep>require 'spira' require 'rdf/turtle' require 'rdf/json' require 'sparql/client' #require 'sparql' module Semantic # Preload ontology # exw allaksei Resource se OResource OmnResource = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-resource#") OmnLifecycle = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-lifecycle#") # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### class OResource < Spira::Base configure :base_uri => OmnResource type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#') # Object Properties has_many :hasInterface, :predicate => OmnResource.hasInterface, :type => :Interface property :hasLocation, :predicate => OmnResource.hasLocation, :type => :Location property :hasHardwareType, :predicate => OmnResource.hasHardwareType, :type => :HardwareType # @omn-domain-pc TODO implementation property :isHardwareTypeOf, :predicate => OmnResource.isHardwareTypeOf, :type => :NetworkObject # Data Properties property :isExclusive, :predicate => OmnResource.isExclusive, :type => Boolean # validates :interfaceOf, :type => :NetworkObject # TODO validations? end class NetworkObject < OResource configure :base_uri => OmnResource.NetworkObject type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#NetworkObject') # Object Properties has_many :hasIPAddress, :predicate => OmnResource.hasIPAddress, :type => :IPAddress property :hasSliverType, :predicate => OmnResource.hasSliverType, :type => :SliverType property :requiredBy, :predicate => OmnResource.requiredBy, :type => :NetworkObject property :parent, :predicate => OmnResource.parent has_many :requires, :predicate => OmnResource.requires, :type => :NetworkObject # Data Properties property :isAvailable, :predicate => OmnResource.isAvailable, :type => Boolean attr_accessor :child end class Node < NetworkObject configure :base_uri => OmnResource.Node type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Node') # apo dw kai katw ta exw prosthesei egw gia testing property :hasSliceID, :predicate => OmnLifecycle.hasSliceID, :type => String property :hasComponentID, :predicate => OmnLifecycle.hasComponentID, :type => URI property :hasState , :predicate => OmnLifecycle.hasState, :type => :State property :hasComponentName, :predicate => OmnLifecycle.hasComponentName, :type => String property :hasID, :predicate => OmnLifecycle.hasID, :type => String has_many :hasLease, :predicate => OmnLifecycle.hasLease, :type => :Lease property :parent, :predicate => OmnResource.parent attr_accessor :child #attr_accessor :parent end class Openflow < NetworkObject configure :base_uri => OmnResource.Openflow type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Openflow') end class Interface < NetworkObject configure :base_uri => OmnResource.Interface type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Interface') # Object Properties property :isInterfaceOf, :predicate => OmnResource.isInterfaceOf, :type => :NetworkObject # TODO how to implement group ranges? / multitypes? property :isSink, :predicate => OmnResource.isSink, :type => :Link property :isSource, :predicate => OmnResource.isSource, :type => :Link # Data Properties property :clientId, :predicate => OmnResource.clientId, :type => String property :macAddress, :predicate => OmnResource.macAddress, :type => String property :port, :predicate => OmnResource.port, :type => Integer end class Location < Spira::Base configure :base_uri => OmnResource.Location type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Location') # Data Properties property :jfedX, :predicate => OmnResource.jfedX, :type => String property :jfedY, :predicate => OmnResource.jfedY, :type => String property :x, :predicate => OmnResource.x, :type => Decimal property :y, :predicate => OmnResource.y, :type => Decimal property :z, :predicate => OmnResource.z, :type => Decimal end class Cloud < NetworkObject configure :base_uri => OmnResource.Cloud type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Cloud') end class Hop < NetworkObject configure :base_uri => OmnResource.Hop type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Hop') end class IPAddress < OResource configure :base_uri => OmnResource.IPAddress type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#IPAddress') # Object Properties property :isIPAddressOf, :predicate => OmnResource.isIPAddressOf, :type => :NetworkObject # Data Properties property :address, :predicate => OmnResource.address, :type => String property :netmask, :predicate => OmnResource.netmask, :type => String property :type, :predicate => OmnResource.type, :type => String end class Link < OResource configure :base_uri => OmnResource.Link type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Link') # Object Properties has_many :hasSink, :predicate => OmnResource.hasSink, :type => :Interface has_many :hasSource, :predicate => OmnResource.hasSource, :type => :Interface property :isPropertyOf, :predicate => OmnResource.isPropertyOf, :type => :LinkProperty end class LinkProperty < OResource configure :base_uri => OmnResource.LinkProperty type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#LinkProperty') # Object Properties has_many :hasProperty, :predicate => OmnResource.hasProperty, :type => :Link end class Path < NetworkObject configure :base_uri => OmnResource.Path type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Path') end class SliverType < NetworkObject configure :base_uri => OmnResource.SliverType type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#SliverType') end class Stitching < NetworkObject configure :base_uri => OmnResource.Stitching type RDF::URI.new('http://open-multinet.info/ontology/omn-resource#Stitching') end end <file_sep>require 'omf-sfa/am/am-rest/rest_handler' require 'omf-sfa/am/am-rest/resource_handler' require 'omf-sfa/am/am_manager' require 'uuid' module OMF::SFA::AM::Rest class SamantAdminHandler < RestHandler @@ip_whitelist = ['127.0.0.1'].freeze def find_handler(path, opts) @return_struct = { # hash :code => { :geni_code => "" }, :value => '', :output => '' } debug "!!!ADMIN handler!!!" remote_ip = opts[:req].env["REMOTE_ADDR"] debug "Trying to connect from >>>>> " + remote_ip #debug "what contains? " + @@ip_whitelist.inspect #debug "contains? " + @@ip_whitelist.include?(remote_ip).to_s #unless @@ip_whitelist.include?(remote_ip) # raise OMF::SFA::AM::Rest::BadRequestException.new "Anauthorized access!" #end RDF::Util::Logger.logger.parent.level = 'off' # Worst Bug *EVER* if path.map(&:downcase).include? "getinfo" opts[:resource_uri] = :getinfo elsif path.map(&:downcase).include? "create" opts[:resource_uri] = :create elsif path.map(&:downcase).include? "update" opts[:resource_uri] = :update elsif path.map(&:downcase).include? "delete" opts[:resource_uri] = :delete elsif path.map(&:downcase).include? "change_state" opts[:resource_uri] = :change_state else raise OMF::SFA::AM::Rest::BadRequestException.new "Invalid URL." end return self end def on_get (method, options) body, format = parse_body(options) params = body[:options] authorizer = options[:req].session[:authorizer] resources = get_info(params) res = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) return ['application/json', JSON.pretty_generate(res)] end def on_post (method, options) body, format = parse_body(options) res_el = body[:resources] authorizer = options[:req].session[:authorizer] resources = create_or_update(res_el, false, authorizer) resp = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) return ['application/json', JSON.pretty_generate(resp)] end def on_put (method, options) body, format = parse_body(options) if method == :change_state resources = body[:resources] resp = change_state(resources) # return ['application/json', JSON.pretty_generate(resp)] else res_el = body[:resources] authorizer = options[:req].session[:authorizer] resources = create_or_update(res_el, true, authorizer) resp = OMF::SFA::AM::Rest::ResourceHandler.omn_response_json(resources, options) return ['application/json', JSON.pretty_generate(resp)] end end def on_delete (method, options) body, format = parse_body(options) resources = body[:resources] authorizer = options[:req].session[:authorizer] resp = delete(resources, authorizer) return ['application/json', JSON.pretty_generate(resp)] end # Retain info based on class/urn def get_info(params) debug 'Admin ListResources: Options: ', params.inspect category = params[:type] descr = params[:description] descr, find_with_array_hash = find_doctor(descr) if category # if applied specific resource type debug "descr = " + descr.inspect resources = @am_manager.find_all_samant_resources(category, descr) elsif urns = params[:urns] # if applied for certain urns resources = @am_manager.find_all_samant_resources(nil, descr) resources.delete_if {|c| !urns.include?(c.to_uri.to_s)} end resources.delete_if {|c| c.to_uri.to_s.include?"/leased"} unless resources.nil? unless find_with_array_hash.empty? resources.delete_if {|c| !find_with_array_hash.values[0].include? eval("c.#{find_with_array_hash.keys[0]}")} unless resources.nil? end resources end # Create or Update SAMANT resources. If +clean_state+ is true, resources are updated, else they are created from scratch. def create_or_update(res_el, clean_state, authorizer) sparql = SPARQL::Client.new($repository) debug 'Admin CreateOrUpdate: resources: ', res_el.inspect unless res_el.is_a?(Array) res_el = [res_el] end resources = [] res_el.each do |params| descr = params[:resource_description] descr = create_doctor(descr, authorizer) # Connect the objects first if clean_state # update urn = params[:urn] if (urn.start_with?("uuid")) type = "Lease" else type = OMF::SFA::Model::GURN.parse(urn).type.camelize end res = eval("SAMANT::#{type}").for(urn) unless sparql.ask.whether([res.to_uri, :p, :o]).true? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{res.inspect}' not found. Please create that first." end authorizer.can_modify_resource?(res, type) res.update_attributes(descr) # Not sure if different than ".for(urn, new_descr)" regarding an already existent urn else # create if params[:type] && (params[:type].camelize == "Uxv") && !(descr.keys.find {|k| k.to_s == "hasUxVType"}) raise OMF::SFA::AM::Rest::BadRequestException.new "Please provide a UxV type in your description." end unless params[:name] && params[:type] && params[:authority] raise OMF::SFA::AM::Rest::BadRequestException.new "One of the following mandatory parameters is missing: name, type, authority." end urn = OMF::SFA::Model::GURN.create(params[:name], {:type => params[:type], :domain => params[:authority]}) type = params[:type].camelize descr[:hasID] = SecureRandom.uuid # Every resource must have a uuid descr[:hasComponentID] = urn.to_s descr[:resourceId] = params[:name] if type.downcase == "uxv" descr[:hasSliceID] = "urn:publicid:IDN+omf:netmode+account+__default__" # default slice_id on creation; required on allocation end res = eval("SAMANT::#{type}").for(urn, descr) # doesn't save unless you explicitly define so unless sparql.ask.whether([res.to_uri, :p, :o]).false? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{res.inspect}' already exists." end authorizer.can_create_resource?(res, type) debug "Res:" + res.inspect res.save! end resources << res end resources end # Delete SAMANT resources def delete(resources, authorizer) sparql = SPARQL::Client.new($repository) debug 'Admin Delete: resources: ', resources.inspect unless resources.is_a?(Array) resources = [resources] end resources.each do |resource| urn = resource[:urn] gurn = OMF::SFA::Model::GURN.parse(resource[:urn]) type = gurn.type.camelize res = eval("SAMANT::#{type}").for(urn) debug "res: " + res.inspect unless sparql.ask.whether([res.to_uri, :p, :o]).true? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{res.inspect}' not found. Please create that first." end if (res.is_a?SAMANT::Uxv)||(res.is_a?SAMANT::Interface)||(res.is_a?SAMANT::System)||(res.is_a?SAMANT::SensingDevice) res.hasComponentID = nil # F*ing bug res.save! end authorizer.can_release_resource?(res) res.destroy! end return {:response => "Resource(s) Successfully Deleted"} end # Connect instances before creating/updating def create_doctor(descr, authorizer) sparql = SPARQL::Client.new($repository) descr.each do |key, value| debug "key = " + key.to_s next if key == :hasComponentID || key == :hasSliceID # These *strings* are permitted to contain the "urn" substring if value.is_a?(Array) arr_value = value new_array = [] arr_value.each do |v| v = create_or_update(v, false, authorizer).first.uri.to_s if v.is_a?(Hash) # create the described object gurn = OMF::SFA::Model::GURN.parse(v) # Assumes "v" is a urn unless gurn.type && gurn.name raise OMF::SFA::AM::Rest::UnsupportedBodyFormatException.new "Invalid URN: " + v.to_s end new_res = eval("SAMANT::#{gurn.type.camelize}").for(gurn.to_s) unless sparql.ask.whether([new_res.to_uri, :p, :o]).true? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{new_res.inspect}' not found. Please create that first." end new_array << new_res end debug "New Array contains: " + new_array.inspect descr[key] = new_array else value = create_or_update(value, false, authorizer).first.uri.to_s if value.is_a?(Hash) # create the described object if value.include? "urn" # Object found, i.e uxv, sensor etc gurn = OMF::SFA::Model::GURN.parse(value) unless gurn.type raise OMF::SFA::AM::Rest::UnsupportedBodyFormatException.new "Invalid URN: " + value.to_s end descr[key] = eval("SAMANT::#{gurn.type.camelize}").for(gurn.to_s) unless sparql.ask.whether([descr[key].to_uri, :p, :o]).true? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{descr[key].inspect}' not found. Please create that first." end elsif value.include? "http" # Instance found, i.e HealthStatus, Resource Status etc type = value.split("#").last # type = value.split("#").last.chop type = type.chop if type[-1,1] == "/" debug "Type: " + type # new_res = eval("SAMANT::#{type}").for("") new_res = eval("SAMANT::#{type.upcase}") unless sparql.ask.whether([new_res.to_uri, :p, :o]).true? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource '#{new_res.inspect}' not found. Please create that first." end descr[key] = new_res elsif value == "nil" descr[key] = nil end end end debug "New Hash contains: " + descr.inspect descr end # Find instances def find_doctor(descr) find_with_array_hash = Hash.new descr.each do |key,value| next if key == :hasComponentID || key == :hasSliceID if value.is_a?(Hash) new_value = get_info(value).first.uri.to_s descr[key] = RDF::URI(new_value) elsif value.is_a?(Array) arr_value = value new_array = [] arr_value.each do |v| if v.include? "http" or v.include? "urn" new_array << RDF::URI(v).to_uri end end find_with_array_hash[key] = new_array puts "Array find fix, hash contains:" puts find_with_array_hash.inspect descr.delete(key) elsif value.include? "http" or value.include? "urn" # Instance found, i.e HealthStatus, Resource Status etc descr[key] = RDF::URI(value) end end debug "New descr contains: " + descr.inspect return descr, find_with_array_hash end # Change Lease state def change_state(resources) debug "I'm in change state!" value = {} value[:geni_slivers] = [] unless resources.is_a?(Array) resources = [resources] end resources.each do |resource| uuid = resource[:urn] if ["ALLOCATED", "CANCELLED"].include? resource[:state].upcase state = eval("SAMANT::#{resource[:state].upcase}") else @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = "Unkown state provided" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end l_uuid = uuid.gsub("uuid:", "") debug "Looking for Lease with uuid: " + l_uuid url = "http://172.16.17.32:8080/openrdf-sesame/repositories/samRemoteClean" Spira.repository = RDF::Sesame::Repository.new(url) lease = SAMANT::Lease.find(:all, :conditions => { :hasID => l_uuid} ).first if lease.nil? @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = "Lease not found!" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end if lease.hasReservationState.uri == SAMANT::CANCELLED.uri @return_struct[:code][:geni_code] = 12 # Search Failed @return_struct[:output] = "Cannot change cancelled lease!" @return_struct[:value] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end lease.hasReservationState = state lease.save lease.isReservationOf.map do |resource| lease.hasReservationState.uri == SAMANT::ALLOCATED.uri ? resource.hasResourceStatus = SAMANT::BOOKED : resource.hasResourceStatus = SAMANT::RELEASED # PRESENT STATE resource.save end if lease.hasReservationState.uri == SAMANT::CANCELLED @am_manager.get_scheduler.release_samant_lease(lease) end tmp = {} tmp[:geni_sliver_urn] = lease.to_uri.to_s tmp[:geni_expires] = lease.expirationTime.to_s tmp[:geni_allocation_status] = if lease.hasReservationState.uri == SAMANT::ALLOCATED.uri then "geni_allocated" else "geni_unallocated" end value[:geni_slivers] << tmp end @return_struct[:code][:geni_code] = 0 @return_struct[:value] = value @return_struct[:output] = '' return ['application/json', JSON.pretty_generate(@return_struct)] end end end <file_sep>source "http://rubygems.org" gem 'rake' # Specify your gem's dependencies in omf_sfa.gemspec gemspec # Frozen local rdf sesame gem, because of peculiarities gem "rdf-sesame", '2.0.2', path: "modified_gems/rdf-sesame-2.0.2" <file_sep>require 'rubygems' gem 'minitest' require 'minitest/autorun' # require 'net/http' require 'rest-client' require 'json' class RestTests < Minitest::Unit::TestCase @@random_number = Random.rand(1100) def setup puts "start testing Broker at localhost:8001 " puts "setting up" puts "test_create_node" json_payload = '{"name":"Ioannina%{number}","x":11.11111,"y":22.2222}' % { number:@@random_number } puts json_payload result = RestClient::Request.execute(method: :post, url: 'https://localhost:8001/omn-resources/locations', headers: {content_type: "application/json" , accept: "application/json"}, payload: json_payload, :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("user_cert.pem")), :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("user_cert.pkey")), :verify_ssl => OpenSSL::SSL::VERIFY_NONE) # puts result puts "test_create_node end"; case result.code when 200 assert(true) result else assert(false) end end def test_get_location_resource puts "test_get_location_resource" json_payload = '{"name":"Ioannina%{number}"}'% { number:@@random_number } # json_payload = '{"name":"Ioannina1234567"}'% { number:@@random_number } puts json_payload result = RestClient::Request.execute(method: :get, url: 'https://localhost:8001/omn-resources/locations', headers: {content_type: "application/json" , accept: "application/json"}, payload: json_payload, :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("user_cert.pem")), :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("user_cert.pkey")), :verify_ssl => OpenSSL::SSL::VERIFY_NONE) puts result puts result.code case result.code when 200 assert(true) else assert(false) end end # def test_get_resources # puts "test_get_resources" # # resource = RestClient::Resource.new( # 'https://localhost:8001/omn-resources/nodes', # :verify_ssl => OpenSSL::SSL::VERIFY_NONE # ) # response = resource.get # # puts "response code" # puts response.code # json_res = JSON.parse(response) # # puts json_res.is_a?(Array) # # # puts "json to array" # puts json_res # => {"val"=>"test","val1"=>"test1","val2"=>"test2"} # puts "access array" # puts json_res.length # puts json_res[0].is_a?(Hash) # # hash_item = json_res[0] # # puts "print keys" # puts hash_item.keys # first_item = hash_item["http://open-multinet.info/ontology/omn-resource#Node/node2"] # puts first_item.is_a?(Hash) # puts first_item # # # puts json_res["http://open-multinet.info/ontology/omn-resource#Node/node2"].to_s # assert_equal 200, response.code # end def teardown puts "tearing down" json_payload = '{"name":"Ioannina%{number}"}'% { number:@@random_number } puts json_payload result = RestClient::Request.execute(method: :delete, url: 'https://localhost:8001/omn-resources/locations', headers: {content_type: "application/json" , accept: "application/json"}, payload: json_payload, :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("user_cert.pem")), :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("user_cert.pkey")), :verify_ssl => OpenSSL::SSL::VERIFY_NONE) puts result case result.code when 200 assert(true) else assert(false) end puts "test_delete_node end" end end<file_sep>require_relative 'anyURItype.rb' # Custom XSD.anyURI type, missing from Spira Implementation module SAMANT # TODO module SAMANT to SAMANT::Model # Ontology Namespaces (prefixes) # Built in vocabs: OWL, RDF, RDFS OMNupper = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn#") OMNresource = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-resource#") OMNlifecycle = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-lifecycle#") OMNfederation = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-federation#") OMNwireless = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-domain-wireless#") # SAMANTuxv = RDF::Vocabulary.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#") FOAF = RDF::Vocabulary.new("http://xmlns.com/foaf/0.1/") GML = RDF::Vocabulary.new("http://www.opengis.net/gml/") GEO = RDF::Vocabulary.new("http://www.georss.org/georss/") GEO2003 = RDF::Vocabulary.new("http://www.w3.org/2003/01/geo/wgs84_pos#") ##### CLASSES ##### class Geometry < Spira::Base configure :base_uri => GML._Geometry type RDF::URI.new("http://www.opengis.net/gml/_Geometry") # Data Properties property :countryCode, :predicate => SAMANTuxv.countryCode, :type => RDF::XSD.string end class Channel < Spira::Base # Imported from omn-domain-wireless:Channel configure :base_uri => OMNwireless.Channel type RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#Channel") # Object Properties property :supportsStandard, :predicate => OMNwireless.supportsStandard, :type => :Standard property :usesFrequency, :predicate => OMNwireless.usesFrequency, :type => :Frequency # Data Properties property :channelNum, :predicate => OMNwireless.channelNum, :type => RDF::XSD.integer end class OFrequency < Spira::Base # Imported from omn-domain-wireless:Frequency configure :base_uri => OMNwireless.Frequency type RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#Frequency") # Data Properties property :lowerBoundFrequency, :predicate => OMNwireless.lowerBoundFrequency, :type => RDF::XSD.integer property :upperBoundFrequency, :predicate => OMNwireless.upperBoundFrequency, :type => RDF::XSD.integer end class Standard < Spira::Base # Imported from omn-domain-wireless:Standard configure :base_uri => OMNwireless.Standard type RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#Standard") end class Size < Spira::Base configure :base_uri => SAMANTuxv.Size type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Size") end class Reservation < Spira::Base # Imported from omn:Reservation configure :base_uri => OMNupper.Reservation type RDF::URI.new("http://open-multinet.info/ontology/omn#Reservation") end class Interface < Spira::Base # Imported from omn-resource:Interface configure :base_uri => OMNresource.Interface type RDF::URI.new("http://open-multinet.info/ontology/omn-resource#Interface") # Object Properties property :hasComponent, :predicate => OMNresource.hasComponent, :type => :Channel property :isInterfaceOf, :predicate => OMNresource.isInterfaceOf, :type => :Uxv # Data Properties property :hasID, :predicate => OMNlifecycle.hasID, :type => RDF::XSD.string property :resourceId, :predicate => OMNlifecycle.resourceId, :type => RDF::XSD.string property :hasInterfaceType, :predicate => SAMANTuxv.hasInterfaceType, :type => RDF::XSD.string property :hasComponentName, :predicate => OMNlifecycle.hasComponentName, :type => RDF::XSD.string property :hasComponentID, :predicate => OMNlifecycle.hasComponentID, :type => XSD.anyURI property :hasRole, :predicate => OMNlifecycle.hasRole, :type => RDF::XSD.string property :consumesPower, :predicate => SAMANTuxv.consumesPower, :type => RDF::XSD.string end class ReservationState < Spira::Base # Imported from omn-lifecycle:ReservationState configure :base_uri => OMNlifecycle.ReservationState type RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#ReservationState") end class Resource < Spira::Base # Imported from omn:Reservation configure :base_uri => OMNupper.Resource type RDF::URI.new("http://open-multinet.info/ontology/omn#Resource") end class Infrastructure < Spira::Base # Imported by omn-federation:Infrastructure configure :base_uri => OMNfederation.Infrastructure type RDF::URI.new("http://open-multinet.info/ontology/omn-federation#Infrastructure") end class HealthStatus < Spira::Base configure :base_uri => SAMANTuxv.HealthStatus type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#HealthStatus") # Object Properties property :isHealthStatusOf, :predicate => SAMANTuxv.isHealthStatusOf, :type => :Uxv property :isHealthStatusOf, :predicate => SAMANTuxv.isHealthStatusOf, :type => :TestBed property :isHealthStatusOf, :predicate => SAMANTuxv.isHealthStatusOf, :type => :SensingDevice property :isHealthStatusOf, :predicate => SAMANTuxv.isHealthStatusOf, :type => :System end class ResourceStatus < Spira::Base configure :base_uri => SAMANTuxv.ResourceStatus type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#ResourceStatus") # Object Properties property :isResourceStatusOf, :predicate => SAMANTuxv.isResourceStatusOf, :type => :Uxv end class UserRole < Spira::Base configure :base_uri => SAMANTuxv.UserRole type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UserRole") # Object Properties has_many :isUserRoleOf, :predicate => SAMANTuxv.isUserRoleOf, :type => :UserSettings end class UserSettings < Spira::Base configure :base_uri => SAMANTuxv.UserSettings type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UserSettings") # Object Properties property :hasUserRole, :predicate => SAMANTuxv.hasUserRole, :type => :UserRole property :isUserSettingsOf, :predicate => SAMANTuxv.isUserSettingsOf, :type => :Person # Data Properties property :hasPreferences, :predicate => SAMANTuxv.hasPreferences, :type => RDF::XSD.string property :isUpdated, :predicate => SAMANTuxv.isUpdated, :type => RDF::XSD.string end class UxVType < Spira::Base configure :base_uri => SAMANTuxv.UxVType type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UxVType") # Object Properties property :isUxVTypeOf, :predicate => SAMANTuxv.isUxVTypeOf, :type => :Uxv end class Person < Spira::Base # User configure :base_uri => FOAF.Person type RDF::URI.new("http://xmlns.com/foaf/0.1/Person") # Object Properties has_many :hasUserSettings, :predicate => SAMANTuxv.hasUserSettings, :type => :UserSettings has_many :usesTestbed, :predicate => SAMANTuxv.usesTestbed, :type => :Testbed # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string property :hasEmail, :predicate => SAMANTuxv.hasEmail, :type => RDF::XSD.string property :hasFirstName, :predicate => SAMANTuxv.hasFirstName, :type => RDF::XSD.string property :hasSurname, :predicate => SAMANTuxv.hasSurname, :type => RDF::XSD.string property :hasUserName, :predicate => SAMANTuxv.hasUserName, :type => RDF::XSD.string property :isSuperUser, :predicate => SAMANTuxv.isSuperUser, :type => RDF::XSD.boolean property :lastLogin, :predicate => SAMANTuxv.lastLogin, :type => RDF::XSD.string property :hasPassword, :predicate => SAMANTuxv.hasPassword, :type => RDF::XSD.string property :hasUserID, :predicate => SAMANTuxv.hasUserID, :type => RDF::XSD.string end class ConfigParameters < Spira::Base configure :base_uri => SAMANTuxv.ConfigParameters type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#ConfigParameters") # Object Properties property :isConfigParametersOf, :predicate => SAMANTuxv.isConfigParametersOf, :type => :Uxv property :hasExperimentResourceConfig, :predicate => SAMANTuxv.hasExperimentResourceConfig, :type => :ExperimentResourceConfig # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string property :hasName, :predicate => SAMANTuxv.hasName, :type => RDF::XSD.string property :hasDescription, :predicate => SAMANTuxv.hasDescription, :type => RDF::XSD.string property :hasConfigParametersID, :predicate => SAMANTuxv.hasConfigParametersID, :type => RDF::XSD.string property :hasConfigParametersMinValue, :predicate => SAMANTuxv.hasConfigParametersMinValue, :type => Float property :hasConfigParametersMaxValue, :predicate => SAMANTuxv.hasConfigParametersMaxValue, :type => Float end class ExperimentResourceConfig < Spira::Base configure :base_uri => SAMANTuxv.ExperimentResourceConfig type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#ExperimentResourceConfig") # Object Properties property :isExperimentResourceConfigOf, :predicate => SAMANTuxv.isExperimentResourceConfigOf, :type => :ConfigParameters # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string property :hasExperimentResourceConfigID, :predicate => SAMANTuxv.hasExperimentResourceConfigID, :type => RDF::XSD.string property :hasExperimentResourceConfigParamValue, :predicate => SAMANTuxv.hasExperimentResourceConfigParamValue, :type => Float end class HealthInformation < Spira::Base configure :base_uri => SAMANTuxv.HealthInformation type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#HealthInformation") # Object Properties property :isHealthInformationOf, :predicate => SAMANTuxv.isHealthInformationOf, :type => :Uxv property :isHealthInformationOf, :predicate => SAMANTuxv.isHealthInformationOf, :type => :Testbed property :isHealthInformationOf, :predicate => SAMANTuxv.isHealthInformationOf, :type => :SensingDevice property :hasGeneralHealthStatus, :predicate => SAMANTuxv.hasGeneralHealthStatus, :type => :GeneralHealthStatus # Data Properties property :isUpdated, :predicate => SAMANTuxv.isUpdated, :type => RDF::XSD.string property :hasMessage, :predicate => SAMANTuxv.hasMessage, :type => RDF::XSD.string end class GeneralHealthStatus < Spira::Base configure :base_uri => SAMANTuxv.GeneralHealthStatus type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#GeneralHealthStatus") # Object Properties property :isGeneralHealthStatusOf, :predicate => SAMANTuxv.isGeneralHealthStatusOf, :type => :HealthInformation end class WiredInterface < Interface # Imported from omn-domain-wireless:WiredInterface configure :base_uri => OMNwireless.WiredInterface type RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#WiredInterface") end class WirelessInterface < Interface # Imported from omn-domain-wireless:WirelessInterface configure :base_uri => OMNwireless.WirelessInterface type RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#WirelessInterface") # Data Properties property :antennaCount, :predicate => OMNwireless.antennaCount, :type => RDF::XSD.integer end class Uxv < Resource configure :base_uri => SAMANTuxv.Uxv type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UxV") # Object Properties property :hasHealthStatus, :predicate => SAMANTuxv.hasHealthStatus, :type => :HealthStatus property :hasResourceStatus, :predicate => SAMANTuxv.hasResourceStatus, :type => :ResourceStatus property :hasHealthInformation, :predicate => SAMANTuxv.hasHealthInformation, :type => :HealthInformation property :isResourceOf, :predicate => SAMANTuxv.isResourceOf, :type => :Testbed property :hasUxVType, :predicate => SAMANTuxv.hasUxVType, :type => :UxVType property :hasReservation, :predicate => OMNlifecycle.hasReservation, :type => :Reservation property :hasConfigParameters, :predicate => SAMANTuxv.hasConfigParameters, :type => :ConfigParameters property :hasSensorSystem, :predicate => SAMANTsensor.hasSensorSystem, :type => :System property :hasParent, :predicate => SAMANTuxv.hasParent, :type => :Uxv has_many :hasChild, :predicate => SAMANTuxv.hasChild, :type => :Uxv has_many :hasInterface, :predicate => OMNresource.hasInterface, :type => :Interface has_many :where, :predicate => GEO.where, :type => :Geometry has_many :hasLease, :predicate => OMNlifecycle.hasLease, :type => :Lease # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string #uuid property :resourceId, :predicate => OMNlifecycle.resourceId, :type => RDF::XSD.string property :clientID, :predicate => SAMANTuxv.clientID, :type => RDF::XSD.string property :hasDescription, :predicate => SAMANTuxv.hasDescription, :type => RDF::XSD.string property :hasName, :predicate => SAMANTuxv.hasName, :type => RDF::XSD.string property :hasStatusMessage, :predicate => SAMANTuxv.hasStatusMessage, :type => RDF::XSD.string property :hasComponentID, :predicate => OMNlifecycle.hasComponentID, :type => RDF::XSD.anyURI property :hasComponentManagerID, :predicate => OMNlifecycle.hasComponentManagerID, :type => URI property :hasComponentManagerName, :predicate => OMNlifecycle.hasComponentManagerName, :type => URI property :hasComponentName, :predicate => OMNlifecycle.hasComponentName, :type => RDF::XSD.string property :hasOriginalID, :predicate => OMNlifecycle.hasOriginalID, :type => RDF::XSD.string property :hasRole, :predicate => OMNlifecycle.hasRole, :type => RDF::XSD.string property :hasSliverID, :predicate => OMNlifecycle.hasSliverID, :type => RDF::XSD.string property :hasSliverName, :predicate => OMNlifecycle.hasSliverName, :type => RDF::XSD.string property :hasSliceID, :predicate => OMNlifecycle.hasSliceID, :type => RDF::XSD.string property :weight, :predicate => SAMANTuxv.weight, :type => RDF::XSD.double property :mtoWeight, :predicate => SAMANTuxv.mtoWeight, :type => RDF::XSD.double property :length, :predicate => SAMANTuxv.length, :type => RDF::XSD.double property :width, :predicate => SAMANTuxv.width, :type => RDF::XSD.double property :height, :predicate => SAMANTuxv.height, :type => RDF::XSD.double property :diameter, :predicate => SAMANTuxv.diameter, :type => RDF::XSD.double property :endurance, :predicate => SAMANTuxv.endurance, :type => RDF::XSD.string property :battery, :predicate => SAMANTuxv.battery, :type => RDF::XSD.string property :hasTopSpeed, :predicate => SAMANTuxv.hasTopSpeed, :type => RDF::XSD.string property :hasAvgSpeed, :predicate => SAMANTuxv.hasAvgSpeed, :type => RDF::XSD.string property :consumesPower, :predicate => SAMANTuxv.consumesPower, :type => RDF::XSD.string end class Lease < Reservation # Sliver # Imported from omn-lifecycle:Lease configure :base_uri => OMNlifecycle.Lease type RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Lease") # Object Properties has_many :isReservationOf, :predicate => SAMANTuxv.isReservationOf, :type => :Uxv property :hasReservationState, :predicate => OMNlifecycle.hasReservationState, :type => :ReservationState # Data Properties property :hasID, :predicate => OMNlifecycle.hasID, :type => RDF::XSD.string property :clientID, :predicate => SAMANTuxv.clientID, :type => RDF::XSD.string property :startTime, :predicate => OMNlifecycle.startTime, :type => RDF::XSD.dateTime property :expirationTime, :predicate => OMNlifecycle.expirationTime, :type => RDF::XSD.dateTime property :hasStatusMessage, :predicate => SAMANTuxv.hasStatusMessage, :type => RDF::XSD.string property :hasSliceID, :predicate => OMNlifecycle.hasSliceID, :type => RDF::XSD.string end class Unallocated < ReservationState # SFA -> Past / RAWFIE -> Released # Imported from omn-lifecycle:Unallocated configure :base_uri => OMNlifecycle.Unallocated type RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Unallocated") end class Allocated < ReservationState # SFA -> Accepted / RAWFIE -> Booked # Imported from omn-lifecycle:Allocated configure :base_uri => OMNlifecycle.Allocated type RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Allocated") end class Provisioned < ReservationState # SFA -> Active / RAWFIE -> Provisioned # Imported from omn-lifecycle:Provisioned configure :base_uri => OMNlifecycle.Provisioned type RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Provisioned") end class Pending < ReservationState # SFA -> Pending / RAWFIE -> Incomplete configure :base_uri => SAMANTuxv.Pending type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Pending") end class Cancelled < ReservationState configure :base_uri => SAMANTuxv.Cancelled type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Cancelled") end class AuV < UxVType configure :base_uri => SAMANTuxv.AuV type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#AuV") end class UaV < UxVType configure :base_uri => SAMANTuxv.UaV type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UaV") end class UgV < UxVType configure :base_uri => SAMANTuxv.UgV type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UgV") end class UsV < UxVType configure :base_uri => SAMANTuxv.UsV type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UsV") end class AuthorityUser < UserRole configure :base_uri => SAMANTuxv.AuthorityUser type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#AuthorityUser") end class Experimenter < UserRole configure :base_uri => SAMANTuxv.Experimenter type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Experimenter") end class TestbedManager < UserRole configure :base_uri => SAMANTuxv.TestbedManager type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#TestbedManager") end class Booked < ResourceStatus configure :base_uri => SAMANTuxv.Booked type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Booked") end class Released < ResourceStatus configure :base_uri => SAMANTuxv.Released type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Released") end class SleepMode < ResourceStatus configure :base_uri => SAMANTuxv.SleepMode type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#SleepMode") end class Critical < HealthStatus configure :base_uri => SAMANTuxv.Critical type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Critical") end class Ok < HealthStatus configure :base_uri => SAMANTuxv.OK type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#OK") end class Shutdown < HealthStatus configure :base_uri => SAMANTuxv.Shutdown type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Shutdown") end class Warning < HealthStatus configure :base_uri => SAMANTuxv.Warning type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Warning") end class Testbed < Infrastructure configure :base_uri => SAMANTuxv.Testbed type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Testbed") # Object Properties property :hasHealthStatus, :predicate => SAMANTuxv.hasHealthStatus, :type => :HealthStatus property :isTestbedOf, :predicate => SAMANTuxv.isTestbedOf, :type => :Person property :hasHealthInformation, :predicate => SAMANTuxv.hasHealthInformation, :type => :HealthInformation property :where, :predicate => GEO.where, :type => :Geometry has_many :hasResource, :predicate => SAMANTuxv.hasResource, :type => :Uxv # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string property :hasName, :predicate => SAMANTuxv.hasName, :type => RDF::XSD.string property :hasDescription, :predicate => SAMANTuxv.hasDescription, :type => RDF::XSD.string property :hasTestbedID, :predicate => SAMANTuxv.hasTestbedID, :type => RDF::XSD.string property :hasUavSupport, :predicate => SAMANTuxv.hasUavSupport, :type => RDF::XSD.boolean property :hasUgvSupport, :predicate => SAMANTuxv.hasUgvSupport, :type => RDF::XSD.boolean property :hasUsvSupport, :predicate => SAMANTuxv.hasUsvSupport, :type => RDF::XSD.boolean property :hasStatusMessage, :predicate => SAMANTuxv.hasStatusMessage, :type => RDF::XSD.string end class Point < Geometry configure :base_uri => GML.Point type RDF::URI.new("http://www.opengis.net/gml/Point") # Data Properties property :pos, :predicate => GML.pos, :type => RDF::XSD.string end class Point3D < Geometry configure :base_uri => SAMANTuxv.Point3D type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Point3D") # Data Properties property :hasID, :predicate => SAMANTuxv.hasID, :type => RDF::XSD.string property :lat, :predicate => GEO2003.lat, :type => RDF::XSD.double property :alt, :predicate => GEO2003.alt, :type => RDF::XSD.double property :long, :predicate => GEO2003.long, :type => RDF::XSD.double end class Polygon < Geometry configure :base_uri => GML.Polygon type RDF::URI.new("http://www.opengis.net/gml/Polygon") # Object Properties property :exterior, :predicate => GML.exterior, :type => :LinearRing end class LinearRing < Geometry configure :base_uri => GML.LinearRing type RDF::URI.new("http://www.opengis.net/gml/LinearRing") # Data Properties has_many :posList, :predicate => GML.posList, :type => RDF::XSD.string end class GeneralOK < GeneralHealthStatus configure :base_uri => SAMANTuxv.GeneralOK type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#GeneralOK") end class GeneralWarning < GeneralHealthStatus configure :base_uri => SAMANTuxv.GeneralWarning type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#GeneralWarning") end class GeneralCritical < GeneralHealthStatus configure :base_uri => SAMANTuxv.GeneralCritical type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#GeneralCritical") end class GeneralUnknown < GeneralHealthStatus configure :base_uri => SAMANTuxv.GeneralUnknown type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#GeneralUnknown") end ##### INDIVIDUALS ##### (modelled as ruby constants) ALLOCATED = Allocated.for("").save! CANCELLED = Cancelled.for("").save! PROVISIONED = Provisioned.for("").save! UNALLOCATED = Unallocated.for("").save! PENDING = Pending.for("").save! AUV = AuV.for("").save! AUTHORITYUSER = AuthorityUser.for("").save! BOOKED = Booked.for("").save! CRITICAL = Critical.for("").save! EXPERIMENTER = Experimenter.for("").save! OK = Ok.for("").save! RELEASED = Released.for("").save! SHUTDOWN = Shutdown.for("").save! SLEEPMODE = SleepMode.for("").save! TESTBEDMANAGER = TestbedManager.for("").save! UAV = UaV.for("").save! UGV = UgV.for("").save! USV = UsV.for("").save! WARNING = Warning.for("").save! GENERALWARNING = GeneralWarning.for("").save! GENERALCRITICAL = GeneralCritical.for("").save! GENERALOK = GeneralOK.for("").save! GENERALUNKNOWN = GeneralUnknown.for("").save! end<file_sep>module SAMANT RDF::Util::Logger.logger.parent.level = 'off' # Ontology Namespaces (prefixes) # Built in vocabs: OWL, RDF, RDFS SAMANTsensor = RDF::Vocabulary.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#") SAMANTuxv = RDF::Vocabulary.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#") QU = RDF::Vocabulary.new("http://purl.oclc.org/NET/ssnx/qu/qu#") DIM = RDF::Vocabulary.new("http://purl.oclc.org/NET/ssnx/qu/dim#") SSN = RDF::Vocabulary.new("http://purl.oclc.org/NET/ssnx/ssn#") DUL = RDF::Vocabulary.new("http://www.loa-cnr.it/ontologies/DUL.owl#") UNIT = RDF::Vocabulary.new("http://purl.oclc.org/NET/ssnx/qu/unit#") OMNlifecycle = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-lifecycle#") ##### CLASSES ##### class Quality < Spira::Base configure :base_uri => DUL.Quality type RDF::URI.new("http://www.loa-cnr.it/ontologies/DUL.owl#Quality") end class QuantityKind < Quality configure :base_uri => QU.QuantityKind type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/qu#QuantityKind") # Object Properties has_many :isPropertyOf, :predicate => SSN.isPropertyOf, :type => :FeatureOfInterest end class UnitOfMeasure < Spira::Base configure :base_uri => DUL.UnitOfMeasure type RDF::URI.new("http://www.loa-cnr.it/ontologies/DUL.owl#UnitOfMeasure") end class Unit < UnitOfMeasure configure :base_uri => QU.Unit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/qu#Unit") # Object Properties property :isUnitOf, :predicate => SAMANTsensor.isUnitOf, :type => :SensingDevice end class SensingDevice < Spira::Base configure :base_uri => SSN.SensingDevice type RDF::URI.new("http://purl.oclc.org/NET/ssnx/ssn#SensingDevice") # Object Properties property :isPartOf, :predicate => DUL.isPartOf, :type => :System has_many :observes, :predicate => SSN.observes, :type => :QuantityKind has_many :hasUnit, :predicate => SAMANTsensor.hasUnit, :type => :Unit # Data Properties property :hasComponentID, :predicate => OMNlifecycle.hasComponentID, :type => RDF::XSD.anyURI property :resourceId, :predicate => OMNlifecycle.resourceId, :type => RDF::XSD.string property :hasVendorName, :predicate => SAMANTsensor.hasVendorName, :type => RDF::XSD.string property :hasProductName, :predicate => SAMANTsensor.hasProductName, :type => RDF::XSD.string property :hasSerial, :predicate => SAMANTsensor.hasSerial, :type => RDF::XSD.string property :hasID, :predicate => SAMANTsensor.hasID, :type => RDF::XSD.string property :hasDescription, :predicate => SAMANTsensor.hasDescription, :type => RDF::XSD.string property :consumesPower, :predicate => SAMANTuxv.consumesPower, :type => RDF::XSD.string end class System < Spira::Base configure :base_uri => SSN.System type RDF::URI.new("http://purl.oclc.org/NET/ssnx/ssn#System") # Object Properties has_many :hasSubSystem, :predicate => SSN.hasSubSystem, :type => :SensingDevice # has_many :hasSubSystem, :predicate => SSN.hasSubSystem, :type => :System property :isSensorSystemOf, :predicate => SAMANTsensor.isSensorSystemOf, :type => :Uxv property :hasHealthStatus, :predicate => SAMANTuxv.hasHealthStatus, :type => :HealthStatus # Data Properties property :hasComponentID, :predicate => OMNlifecycle.hasComponentID, :type => RDF::XSD.anyURI property :resourceId, :predicate => OMNlifecycle.resourceId, :type => RDF::XSD.string property :hasVendorName, :predicate => SAMANTsensor.hasVendorName, :type => RDF::XSD.string property :hasProductName, :predicate => SAMANTsensor.hasProductName, :type => RDF::XSD.string property :hasSerial, :predicate => SAMANTsensor.hasSerial, :type => RDF::XSD.string property :hasID, :predicate => SAMANTsensor.hasID, :type => RDF::XSD.string property :hasDescription, :predicate => SAMANTsensor.hasDescription, :type => RDF::XSD.string property :consumesPower, :predicate => SAMANTuxv.consumesPower, :type => RDF::XSD.string end class FeatureOfInterest < Spira::Base configure :base_uri => SSN.FeatureOfInterest type RDF::URI.new("http://purl.oclc.org/NET/ssnx/ssn#FeatureOfInterest") # Object Properties has_many :hasProperty, :predicate => SSN.hassProperty, :type => :QuantityKind end class Water < FeatureOfInterest configure :base_uri => SAMANTsensor.Water type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Water") end class Air < FeatureOfInterest configure :base_uri => SAMANTsensor.Air type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Air") end class Ground < FeatureOfInterest configure :base_uri => SAMANTsensor.Ground type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Ground") end class AccelerationSensor < SensingDevice configure :base_uri => SAMANTsensor.AccelerationSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#AccelerationSensor") end class AngleSensor < SensingDevice configure :base_uri => SAMANTsensor.AngleSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#AngleSensor") end class CapacitanceSensor < SensingDevice configure :base_uri => SAMANTsensor.CapacitanceSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#CapacitanceSensor") end class ConductanceSensor < SensingDevice configure :base_uri => SAMANTsensor.ConductanceSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ConductanceSensor") end class ConcentrationSensor < SensingDevice configure :base_uri => SAMANTsensor.ConcentrationSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ConcentrationSensor") end class DistanceSensor < SensingDevice configure :base_uri => SAMANTsensor.DistanceSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#DistanceSensor") end class DurationSensor < SensingDevice configure :base_uri => SAMANTsensor.DurationSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#DurationSensor") end class ElectricConductivitySensor < SensingDevice configure :base_uri => SAMANTsensor.ElectricConductivitySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ElectricConductivitySensor") end class ElectricCurrentRateSensor < SensingDevice configure :base_uri => SAMANTsensor.ElectricCurrentRateSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ElectricCurrentRateSensor") end class ElectricPotentialSensor < SensingDevice configure :base_uri => SAMANTsensor.ElectricPotentialSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ElectricPotentialSensor") end class ElectricResistanceSensor < SensingDevice configure :base_uri => SAMANTsensor.ElectricResistanceSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ElectricResistanceSensor") end class EnergySensor < SensingDevice configure :base_uri => SAMANTsensor.EnergySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#EnergySensor") end class GeolocationSensor < SensingDevice configure :base_uri => SAMANTsensor.GeolocationSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#GeolocationSensor") end class ForceSensor < SensingDevice configure :base_uri => SAMANTsensor.ForceSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ForceSensor") end class FrequencySensor < SensingDevice configure :base_uri => SAMANTsensor.FrequencySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#FrequencySensor") end class ImageSensor < SensingDevice configure :base_uri => SAMANTsensor.ImageSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ImageSensor") end class ImageSensor < SensingDevice configure :base_uri => SAMANTsensor.ImageSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ImageSensor") end class ImageSensor < SensingDevice configure :base_uri => SAMANTsensor.ImageSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ImageSensor") end class MassSensor < SensingDevice configure :base_uri => SAMANTsensor.MassSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#MassSensor") end class PowerSensor < SensingDevice configure :base_uri => SAMANTsensor.PowerSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#PowerSensor") end class RotationalSpeedSensor < SensingDevice configure :base_uri => SAMANTsensor.RotationalSpeedSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#RotationalSpeedSensor") end class InformationDataSensor < SensingDevice configure :base_uri => SAMANTsensor.InformationDataSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#InformationDataSensor") end class TurbiditySensor < SensingDevice configure :base_uri => SAMANTsensor.TurbiditySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#TurbiditySensor") end class SalinitySensor < SensingDevice configure :base_uri => SAMANTsensor.SalinitySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#SalinitySensor") end class StressOrPressureSensor < SensingDevice configure :base_uri => SAMANTsensor.StressOrPressureSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#StressOrPressureSensor") end class TemperatureSensor < SensingDevice configure :base_uri => SAMANTsensor.TemperatureSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#TemperatureSensor") end class VelocityorSpeedSensor < SensingDevice configure :base_uri => SAMANTsensor.VelocityorSpeedSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#VelocityorSpeedSensor") end class VolumeSensor < SensingDevice configure :base_uri => SAMANTsensor.VolumeSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#VolumeSensor") end class ConductivitySensor < SensingDevice configure :base_uri => SAMANTsensor.ConductivitySensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ConductivitySensor") end class SoundSensor < SensingDevice configure :base_uri => SAMANTsensor.SoundSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#SoundSensor") end class SoundSpeedSensor < VelocityorSpeedSensor configure :base_uri => SAMANTsensor.SoundSpeedSensor type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#SoundSpeedSensor") end class SimpleQuantityKind < QuantityKind configure :base_uri => QU.SimpleQuantityKind type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/qu#SimpleQuantityKind") end class Conductance < QuantityKind configure :base_uri => DIM.Conductance type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Conductance") end class ConductanceUnit < Unit configure :base_uri => DIM.ConductanceUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConductanceUnit") end class Salinity < SimpleQuantityKind configure :base_uri => SAMANTsensor.Salinity type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Salinity") end class Air < FeatureOfInterest configure :base_uri => SAMANTsensor.Air type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Air") end class Ground < FeatureOfInterest configure :base_uri => SAMANTsensor.Ground type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Ground") end ######################### # Magnitudes and Units ######################### class Acceleration < QuantityKind configure :base_uri => DIM.Acceleration type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Acceleration") end class AccelerationUnit < Unit configure :base_uri => DIM.AccelerationUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AccelerationUnit") end class Angle < QuantityKind configure :base_uri => DIM.Angle type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Angle") end class AngleUnit < Unit configure :base_uri => DIM.AngleUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AngleUnit") end class Capacitance < QuantityKind configure :base_uri => DIM.Capacitance type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Capacitance") end class CapacitanceUnit < Unit configure :base_uri => DIM.CapacitanceUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#CapacitanceUnit") end class Concentration < QuantityKind configure :base_uri => DIM.Concentration type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Concentration") end class ConcentrationUnit < Unit configure :base_uri => DIM.ConcentrationUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConcentrationUnit") end class Dimensionless < QuantityKind configure :base_uri => DIM.Dimensionless type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Dimensionless") end class DimensionlessUnit < Unit configure :base_uri => DIM.DimensionlessUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DimensionlessUnit") end class Distance < QuantityKind configure :base_uri => DIM.Distance type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Distance") end class DistanceUnit < Unit configure :base_uri => DIM.DistanceUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DistanceUnit") end class Duration < QuantityKind configure :base_uri => DIM.Duration type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Duration") end class DurationUnit < Unit configure :base_uri => DIM.DurationUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DurationUnit") end class ElectricConductivity < QuantityKind configure :base_uri => DIM.ElectricConductivity type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricConductivity") end class ElectricConductivityUnit < Unit configure :base_uri => DIM.ElectricConductivityUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricConductivityUnit") end class ElectricCurrentRate < QuantityKind configure :base_uri => DIM.ElectricCurrentRate type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricCurrentRate") end class ElectricCurrentRateUnit < Unit configure :base_uri => DIM.ElectricCurrentRateUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricCurrentRateUnit") end class ElectricPotential < QuantityKind configure :base_uri => DIM.ElectricPotential type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricPotential") end class ElectricPotentialUnit < Unit configure :base_uri => DIM.ElectricPotentialUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricPotentialUnit") end class ElectricResistance < QuantityKind configure :base_uri => DIM.ElectricResistance type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricResistance") end class ElectricResistanceUnit < Unit configure :base_uri => DIM.ElectricResistanceUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricResistanceUnit") end class Energy < QuantityKind configure :base_uri => DIM.Energy type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Energy") end class EnergyUnit < Unit configure :base_uri => DIM.EnergyUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#EnergyUnit") end class Force < QuantityKind configure :base_uri => DIM.Force type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Force") end class ForceUnit < Unit configure :base_uri => DIM.ForceUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ForceUnit") end class Frequency < QuantityKind configure :base_uri => DIM.Frequency type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Frequency") end class FrequencyUnit < Unit configure :base_uri => DIM.FrequencyUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#FrequencyUnit") end class Geolocation < QuantityKind configure :base_uri => DIM.Geolocation type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Geolocation") end class GeolocationUnit < Unit configure :base_uri => DIM.GeolocationUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#GeolocationUnit") end class MagneticFluxDensity < QuantityKind configure :base_uri => DIM.MagneticFluxDensity type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MagneticFluxDensity") end class MagneticFluxDensityUnit < Unit configure :base_uri => DIM.MagneticFluxDensityUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MagneticFluxDensityUnit") end class InformationData < SimpleQuantityKind configure :base_uri => SAMANTsensor.InformationData type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#InformationData") end class InformationDataUnit < Unit configure :base_uri => SAMANTsensor.InformationDataUnit type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#InformationDataUnit") end class Power < SimpleQuantityKind configure :base_uri => SAMANTsensor.Power type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Power") end class PowerUnit < Unit configure :base_uri => SAMANTsensor.PowerUnit type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#PowerUnit") end class LevelOfAFieldQuantity < QuantityKind configure :base_uri => DIM.LevelOfAFieldQuantity type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#LevelOfAFieldQuantity") end class LevelOfAFieldQuantityUnit < Unit configure :base_uri => DIM.LevelOfAFieldQuantityUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#LevelOfAFieldQuantityUnit") end class Mass < QuantityKind configure :base_uri => DIM.Mass type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Mass") end class MassUnit < Unit configure :base_uri => DIM.MassUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MassUnit") end class Image < QuantityKind configure :base_uri => DIM.Image type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Image") end class ImageUnit < Unit configure :base_uri => DIM.ImageUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ImageUnit") end class RotationalSpeed < QuantityKind configure :base_uri => DIM.RotationalSpeed type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#RotationalSpeed") end class RotationalSpeedUnit < Unit configure :base_uri => DIM.RotationalSpeedUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#RotationalSpeedUnit") end class StressOrPressure < QuantityKind configure :base_uri => DIM.StressOrPressure type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#StressOrPressure") end class StressOrPressureUnit < Unit configure :base_uri => DIM.StressOrPressureUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#StressOrPressureUnit") end class Turbidity < SimpleQuantityKind configure :base_uri => SAMANTsensor.Turbidity type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#Turbidity") end class TurbidityUnit < Unit configure :base_uri => SAMANTsensor.TurbidityUnit type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#TurbidityUnit") end class SalinityUnit < Unit configure :base_uri => SAMANTsensor.SalinityUnit type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#SalinityUnit") end class Temperature < QuantityKind configure :base_uri => DIM.Temperature type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Temperature") end class TemperatureUnit < Unit configure :base_uri => DIM.TemperatureUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#TemperatureUnit") end class VelocityOrSpeed < QuantityKind configure :base_uri => DIM.VelocityOrSpeed type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#VelocityOrSpeed") end class VelocityOrSpeedUnit < Unit configure :base_uri => DIM.VelocityOrSpeedUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#VelocityOrSpeedUnit") end class Volume < QuantityKind configure :base_uri => DIM.Volume type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#Volume") end class VolumeUnit < Unit configure :base_uri => DIM.VolumeUnit type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#VolumeUnit") end ############### # Individuals ############### class MetrePerSecondSquared < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#metrePerSecondSquared" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AccelerationUnit") end class Radian < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#radian" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AngleUnit") end class DegreeUnitOfAngle < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#degreeUnitOfAngle" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AngleUnit") end class SecondUnitOfAngle < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#secondUnitOfAngle" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AngleUnit") end class MinuteUnitOfAngle < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#minuteUnitOfAngle" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#AngleUnit") end class Percent < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#percent" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DimensionlessUnit") end class PartsPerMillion < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#partsPerMillion" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConcentrationUnit") end class PartsPerBillion < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#partsPerBillion" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConcentrationUnit") end class Ph < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#pH" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConcentrationUnit") end class MolePerLitre < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#molePerLitre" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConcentrationUnit") end class Metre < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#metre" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DistanceUnit") end class SecondUnitOfTime < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#secondUnitOfTime" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#DurationUnit") end class SiemensPerMetre < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#siemensPerMetre" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricConductivityUnit") end class Siemens < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#siemens" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ConductanceUnit") end class Ampere < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#ampere" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricCurrentRateUnit") end # TODO check if case sensitive e.g. Volt or volt class Volt < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#volt" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ElectricPotentialUnit") end class Newton < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#newton" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#ForceUnit") end class Hertz < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#hertz" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#FrequencyUnit") end class Bit < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#bit" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#InformationDataUnit") end class Byte < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#byte" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#InformationDataUnit") end class Pixel < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#pixel" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ImageUnit") end class Decibel < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#decibel" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#LevelOfAFieldQuantityUnit") end class Kilogram < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#kilogram" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MassUnit") end class DegreePerSecond < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#degreePerSecond" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#RotationalSpeedUnit") end class RadianPerSecond < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#radianPerSecond" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#RotationalSpeedUnit") end class RotationPerMinute < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#rotationPerMinute" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#RotationalSpeedUnit") end class Psu < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#psu" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#SalinityUnit") end class Pascal < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#pascal" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#StressOrPressureUnit") end class Millibar < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#millibar" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#StressOrPressureUnit") end class Kelvin < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#kelvin" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#TemperatureUnit") end class DegreeCelsius < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#degreeCelsius" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#TemperatureUnit") end class Gauss < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#gauss" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MagneticFluxDensityUnit") end class Tesla < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#tesla" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#MagneticFluxDensityUnit") end class Ntu < Spira::Base configure :base_uri => "http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#ntu" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#TurbidityUnit") end class MetrePerSecond < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/unit#metrePerSecond" type RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#VelocityOrSpeedUnit") end class AtmosphericPressure < Spira::Base configure :base_uri => "http://purl.oclc.org/NET/ssnx/qu/quantity#atmosphericPressure" type RDF::URI.new("http://purl.oclc.org/NET/ssnx/qu/dim#StressOrPressure") end METERPERSECONDSQUARED = MetrePerSecondSquared.for("").save! RADIAN = Radian.for("").save! DEGREEUNITOFANGLE = DegreeUnitOfAngle.for("").save! SECONDUNITOFANGLE = SecondUnitOfAngle.for("").save! MINUTEUNITOFANGLE = MinuteUnitOfAngle.for("").save! PERCENT = Percent.for("").save! PARTSPERMILLION = PartsPerMillion.for("").save! PARTSPERBILLION = PartsPerBillion.for("").save! PH = Ph.for("").save! MOLEPERLITRE = MolePerLitre.for("").save! METRE = Metre.for("").save! SECONDUNITOFTIME = SecondUnitOfTime.for("").save! SIEMENSPERMETRE = SiemensPerMetre.for("").save! SIEMENS = Siemens.for("").save! AMPERE = Ampere.for("").save! VOLT = Volt.for("").save! NEWTON = Newton.for("").save! HERTZ = Hertz.for("").save! BIT = Bit.for("").save! BYTE = Byte.for("").save! PIXEL = Pixel.for("").save! KILOGRAM = Kilogram.for("").save! DECIBEL = Decibel.for("").save! RADIANPERSECOND = RadianPerSecond.for("").save! DEGREEPERSECOND = DegreePerSecond.for("").save! ROTATIONPERMINUTE = RotationPerMinute.for("").save! PSU = Psu.for("").save! PASCAL = Pascal.for("").save! MILLIBAR = Millibar.for("").save! KELVIN = Kelvin.for("").save! DEGREECELSIUS = DegreeCelsius.for("").save! NTU = Ntu.for("").save! METREPERSECOND = MetrePerSecond.for("").save! GROUND = Ground.for("") AIR = Air.for("") WATER = Water.for("") GEOLOCATION = Geolocation.for("").save! ATMOSPHERICPRESSURE = AtmosphericPressure.for("").save! ROTATIONALSPEED = RotationalSpeed.for("").save! ACCELERATION = Acceleration.for("").save! MAGNETICFLUXDENSITY = MagneticFluxDensity.for("").save! IMAGE = Image.for("").save! TEMPERATURE = Temperature.for("").save! CONCENTRATION = Concentration.for("").save! CONDUCTANCE = Conductance.for("").save! end<file_sep>require 'spira' require 'rdf/turtle' require 'rdf/json' require 'sparql/client' #require 'sparql' module Semantic # Preload ontology # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### #exw metaferei polla apo Lifecycle stin OMN class Action < State configure :base_uri => OmnLifecycle.Action type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Action') end class Active < State configure :base_uri => OmnLifecycle.Active type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Active') end class Allocated < ReservationState configure :base_uri => OmnLifecycle.Allocated type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Allocated') end class Cleaned < State configure :base_uri => OmnLifecycle.Cleaned type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Cleaned') end class Confirmation < Topology configure :base_uri => OmnLifecycle.Confirmation type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Confirmation') end class Error < State configure :base_uri => OmnLifecycle.Error type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Error') end class Failure < State configure :base_uri => OmnLifecycle.Failure type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Failure') end class Initialized < State configure :base_uri => OmnLifecycle.Initialized type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Initialized') end class Installed < State configure :base_uri => OmnLifecycle.Installed type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Installed') end class Lease < Reservation configure :base_uri => OmnLifecycle.Lease type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Lease') end class Manifest < Topology configure :base_uri => OmnLifecycle.Manifest type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Manifest') end class Nascent < State configure :base_uri => OmnLifecycle.Nascent type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Nascent') end class NotReady < State configure :base_uri => OmnLifecycle.NotReady type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#NotReady') end class NotYetInitialized < State configure :base_uri => OmnLifecycle.NotYetInitialized type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#NotYetInitialized') end class Offering < Topology configure :base_uri => OmnLifecycle.Offering type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Offering') end class Opstate < Resource configure :base_uri => OmnLifecycle.Opstate type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Opstate') # Object Properties has_many :hasStartState, :predicate => OmnLifecycle.hasStartState, :type => :State end class Pending < State configure :base_uri => OmnLifecycle.Pending type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Pending') end class Preinit < State configure :base_uri => OmnLifecycle.Preinit type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Preinit') end class Unknown < State configure :base_uri => OmnLifecycle.Unknown type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Unknown') end class Provisioned < State configure :base_uri => OmnLifecycle.Provisioned type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Provisioned') end class Ready < State configure :base_uri => OmnLifecycle.Ready type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Ready') end class Removing < State configure :base_uri => OmnLifecycle.Removing type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Removing') end class Request < Topology configure :base_uri => OmnLifecycle.Request type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Request') end class Success < State configure :base_uri => OmnLifecycle.Success type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Success') end class Restart < State configure :base_uri => OmnLifecycle.Restart type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Restart') end class Start < State configure :base_uri => OmnLifecycle.Start type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Start') end class Started < State configure :base_uri => OmnLifecycle.Started type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Started') end class Stop < State configure :base_uri => OmnLifecycle.Stop type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Stop') end class Stopped < State configure :base_uri => OmnLifecycle.Stopped type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Stopped') end class Stopping < State configure :base_uri => OmnLifecycle.Stopping type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Stopping') end class Unallocated < ReservationState configure :base_uri => OmnLifecycle.Unallocated type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Unallocated') end class Reload < State configure :base_uri => OmnLifecycle.Reload type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Reload') end class UpdatingUsers < State configure :base_uri => OmnLifecycle.UpdatingUsers type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#UpdatingUsers') end class UpdateUsersCancel < State configure :base_uri => OmnLifecycle.UpdateUsersCancel type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#UpdateUsersCancel') end class UpdateUsers < State configure :base_uri => OmnLifecycle.UpdateUsers type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#UpdateUsers') end class Uncompleted < State configure :base_uri => OmnLifecycle.Uncompleted type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Uncompleted') end class Updating < State configure :base_uri => OmnLifecycle.Updating type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Updating') end class Wait < State configure :base_uri => OmnLifecycle.Wait type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#Wait') end end<file_sep>require 'omf-sfa/am/am-rest/rest_handler' require 'omf-sfa/am/am_manager' require 'uuid' require 'json/ld' require_relative '../../omn-models/resource.rb' #require_relative '../../omn-models/populator.rb' module OMF::SFA::AM::Rest # Handles an individual resource # class ResourceHandler < RestHandler # Return the handler responsible for requests to +path+. # The default is 'self', but override if someone else # should take care of it # def find_handler(path, opts) #opts[:account] = @am_manager.get_default_account opts[:resource_uri] = path.join('/') if path.size == 0 || path.size == 1 debug "find_handler: path: '#{path}' opts: '#{opts.inspect}'" return self elsif path.size == 3 #/resources/type1/UUID/type2 px opts[:source_resource_uri] = path[0] opts[:source_resource_uuid] = path[1] opts[:target_resource_uri] = path[2] raise OMF::SFA::AM::Rest::BadRequestException.new "'#{opts[:source_resource_uuid]}' is not a valid UUID." unless UUID.validate(opts[:source_resource_uuid]) require 'omf-sfa/am/am-rest/resource_association_handler' return OMF::SFA::AM::Rest::ResourceAssociationHandler.new(@am_manager, opts) else raise OMF::SFA::AM::Rest::BadRequestException.new "Invalid URL." end end # List a resource # # @param [String] request URI # @param [Hash] options of the request # @return [String] Description of the requested resource. def on_get(resource_uri, opts) # resource uri px "locations", "nodes" klp debug "on_get: #{resource_uri}" authenticator = opts[:req].session[:authorizer] unless resource_uri.empty? # an exeis zitisei resource me sugkekrimeno uri resource_type, resource_params = parse_uri(resource_uri, opts) # gurnaei type kai parameters if resource_uri == 'leases' # leases, eidiki metaxeirisi status_types = ["pending", "accepted", "active"] # default value status_types = resource_params[:status].split(',') unless resource_params[:status].nil? acc_desc = {} acc_desc[:urn] = resource_params.delete(:account_urn) if resource_params[:account_urn] acc_desc[:uuid] = resource_params.delete(:account_uuid) if resource_params[:account_uuid] account = @am_manager.find_account(acc_desc, authenticator) unless acc_desc.empty? resource = @am_manager.find_all_leases(account, status_types, authenticator) # gurnaei ena pinaka me ola ta leases return show_resource(resource, opts) # xml/json analoga me ta opts end descr = {} descr.merge!(resource_params) unless resource_params.empty? opts[:path] = opts[:req].path.split('/')[0 .. -2].join('/') descr[:account_id] = @am_manager.get_scheduler.get_nil_account.id if eval("OMF::SFA::Model::#{resource_type}").can_be_managed? && !@opts[:semantic] if descr[:name].nil? && descr[:uuid].nil? resource = @am_manager.find_all_resources(descr, resource_type, authenticator, @opts[:semantic]) else resource = @am_manager.find_resource(descr, resource_type, authenticator, @opts[:semantic]) end return show_resource(resource, opts) else # an exeis keno uri, opote ta 8es ola debug "list all resources." resource = @am_manager.find_all_resources_for_account(opts[:account], @opts[:semantic], authenticator) end raise UnknownResourceException, "No resources matching the request." if resource.empty? show_resource(resource, opts) end # Update an existing resource # # @param [String] request URI # @param [Hash] options of the request # @return [String] Description of the updated resource. def on_put(resource_uri, opts) debug "on_put: #{resource_uri}" resource = update_resource(resource_uri, true, opts) show_resource(resource, opts) end # Create a new resource # # @param [String] request URI # @param [Hash] options of the request # @return [String] Description of the created resource. def on_post(resource_uri, opts) # resource_uri = Nodes debug "on_post: #{resource_uri}" resource = update_resource(resource_uri, false, opts) show_resource(resource, opts) end # Deletes an existing resource # # @param [String] request URI # @param [Hash] options of the request # @return [String] Description of the created resource. def on_delete(resource_uri, opts) debug "on_delete: #{resource_uri}" delete_resource(resource_uri, opts) show_resource(nil, opts) # epistrefei ena sketo "OK" end # Update resource(s) referred to by +resource_uri+. If +clean_state+ is # true, reset any other state to it's default. # def update_resource(resource_uri, clean_state, opts) body, format = parse_body(opts) # parsarei ta dosmena opts eite einai xml eite json, epistrefei array of hashes resource_type, resource_params = parse_uri(resource_uri, opts) # parsarei ton tupo twn dedomenwn authenticator = opts[:req].session[:authorizer] case format # when :empty # # do nothing when :xml resource = @am_manager.update_resources_from_xml(body.root, clean_state, opts) # den exei ginei kalo implement se auton ton tomea when :json if clean_state resource = update_a_resource(body, resource_type, authenticator) # clean state = true mpainei edw else resource = create_new_resource(body, resource_type, authenticator) # clean state = false kanei create end else raise UnsupportedBodyFormatException.new(format) end resource end # This methods deletes components, or more broadly defined, removes them # from a slice. # # Currently, we simply transfer components to the +default_sliver+ # def delete_resource(resource_uri, opts) body, format = parse_body(opts) resource_type, resource_params = parse_uri(resource_uri, opts) authenticator = opts[:req].session[:authorizer] release_resource(body, resource_type, authenticator) end # Update the state of +component+ according to inforamtion # in the http +req+. # # def update_component_xml(component, modifier_el, opts) end # Return the state of +component+ # # +component+ - Component to display information about. !!! Can be nil - show only envelope # def show_resource(resource, opts) debug "i m in show resource" unless about = opts[:req].path throw "Missing 'path' declaration in request" end path = opts[:path] || about case opts[:format] when 'xml' show_resources_xml(resource, path, opts) when 'ttl' self.class.omn_response_json(resource, opts) else show_resources_json(resource, path, opts) end end def show_resources_xml(resource, path, opts) #debug "show_resources_xml: #{resource}" opts[:href_prefix] = path announcement = OMF::SFA::Model::OComponent.sfa_advertisement_xml(resource, opts) ['text/xml', announcement.to_xml] end def show_resources_json(resources, path, opts) res = resources ? resource_to_json(resources, path, opts) : {response: "OK"} #TODO removed (temporary) for HAI integration #res[:about] = opts[:req].path ['application/json', JSON.pretty_generate({:resource_response => res}, :for_rest => true)] end ### self.tade, alliws einai instance method. emeis tin theloume class method def self.omn_response_json(resources, opts) debug "Generating OMN (json) response" jsonLDserializer(resources, opts) end def self.jsonLDserializer(resources, opts) #debug "resources " + resources.inspect sparql = SPARQL::Client.new($repository) res = [] if resources.kind_of?(Array) res_ary = resources else res_ary = [resources] end res_ary.delete_if {|res| res.nil? } res_ary.each { |resource| query_graph = [] s = resource.to_uri s_stripped = RDF::URI.new(s.to_s.split('/').shift) # debug "stripped: " + s_stripped query_graph << sparql.construct([s_stripped, :p, :o]) .where([s, :p, :o]) .filter("?p != <http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#hasChild>") # do not show hasChild predicates .filter("?p != <http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#hasParent>") # do not show hasParent predicates .filter("!regex (str(?o), \"leased@\")") .filter("?p != <http://open-multinet.info/ontology/omn-lifecycle#hasLease>") # treat leases specifically, beneath query_graph << sparql.construct([s_stripped, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasLease"), :o]) .where([s, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasLease"), :o], [:o, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasReservationState"), :rs]) .filter("?rs != <http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Cancelled/>") # filter out this kind of leases .filter("?rs != <http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Pending/>") .filter("?rs != <http://open-multinet.info/ontology/omn-lifecycle#Unallocated/>") output = JSON::LD::Writer.buffer do |writer| query_graph.collect { |q| writer << q } end res << ::JSON.parse(output)# apo JSON se hash, gia na ginei swsto merge } raise UnknownResourceException, "No resources matching the request." if res.empty? #TODO removed (temporary) for HAI integration #res << {:about => opts[:req].path} res end # Creates the omn-rspec # currently works only for advertisement (offering) rspecs def self.rspecker(resources, type) debug "resources " + resources.inspect timestamp = Time.now.getutc sparql = SPARQL::Client.new($repository) uuid = ("urn:uuid:" + SecureRandom.uuid).to_sym # Rspec urn rtype_g = [RDF::URI.new(uuid), RDF::URI.new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#"+type.to_s)] rlabel_g = [RDF::URI.new(uuid), RDF::URI.new("http://www.w3.org/2000/01/rdf-schema#label"), type.to_s] global_writer = [] global_writer << rlabel_g << rtype_g resources.delete_if {|res| res.nil? } resources.collect { |rsc| # Each UxV !MUST! provide the exact following two Hardware Types: hw1 = ("urn:uuid:" + SecureRandom.uuid).to_sym # UxV Hardware Type urn hw2 = ("urn:uuid:" + SecureRandom.uuid).to_sym # Sensor Hardware Type urn #puts rsc.to_uri rsc_uri = rsc.to_uri if (rsc.kind_of?SAMANT::Uxv) && rsc.hasParent resource_fix = rsc.hasParent.to_uri else resource_fix = rsc_uri end #debug "rsc = " + rsc.to_s #debug "rsc_uri = " + rsc_uri.to_s # Leases global_writer << sparql .construct([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Lease")], [RDF::URI.new(uuid), RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasLease"), rsc_uri]) .where([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Lease")]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#expirationTime"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#expirationTime"), :o]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#startTime"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#startTime"), :o]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasID"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasID"), :o]) if type == :Manifest global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasSliceID"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasSliceID"), :o]) end # Nodes global_writer << sparql .construct([resource_fix, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#Node")], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#isExclusive"), true], [RDF::URI.new(uuid), RDF::URI.new("http://open-multinet.info/ontology/omn#hasResource"), resource_fix], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn#isResourceOf"), RDF::URI.new(uuid)], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#hasHardwareType"), RDF::URI.new(hw1)], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#managedBy"), RDF::URI.new("urn:uuid:DUMMY_AUTHORITY")], [RDF::URI.new("urn:uuid:DUMMY_AUTHORITY"), RDF::URI.new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), RDF::URI.new("http://open-multinet.info/ontology/omn-domain-geni-fire#AMService")]) .where([rsc_uri, :p, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UxV")]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://www.w3.org/2000/01/rdf-schema#label"), :o], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasComponentName"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#resourceId"), :o]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#isAvailable"), true]) .where([rsc_uri, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#hasResourceStatus"), RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Released/")]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#isAvailable"), false]) .where([rsc_uri, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#hasResourceStatus"), RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Booked/")]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#isAvailable"), false]) .where([rsc_uri, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#hasResourceStatus"), RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#SleepMode/")]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#hasInterface"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#hasInterface"), :o]) unless type == :Manifest global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#hasLocation"), :o]) .where([rsc_uri, RDF::URI.new("http://www.georss.org/georss/where"), :o]) global_writer << sparql .construct([resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasLease"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasLease"), :l], [:l, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#Allocated/")], [:l, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasID"), :o]) end # Interfaces unless type == :Manifest global_writer << sparql .construct([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#Interface")]) .where([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#WiredInterface")]) global_writer << sparql .construct([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#Interface")]) .where([rsc_uri, :p, RDF::URI.new("http://open-multinet.info/ontology/omn-domain-wireless#WirelessInterface")]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasComponentID"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasComponentID"), :o]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasComponentName"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasComponentName"), :o]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasRole"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#hasRole"), :o],) end # Hardware Types global_writer << sparql .construct([RDF::URI.new(hw1), RDF::URI.new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), RDF::URI.new("http://open-multinet.info/ontology/omn-resource#HardwareType")], [RDF::URI.new(hw1), RDF::URI.new("http://www.w3.org/2000/01/rdf-schema#label"), :o]) .where([rsc_uri, RDF::URI.new("http://open-multinet.info/ontology/omn-lifecycle#resourceId"), :o], [rsc_uri, :p, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UxV")]) if (rsc.kind_of?SAMANT::Uxv) && rsc.hasSensorSystem global_writer << sparql .construct([RDF::URI.new(hw2), RDF::URI.new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), RDF::URI.new("http://open-multinet.info/ontology/omn-resource#HardwareType")], [RDF::URI.new(hw2), RDF::URI.new("http://www.w3.org/2000/01/rdf-schema#label"), :o], [resource_fix, RDF::URI.new("http://open-multinet.info/ontology/omn-resource#hasHardwareType"), RDF::URI.new(hw2)] ) .where([rsc_uri, :p, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#UxV")], [rsc_uri, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#hasSensorSystem"), :s], [:s, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-sensor#hasID"), :o] ) end # Locations global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), RDF::URI.new("http://open-multinet.info/ontology/omn-resource#Location")], [rsc_uri, RDF::URI.new("http://www.geonames.org/ontology#countryCode"), "DUMMY_COUNTRYCODE"]) .where([rsc_uri, :p, RDF::URI.new("http://www.semanticweb.org/rawfie/samant/omn-domain-uxv#Point3D")]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://www.w3.org/2003/01/geo/wgs84_pos#lat"), :o]) .where([rsc_uri, RDF::URI.new("http://www.w3.org/2003/01/geo/wgs84_pos#lat"), :o]) global_writer << sparql .construct([rsc_uri, RDF::URI.new("http://www.w3.org/2003/01/geo/wgs84_pos#long"), :o]) .where([rsc_uri, RDF::URI.new("http://www.w3.org/2003/01/geo/wgs84_pos#long"), :o]) #debug "is it array? " + global_writer.kind_of?(Array).to_s } if type == :Offering filename = "ready4translation/advRSpec@#{timestamp}.ttl".delete(' ') else filename = "ready4translation/mnfRSpec@#{timestamp}.ttl".delete(' ') end RDF::Turtle::Writer.open(filename) do |writer| global_writer.collect { |g| writer << g } end return filename end def resource_to_json(resource, path, opts, already_described = {}) debug "resource_to_json: resource: #{resource.inspect}, path: #{path}" if resource.kind_of? Enumerable res = [] resource.each do |r| p = path res << resource_to_json(r, p, opts, already_described)[:resource] end res = {:resources => res} # hash else #prefix = path.split('/')[0 .. -2].join('/') # + '/' prefix = path if resource.respond_to? :to_sfa_hashXXX debug "TO_SFA_HASH: #{resource}" res = {:resource => resource.to_sfa_hash(already_described, :href_prefix => prefix)} else rh = resource.to_hash # unless (account = resource.account) == @am_manager.get_default_account() # rh[:account] = {:uuid => account.uuid.to_s, :name => account.name} # end res = {:resource => rh} end end res end protected def parse_uri(resource_uri, opts) params = opts[:req].params.symbolize_keys! params.delete("account") return ['mapper', params] if opts[:req].env["REQUEST_PATH"] == '/mapper' case resource_uri when "cmc" type = "ChasisManagerCard" when "wimax" type = "WimaxBaseStation" when "lte" type = "ENodeB" when "openflow" type = "OpenflowSwitch" else type = resource_uri.singularize.camelize # to kanei eniko, kefalaio prwto, diwxnei underscores begin eval("OMF::SFA::Model::#{type}").class rescue NameError => ex raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown resource type '#{resource_uri}'." end end debug "parse uri " + type [type, params] end # Create a new resource # # @param [Hash] Describing properties of the requested resource # @param [String] Type to create # @param [Authorizer] Defines context for authorization decisions # @return [OResource] The resource created # @raise [UnknownResourceException] if no resource can be created # def create_new_resource(resource_descr, type_to_create, authorizer) debug "create_new_resource: resource_descr: #{resource_descr}, type_to_create: #{type_to_create}" authorizer.can_create_resource?(resource_descr, type_to_create) if type_to_create == "Lease" #Lease is a unigue case, needs special treatment raise OMF::SFA::AM::Rest::BadRequestException.new "Attribute account is mandatory." if resource_descr[:account].nil? && resource_descr[:account_attributes].nil? raise OMF::SFA::AM::Rest::BadRequestException.new "Attribute components is mandatory." if (resource_descr[:components].nil? || resource_descr[:components].empty?) && (resource_descr[:components_attributes].nil? || resource_descr[:components_attributes].empty?) raise OMF::SFA::AM::Rest::BadRequestException.new "Attributes valid_from and valid_until are mandatory." if resource_descr[:valid_from].nil? || resource_descr[:valid_until].nil? res_descr = {} # praktika ena hash/antigrafo tou resource description, me kapoia epipleon res_descr[:name] = resource_descr[:name] res_descr[:valid_from] = resource_descr[:valid_from] res_descr[:valid_until] = resource_descr[:valid_until] ac_desc = resource_descr[:account] || resource_descr[:account_attributes] # praktika simainei opoio ap ta 2 uparxei ac = OMF::SFA::Model::Account.first(ac_desc) raise OMF::SFA::AM::Rest::UnknownResourceException.new "Account with description '#{ac_desc}' does not exist." if ac.nil? raise OMF::SFA::AM::Rest::NotAuthorizedException.new "Account with description '#{ac_desc}' is closed." unless ac.active? res_descr[:account_id] = ac.id lease = @am_manager.find_or_create_lease(res_descr, authorizer) # Return the lease described by +lease_descr+. Create if it doesn't exist. comps = resource_descr[:components] || resource_descr[:components_attributes] nil_account_id = @am_manager._get_nil_account.id # default account, admin account components = [] comps.each do |c| desc = {} desc[:account_id] = nil_account_id desc[:uuid] = c[:uuid] unless c[:uuid].nil? desc[:name] = c[:name] unless c[:name].nil? if k = OMF::SFA::Model::Resource.first(desc) components << k #vres to component me to tade uuid h name (analoga ti exei do8ei) kai valto ston pinaka components end end scheduler = @am_manager.get_scheduler comps = [] components.each do |comp| comps << c = scheduler.create_child_resource({uuid: comp.uuid, account_id: ac.id}, comp[:type].to_s.split('::').last) unless scheduler.lease_component(lease, c) scheduler.delete_lease(lease) @am_manager.release_resources(comps, authorizer) # kanei destroy ta resources raise NotAuthorizedException.new "Reservation for the resource '#{c.name}' failed. The resource is either unavailable or a policy quota has been exceeded." end end resource = lease else if resource_descr.kind_of? Array descr = [] resource_descr.each do |res| res_descr = {} res_descr.merge!({uuid: res[:uuid]}) if res.has_key?(:uuid) # an sto hash uparxei kleisi "uuid" res_descr.merge!({name: res[:name]}) if res.has_key?(:name) # ftiaxnei ena hashaki me to uuid kai to name kai to vazei ston pinaka descr descr << res_descr unless eval("OMF::SFA::Model::#{type_to_create}").first(res_descr) # ektos an uparxei hdh end # elegxei an ta resources uparxoun raise OMF::SFA::AM::Rest::BadRequestException.new "No resources described in description #{resource_descr} is valid. Maybe all the resources alreadt=y exist." if descr.empty? elsif resource_descr.kind_of? Hash descr = {} descr.merge!({uuid: resource_descr[:uuid]}) if resource_descr.has_key?(:uuid) descr.merge!({name: resource_descr[:name]}) if resource_descr.has_key?(:name) if descr.empty? raise OMF::SFA::AM::Rest::BadRequestException.new "Resource description is '#{resource_descr}'." else raise OMF::SFA::AM::Rest::BadRequestException.new "Resource with descr '#{descr} already exists'." if eval("OMF::SFA::Model::#{type_to_create}").first(descr) end end if resource_descr.kind_of? Array # logika an exeis dosei polla resources resource = [] resource_descr.each do |res_desc| resource << eval("OMF::SFA::Model::#{type_to_create}").create(res_desc) @am_manager.manage_resource(resource.last) if resource.last.account.nil? if type_to_create == 'Account' @am_manager.liaison.create_account(resource.last) end end elsif resource_descr.kind_of? Hash # an exeis dwsei ena resource # EXW PEIRAKSEI if @opts[:semantic] debug "semantic creation" sparql = SPARQL::Client.new($repository) id = resource_descr[:name] resource_descr.delete(:name) res = eval("Semantic::#{type_to_create}").for(id, resource_descr) res.save! resource = sparql.construct([res.uri, :p, :o]).where([res.uri, :p, :o]) ############## else resource = eval("OMF::SFA::Model::#{type_to_create}").create(resource_descr) @am_manager.manage_resource(resource) if resource.class.can_be_managed? if type_to_create == 'Account' @am_manager.liaison.create_account(resource) end end end end resource end # Update a resource # # @param [Hash] Describing properties of the requested resource # @param [String] Type to create # @param [Authorizer] Defines context for authorization decisions # @return [OResource] The resource created # @raise [UnknownResourceException] if no resource can be created # def update_a_resource(resource_descr, type_to_create, authorizer) descr = {} descr.merge!({uuid: resource_descr[:uuid]}) if resource_descr.has_key?(:uuid) descr.merge!({name: resource_descr[:name]}) if descr[:uuid].nil? && resource_descr.has_key?(:name) # EXW PEIRAKSEI -> <NAME>, <NAME> if @opts[:semantic] debug "semantic UPDATE" sparql = SPARQL::Client.new($repository) id = resource_descr[:name] resource_descr.delete(:name) res = eval("Semantic::#{type_to_create}").for(id).update_attributes(resource_descr) return sparql.construct([res.uri, :p, :o]).where([res.uri, :p, :o]) ############## else debug "stoixeia: " + type_to_create.to_s + ", " + descr.inspect unless descr.empty? if resource = eval("OMF::SFA::Model::#{type_to_create}").first(descr) # prwta ferto, meta kanto update authorizer.can_modify_resource?(resource, type_to_create) resource.update(resource_descr) # to resource description exei parsaristei kai ginetai katallila to update sti vasi dedomenwn @am_manager.get_scheduler.update_lease_events_on_event_scheduler(resource) if type_to_create == 'Lease' # @am_manager.manage_resource(resource) else raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown resource with descr'#{resource_descr}'." end end end resource end # Release a resource # # @param [Hash] Describing properties of the requested resource # @param [String] Type to create # @param [Authorizer] Defines context for authorization decisions # @return [OResource] The resource created # @raise [UnknownResourceException] if no resource can be created # def release_resource(resource_descr, type_to_release, authorizer) if type_to_release == "Lease" #Lease is a unigue case, needs special treatment if resource = OMF::SFA::Model::Lease.first(resource_descr) @am_manager.release_lease(resource, authorizer) else raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown Lease with descr'#{resource_descr}'." end else # EXW PEIRAKSEI #### if @opts[:semantic] debug "semantic delete" #id = resource_descr[:name] resource = eval("Semantic::#{type_to_release}").for(resource_descr[:name]) debug resource.inspect resource.destroy ############## else authorizer.can_release_resource?(resource_descr) if resource = eval("OMF::SFA::Model::#{type_to_release}").first(resource_descr) if type_to_release == 'Account' @am_manager.liaison.close_account(resource) end resource.destroy else raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown resource with descr'#{resource_descr}'." end end end resource end # Before create a new resource, parse the resource description and alternate existing resources. # # @param [Hash] Resource Description # @return [Hash] New Resource Description # @raise [UnknownResourceException] if no resource can be created # def parse_resource_description(resource_descr, type_to_create) resource_descr.each do |key, value| debug "checking prop: '#{key}': '#{value}': '#{type_to_create}'" if value.kind_of? Array value.each_with_index do |v, i| if v.kind_of? Hash # debug "Array: #{v.inspect}" begin k = eval("OMF::SFA::Model::#{key.to_s.singularize.capitalize}").first(v) raise NameError if k.nil? resource_descr[key][i] = k rescue NameError => nex model = eval("OMF::SFA::Model::#{type_to_create}.get_oprops[key][:__type__]") resource_descr[key][i] = (k = eval("OMF::SFA::Model::#{model}").first(v)) ? k : v end end end elsif value.kind_of? Hash debug "Hash: #{key.inspect}: #{value.inspect}" begin k = eval("OMF::SFA::Model::#{key.to_s.singularize.capitalize}").first(value) raise NameError if k.nil? resource_descr[key] = k rescue NameError => nex model = eval("OMF::SFA::Model::#{type_to_create}.get_oprops[key][:__type__]") resource_descr[key] = (k = eval("OMF::SFA::Model::#{model}").first(value)) ? k : value end end end resource_descr end end # ResourceHandler end # module <file_sep>require 'spira' require 'rdf/turtle' require 'rdf/json' require 'sparql/client' #require 'sparql' module Semantic # Preload ontology OmnWireless = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn_wireless.owl#") OmnMonitoringUnit = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-monitoring-unit#") # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### class Prefix < Spira::Base #ELABORATE configure :base_uri => OmnMonitoringUnit.Prefix type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#Prefix') end class Feature < Spira::Base configure :base_uri => OmnWireless.Feature type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#Feature') end class Location < Spira::Base configure :base_uri => OmnWireless.Location type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#Location') end class DecimalPrefix < Prefix configure :base_uri => OmnMonitoringUnit.DecimalPrefix type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#DecimalPrefix') end class Antenna < Feature configure :base_uri => OmnWireless.Antenna type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#Antenna') end class AntennaBandSupport < Feature configure :base_uri => OmnWireless.AntennaBandSupport type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#AntennaBandSupport') end class AntennaType < Feature configure :base_uri => OmnWireless.AntennaType type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#AntennaType') end class Channel < Component configure :base_uri => OmnWireless.Channel type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#Channel') end #class Frequency < Feature # configure :base_uri => OmnWireless.Frequency # type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#Frequency') #end class MicroController < Component configure :base_uri => OmnWireless.MicroController type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#MicroController') end class Sensor < Component configure :base_uri => OmnWireless.Sensor type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#Sensor') end class SensorModule < Component configure :base_uri => OmnWireless.SensorModule type RDF::URI.new('http://open-multinet.info/ontology/omn-monitoring-unit#SensorModule') end class Standard < Feature configure :base_uri => OmnWireless.Standard type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#Standard') end class WiredInterface < Interface configure :base_uri => OmnWireless.WiredInterface type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#WiredInterface') end class WirelessInterface < Interface configure :base_uri => OmnWireless.WirelessInterface type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#WirelessInterface') # Object Properties has_many :hasAntenna, :predicate => OmnWireless.hasAntenna, :type => :Antenna has_many :hasAntennaBandSupport, :predicate => OmnWireless.hasAntennaBandSupport, :type => :AntennaBandSupport end class XyzCartesianCoordinate < Location configure :base_uri => OmnWireless.XyzCartesianCoordinate type RDF::URI.new('http://open-multinet.info/ontology/omn_wireless.owl#xyzCartesianCoordinate') end end <file_sep>require 'data_objects' require 'rdf/do' require 'do_sqlite3' require 'rdf/sesame' #$repository = Spira.repository = RDF::DataObjects::Repository.new uri: 'sqlite3:./test.db' #url = "http://127.0.0.1:8080/openrdf-sesame/repositories/remote/" url = "http://172.16.58.3:8080/openrdf-sesame/repositories/samRemoteClean" $repository = Spira.repository = RDF::Sesame::Repository.new(url) require_relative '../samant_models/sensor.rb' require_relative '../samant_models/uxv.rb' # Repopulate triplestore RDF::Util::Logger.logger.parent.level = 'off' #sliver1 = SAMANT::Lease.for('urn:publicid:IDN+omf:netmode+sliver+375525ca-12ee-468c-9dd3-23603a7165c9'.to_sym) #sliver1.hasReservationState = SAMANT::ALLOCATED #sliver1.startTime = Time.parse('2017-03-01T19:00:00Z') #sliver1.expirationTime = Time.parse('2017-03-02T20:00:00Z') #sliver1.hasID = 'urn:publicid:IDN+omf:netmode+sliver+375525ca-12ee-468c-9dd3-23603a7165c9' #sliver1.hasSliceID = 'urn:publicid:IDN+fed4fire:global:netmode1+slice+samant_test' #1111111111111111111111111 uav1MultiSensor = SAMANT::System.for('urn:uav1+multi+sensor'.to_sym) uav1MultiSensor.hasID = 'UaV1MS345' uav1MultiSensor.save ifr1 = SAMANT::WiredInterface.for('urn:uuid:interface+1+wired+uav1:eth0'.to_sym) ifr1.hasComponentID = 'urn:uuid:interface+1+wired+uav1:eth0' ifr1.hasComponentName = 'uav1:eth0' ifr1.hasRole = 'experimental' uav1Point3D = SAMANT::Point3D.for('urn:uav+point3D'.to_sym) uav1Point3D.lat = 5.5701e1 uav1Point3D.long = 1.2552e1 uav1Point3D.save uav1 = SAMANT::Uxv.for('urn:publicid:IDN+samant+uav+flexus1'.to_sym) uav1.hasComponentID = 'urn:publicid:IDN+samant+uav+flexus1' uav1.hasResourceStatus = SAMANT::RELEASED uav1.hasSliceID = 'urn:publicid:IDN+omf:netmode+account+__default__' uav1.where << uav1Point3D uav1.hasUxVType = SAMANT::UAV uav1.hasSensorSystem = uav1MultiSensor uav1.resourceId = 'UaV_FLEXUS1' uav1.hasInterface << ifr1 ifr1.isInterfaceOf = uav1 ifr1.save uav1.save #2222222222222222222222222 auv1MultiSensor = SAMANT::System.for('urn:auv1+multi+sensor'.to_sym) auv1MultiSensor.hasID = 'AuV1MS345' auv1MultiSensor.save ifr2 = SAMANT::WiredInterface.for('urn:uuid:interface+1+wired+auv1:eth0'.to_sym) ifr2.hasComponentID = 'urn:uuid:interface+1+wired+auv1:eth0' ifr2.hasComponentName = 'auv1:eth0' ifr2.hasRole = 'experimental' auv1Point3D = SAMANT::Point3D.for('urn:auv1+point3D'.to_sym) auv1Point3D.lat = 2.1701e1 auv1Point3D.long = 9.355200000000001e1 auv1Point3D.save auv1 = SAMANT::Uxv.for('urn:publicid:IDN+samant+auv+altus1'.to_sym) auv1.hasComponentID = 'urn:publicid:IDN+samant+auv+altus1' auv1.hasResourceStatus = SAMANT::RELEASED auv1.hasSliceID = 'urn:publicid:IDN+omf:netmode+account+__default__' auv1.where << auv1Point3D auv1.hasUxVType = SAMANT::AUV auv1.hasSensorSystem = auv1MultiSensor auv1.resourceId = 'AuV_ALTUS1' auv1.hasInterface << ifr2 ifr2.isInterfaceOf = auv1 ifr2.save auv1.save #33333333333333333333333 auv2MultiSensor = SAMANT::System.for('urn:auv2+multi+sensor'.to_sym) auv2MultiSensor.hasID = 'AuV2MS345' auv2MultiSensor.save ifr3 = SAMANT::WiredInterface.for('urn:uuid:interface+1+wired+auv2:eth0'.to_sym) ifr3.hasComponentID = 'urn:uuid:interface+1+wired+auv2:eth0' ifr3.hasComponentName = 'auv2:eth0' ifr3.hasRole = 'experimental' auv2Point3D = SAMANT::Point3D.for('urn:auv2+point3D'.to_sym) auv2Point3D.lat = 3.1701e1 auv2Point3D.long = 10.355200000000001e1 auv2Point3D.save auv2 = SAMANT::Uxv.for('urn:publicid:IDN+samant+auv+altus2'.to_sym) auv2.hasComponentID = 'urn:publicid:IDN+samant+auv+altus2' auv2.hasResourceStatus = SAMANT::RELEASED auv2.hasSliceID = 'urn:publicid:IDN+omf:netmode+account+__default__' auv2.where << auv2Point3D auv2.hasUxVType = SAMANT::AUV auv2.hasSensorSystem = auv2MultiSensor auv2.resourceId = 'AuV_ALTUS2' auv2.hasInterface << ifr3 ifr3.isInterfaceOf = auv2 ifr3.save auv2.save #4444444444444444444444444 auv3MultiSensor = SAMANT::System.for('urn:auv3+multi+sensor'.to_sym) auv3MultiSensor.hasID = 'AuV3MS345' auv3MultiSensor.save ifr4 = SAMANT::WiredInterface.for('urn:uuid:interface+1+wired+auv3:eth0'.to_sym) ifr4.hasComponentID = 'urn:uuid:interface+1+wired+auv3:eth0' ifr4.hasComponentName = 'auv3:eth0' ifr4.hasRole = 'experimental' auv3Point3D = SAMANT::Point3D.for('urn:auv3+point3D'.to_sym) auv3Point3D.lat = 4.1701e1 auv3Point3D.long = 11.355200000000001e1 auv3Point3D.save auv3 = SAMANT::Uxv.for('urn:publicid:IDN+samant+auv+altus3'.to_sym) auv3.hasComponentID = 'urn:publicid:IDN+samant+auv+altus3' auv3.hasResourceStatus = SAMANT::RELEASED auv3.hasSliceID = 'urn:publicid:IDN+omf:netmode+account+__default__' auv3.where << auv3Point3D auv3.hasUxVType = SAMANT::AUV auv3.hasSensorSystem = auv3MultiSensor auv3.resourceId = 'AuV_ALTUS3' auv3.hasInterface << ifr4 ifr4.isInterfaceOf = auv3 ifr4.save auv3.save #sliver1.isReservationOf << auv2 << auv3 #sliver1.save #555555555555555555555555555 ugv1MultiSensor = SAMANT::System.for('urn:ugv1+multi+sensor'.to_sym) ugv1MultiSensor.hasID = 'UgV1MS345' ugv1MultiSensor.save ifr5 = SAMANT::WirelessInterface.for('urn:uuid:interface+1+wired+ugv1:bt0'.to_sym) ifr5.hasComponentID = 'urn:uuid:interface+1+wired+gv1:bt0' ifr5.hasComponentName = 'gv1:bt0' ifr5.hasRole = 'experimental' ugv1Point3D = SAMANT::Point3D.for('urn:ugv1+point3D'.to_sym) ugv1Point3D.lat = 4.1701e1 ugv1Point3D.long = 11.355200000000001e1 ugv1Point3D.save ugv1 = SAMANT::Uxv.for('urn:publicid:IDN+samant+ugv+altus1'.to_sym) ugv1.hasComponentID = 'urn:publicid:IDN+samant+ugv+altus1' ugv1.hasResourceStatus = SAMANT::RELEASED ugv1.hasSliceID = 'urn:publicid:IDN+omf:netmode+account+__default__' ugv1.where << ugv1Point3D ugv1.hasUxVType = SAMANT::AUV ugv1.hasSensorSystem = auv3MultiSensor ugv1.resourceId = 'UgV_ALTUS1' ugv1.hasInterface << ifr5 ifr5.isInterfaceOf = ugv1 ifr5.save ugv1.save<file_sep>require 'spira' require 'rdf/turtle' require 'rdf/json' require 'sparql/client' #require 'sparql' module Semantic # Preload ontology Omn = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn#") OmnLifecycle = RDF::Vocabulary.new("http://open-multinet.info/ontology/omn-lifecycle#") # Built in vocabs: OWL, RDF, RDFS ##### CLASSES ##### class Attribute < Spira::Base configure :base_uri => Omn.Attribute type RDF::URI.new('http://open-multinet.info/ontology/omn#Attribute') # Object Properties has_many :isAttributeOf, :predicate => Omn.isAttributeOf # Data Properties property :isReadonly, :predicate => Omn.isReadonly, :type => Boolean end class Component < Spira::Base configure :base_uri => Omn.Component type RDF::URI.new('http://open-multinet.info/ontology/omn#Component') # Object Properties has_many :adaptsFrom, :predicate => Omn.adaptsFrom has_many :adaptsTo, :predicate => Omn.adaptsTo has_many :dependsOn, :predicate => Omn.dependsOn has_many :hasAttribute, :predicate => Omn.hasAttribute, :type => :Attribute has_many :hasComponent, :predicate => Omn.hasComponent, :type => :Component has_many :isComponentOf, :predicate => Omn.isComponentOf has_many :relatesTo, :predicate => Omn.relatesTo # Data Properties property :hasComponentID, :predicate => OmnLifecycle.hasComponentID, :type => URI property :hasComponentManagerID, :predicate => OmnLifecycle.hasComponentManagerID, :type => URI property :hasComponentManagerName, :predicate => OmnLifecycle.hasComponentManagerName, :type => URI property :hasComponentName, :predicate => OmnLifecycle.hasComponentName, :type => String end class ReservationState < Attribute configure :base_uri => OmnLifecycle.ReservationState type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#ReservationState') # Object Properties has_many :isReservationStateOf, :predicate => OmnLifecycle.isReservationStateOf, :type => :Reservation end class State < Attribute configure :base_uri => OmnLifecycle.State type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#State') # Object Properties property :hasAction, :predicate => OmnLifecycle.hasAction, :type => :Action property :hasNext, :predicate => OmnLifecycle.hasNext, :type => :State property :hasStateName, :predicate => OmnLifecycle.hasStateName, :type => :State property :hasType, :predicate => OmnLifecycle.hasType, :type => :State has_many :hasWait, :predicate => OmnLifecycle.hasWait, :type => :Wait has_many :isStateOf, :predicate => OmnLifecycle.isStateOf, :type => :LifecycleUnion end class LifecycleUnion < Spira::Base configure :base_uri => OmnLifecycle type RDF::URI.new('http://open-multinet.info/ontology/omn-lifecycle#') # Object Properties has_many :canBeImplementedBy, :predicate => OmnLifecycle.canBeImplementedBy, :type => :LifecycleUnion has_many :canImplement, :predicate => OmnLifecycle.canImplement, :type => :LifecycleUnion has_many :childOf , :predicate => OmnLifecycle.childOf, :type => :LifecycleUnion property :hasState , :predicate => OmnLifecycle.hasState, :type => :State has_many :implementedBy, :predicate => OmnLifecycle.implementedBy, :type => :LifecycleUnion has_many :implements, :predicate => OmnLifecycle.implements, :type => :LifecycleUnion has_many :parentOf, :predicate => OmnLifecycle.parentOf, :type => :LifecycleUnion has_many :usesService, :predicate => OmnLifecycle.usesService, :type => :Service end class Group < LifecycleUnion configure :base_uri => Omn.Group type RDF::URI.new('http://open-multinet.info/ontology/omn#Group') # Object Properties has_many :hasLease, :predicate => OmnLifecycle.hasLease, :type => :Lease has_many :managedBy, :predicate => OmnLifecycle.managedBy, :type => :Service has_many :adaptsFrom, :predicate => Omn.adaptsFrom has_many :adaptsTo, :predicate => Omn.adaptsTo has_many :dependsOn, :predicate => Omn.dependsOn has_many :hasAttribute, :predicate => Omn.hasAttribute, :type => :Attribute has_many :hasGroup, :predicate => Omn.hasGroup, :type => :Group has_many :hasReservation, :predicate => Omn.hasReservation, :type => :Reservation has_many :hasResource, :predicate => Omn.hasResource #, :type => :Resource has_many :hasService, :predicate => Omn.hasService, :type => :Service has_many :isGroupOf, :predicate => Omn.isGroupOf, :type => :Group has_many :relatesTo, :predicate => Omn.relatesTo # Data Properties property :expirationTime, :predicate => OmnLifecycle.expirationTime, :type => DateTime property :hasURI, :predicate => Omn.hasURI, :type => URI end class Reservation < LifecycleUnion configure :base_uri => Omn.Reservation type RDF::URI.new('http://open-multinet.info/ontology/omn#Reservation') # Object Properties has_many :hasReservationState, :predicate => OmnLifecycle.hasReservationState, :type => :ReservationState has_many :isReservationOf, :predicate => Omn.isReservationOf, :type => :NetworkObject # Data Properties property :hasID, :predicate => OmnLifecycle.hasID, :type => String property :hasIdRef, :predicate => OmnLifecycle.hasIdRef, :type => String property :hasSliceID, :predicate => OmnLifecycle.hasSliceID, :type => String # Exoun mpei proswrina mexri na vroume ti paizei property :expirationTime, :predicate => OmnLifecycle.expirationTime, :type => DateTime property :startTime, :predicate => OmnLifecycle.startTime, :type => DateTime end class Resource < Spira::Base configure :base_uri => Omn.Resource type RDF::URI.new('http://open-multinet.info/ontology/omn#Resource') # Object Properties has_many :hasLease, :predicate => OmnLifecycle.hasLease, :type => :Lease has_many :managedBy, :predicate => OmnLifecycle.managedBy, :type => :Service has_many :adaptsFrom, :predicate => Omn.adaptsFrom has_many :adaptsTo, :predicate => Omn.adaptsTo has_many :dependsOn, :predicate => Omn.dependsOn has_many :hasAttribute, :predicate => Omn.hasAttribute, :type => :Attribute has_many :hasComponent, :predicate => Omn.hasComponent, :type => :Component has_many :hasReservation, :predicate => Omn.hasReservation, :type => :Reservation has_many :hasService, :predicate => Omn.hasService, :type => :Service has_many :isResourceOf, :predicate => Omn.isResourceOf, :type => :Group has_many :relatesTo, :predicate => Omn.relatesTo # Data Properties property :creationTime, :predicate => OmnLifecycle.creationTime, :type => DateTime property :creator, :predicate => OmnLifecycle.creator, :type => String property :expirationTime, :predicate => OmnLifecycle.expirationTime, :type => DateTime property :hasAuthenticationInformation, :predicate => OmnLifecycle.hasAuthenticationInformation, :type => String property :hasComponentID, :predicate => OmnLifecycle.hasComponentID, :type => URI property :hasComponentManagerID, :predicate => OmnLifecycle.hasComponentManagerID, :type => URI property :hasComponentManagerName, :predicate => OmnLifecycle.hasComponentManagerName, :type => URI property :hasComponentName, :predicate => OmnLifecycle.hasComponentName, :type => String property :hasID, :predicate => OmnLifecycle.hasID, :type => String property :hasIdRef, :predicate => OmnLifecycle.hasIdRef, :type => String property :hasOriginalID, :predicate => OmnLifecycle.hasOriginalID, :type => String property :resourceId, :predicate => OmnLifecycle.resourceId, :type => String property :hasRole, :predicate => OmnLifecycle.hasRole, :type => String property :hasSliverID, :predicate => OmnLifecycle.hasSliverID, :type => String property :hasSliceID, :predicate => OmnLifecycle.hasSliceID, :type => String property :hasSliverName, :predicate => OmnLifecycle.hasSliverName, :type => String property :startTime, :predicate => OmnLifecycle.startTime, :type => DateTime property :hasURI, :predicate => Omn.hasURI, :type => URI property :isVirtualized, :predicate => Omn.isVirtualized, :type => Boolean end class Service < LifecycleUnion configure :base_uri => Omn.Service type RDF::URI.new('http://open-multinet.info/ontology/omn#Service') # Object Properties has_many :hasLease, :predicate => OmnLifecycle.hasLease, :type => :Lease has_many :serviceIsUsedBy, :predicate => OmnLifecycle.serviceIsUsedBy, :type => :LifecycleUnion has_many :managedBy, :predicate => OmnLifecycle.managedBy, :type => :Service has_many :adaptsFrom, :predicate => Omn.adaptsFrom has_many :adaptsTo, :predicate => Omn.adaptsTo has_many :dependsOn, :predicate => Omn.dependsOn has_many :hasAttribute, :predicate => Omn.hasAttribute, :type => :Attribute has_many :hasComponent, :predicate => Omn.hasComponent, :type => :Component has_many :hasReservation, :predicate => Omn.hasReservation, :type => :Reservation has_many :isServiceOf, :predicate => Omn.isServiceOf has_many :relatesTo, :predicate => Omn.relatesTo # Data Properties property :creationTime, :predicate => OmnLifecycle.creationTime, :type => DateTime property :creator, :predicate => OmnLifecycle.creator, :type => String property :expirationTime, :predicate => OmnLifecycle.expirationTime, :type => DateTime property :hasAuthenticationInformation, :predicate => OmnLifecycle.hasAuthenticationInformation, :type => String property :hasComponentID, :predicate => OmnLifecycle.hasComponentID, :type => URI property :hasComponentManagerID, :predicate => OmnLifecycle.hasComponentManagerID, :type => URI property :hasComponentManagerName, :predicate => OmnLifecycle.hasComponentManagerName, :type => URI property :hasComponentName, :predicate => OmnLifecycle.hasComponentName, :type => String property :hasID, :predicate => OmnLifecycle.hasID, :type => String property :hasIdRef, :predicate => OmnLifecycle.hasIdRef, :type => String property :hasOriginalID, :predicate => OmnLifecycle.hasOriginalID, :type => String property :resourceId, :predicate => OmnLifecycle.resourceId, :type => String property :hasRole, :predicate => OmnLifecycle.hasRole, :type => String property :hasSliverID, :predicate => OmnLifecycle.hasSliverID, :type => String property :hasSliceID, :predicate => OmnLifecycle.hasSliceID, :type => String property :hasSliverName, :predicate => OmnLifecycle.hasSliverName, :type => String property :startTime, :predicate => OmnLifecycle.startTime, :type => DateTime property :hasEndpoint, :predicate => Omn.hasEndpoint, :type => URI property :hasURI, :predicate => Omn.hasURI, :type => URI end class Topology < LifecycleUnion configure :base_uri => Omn.Topology type RDF::URI.new('http://open-multinet.info/ontology/omn#Topology') # Data Properties property :project, :predicate => OmnLifecycle.project, :type => String end end
492c9968dd1afc33097823e430839324cc185d99
[ "Markdown", "Ruby" ]
28
Ruby
maravger/samant-sfa
ab43ef301e9dc3f77b0299c80e8bd96a861a0bb5
5476dae21b80405f6a030897be55c2a925f78503
refs/heads/master
<file_sep><?php class Creativestyle_Sare_Block_Adminhtml_Dashboard extends Mage_Adminhtml_Block_Abstract { public function __construct(){ $this->setTemplate("sare/dashboard.phtml"); } public function render(Varien_Data_Form_Element_Abstract $element){ return Mage::app()->getLayout()->createBlock('Mage_Core_Block_Template', 'Sare_Infoblock', array('template' => 'sare/infoblock.phtml'))->toHtml(); } public function getSubscribedCount(){ $collection = Mage::getModel('newsletter/subscriber')->getCollection()->addFieldToFilter('subscriber_status', array('eq'=>Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED)); return $collection->getSize(); } public function getNonActivated(){ $collection = Mage::getModel('newsletter/subscriber')->getCollection()->addFieldToFilter('subscriber_status', array('eq'=>Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE)); return $collection->getSize(); } public function getUnsubscribedCount(){ $collection = Mage::getModel('newsletter/subscriber')->getCollection()->addFieldToFilter('subscriber_status', array('eq'=>Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED)); return $collection->getSize(); } }<file_sep><?php /** * Created by JetBrains PhpStorm. * User: Adam * Date: 15.06.13 * Time: 13:38 * To change this template use File | Settings | File Templates. */ /* @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this; $installer->startSetup(); $sql = 'CREATE TABLE '. $this->getTable('cs_sare_email').'( `id` BIGINT UNSIGNED NOT NULL, `email` VARCHAR(255) NOT NULL, `created_at` DATETIME NOT NULL, PRIMARY KEY (`id`), INDEX `email` (`id`) ) COMMENT= "Table responsible for holding email / key at SARE" COLLATE="latin1_swedish_ci" ENGINE=InnoDB;'; $installer->run($sql); $installer->run('ALTER TABLE '.$this->getTable('cs_sare_email').' CHANGE `id` `id` INT(32) UNSIGNED AUTO_INCREMENT'); $installer->run('ALTER TABLE '.$this->getTable('cs_sare_email').' ADD COLUMN `mkey` VARCHAR(32) NULL AFTER `email`;'); $installer->endSetup();<file_sep><?php class Creativestyle_Sare_IndexController extends Mage_Core_Controller_Front_Action { public function abandonedcartsAction(){ die('Disabled in this version.'); $key = $this->getRequest()->getParam('key'); if($key!=Mage::getStoreConfig('sare/settings/key')){ die('Wrong key!'); } $collection = Mage::getResourceModel('reports/quote_collection'); $collection->prepareForAbandonedReport($this->_storeIds); $items= array(); foreach($collection as $order){ $updatedAt = $order->getUpdatedAt(); $item = array('updated_at'=>$updatedAt, 'created_at'=>$order->getCreatedAt(), 'grand_total'=>$order->getGrandTotal(), 'customer_name'=>$order->getCustomerName(), 'customer_id'=>$order->getCustomerId(), 'customer_email'=>$order->getCustomerEmail(), ); $productItems = ''; foreach($order->getAllVisibleItems() as $quoteItem){ $productItems = implode('|', array('sku'=>$quoteItem->getSku(), 'name'=>$quoteItem->getName(), 'qty'=>$quoteItem->getQty(), 'price'=>$quoteItem->getPrice() )); } $item['items'] = $productItems; $items[] = $item; } echo serialize($items); die(); } public function getcartAction(){ $key = $this->getRequest()->getParam('key'); if($key!=Mage::getStoreConfig('sare/settings/key')){ die('Wrong key!'); } $block = Mage::app()->getLayout()->createBlock('Creativestyle_Sare_Block_Abandonedcartitems', 'Sare_ACItems', array('template' => 'sare/abandonedcarts.phtml')); echo $block->toHtml(); die(); } }<file_sep><?php class Creativestyle_Sare_Model_Observer{ public function newsletterSubscriberSaveCommitAfter(Varien_Event_Observer $observer) { if(!Mage::getStoreConfig('sare/settings/enabled')){ return $this; } $event = $observer->getEvent(); $subscriber = $event->getDataObject(); $statusChange = $subscriber->getIsStatusChanged(); if($subscriber->getCustomerId()==0){ // This is guest subscriber, check if we should synchro them if(!Mage::getStoreConfig('sare/guest_settings/synchro_enabled')){ return false; } } else { // Customer subscriber, again - need to check if we can save him/her if(!Mage::getStoreConfig('sare/customer_settings/synchro_enabled')){ return false; } } // Trigger if user is now subscribed and there has been a status change: if ($statusChange == true) { if($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) { Mage::getModel('creativestyle_sare/sare')->subscribe($subscriber->getEmail(), $subscriber->getCustomerId(), $subscriber->getUnsubscriptionLink()); } elseif($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { Mage::getModel('creativestyle_sare/sare')->unsubscribe($subscriber->getEmail(), $subscriber->getCustomerId()); } } else { // Seems to be Magento bug - when unsubscribing, flag: isStatusChanged is false - should be true? // Therefore we need to check if action == unsubscribe $moduleName = Mage::app()->getRequest()->getModuleName(); $actionName = Mage::app()->getRequest()->getActionName(); if($moduleName=='newsletter'&&$actionName=='unsubscribe'){ Mage::getModel('creativestyle_sare/sare')->unsubscribe($subscriber->getEmail()); } } return $observer; } public function test($event){ if(!Mage::getStoreConfig('sare/settings/enabled')||!Mage::getStoreConfig('sare/settings/enabled_addresschange')){ return $event; } $customerId = $event->getCustomerAddress()->getCustomerId(); $customer = Mage::getModel('customer/customer')->load($customerId); $this->updateCustomerData($event, $customer); } public function customerDeletedAction(Varien_Event_Observer $observer) { $subscriber = $observer->getEvent()->getSubscriber(); Mage::getModel('creativestyle_sare/sare')->unsubscribe($subscriber->getEmail(), $subscriber->getCustomerId()); } public function updateCustomerDataAfterOrder($observer){ if(!Mage::getStoreConfig('sare/settings/enabled')||!Mage::getStoreConfig('sare/settings/enabled_afterorder')){ return $observer; } $order = $observer->getOrder(); $customer = Mage::getModel('customer/customer')->load($order->getCustomerId()); $subscriberModel = Mage::getModel('newsletter/subscriber')->loadByEmail($customer->getEmail()); if(!$subscriberModel->isSubscribed()){ return false; } $sareSubscriberModel = Mage::getModel('creativestyle_sare/email')->loadByAttribute($customer->getEmail(), 'email'); // Now we know we have customer already subscribed in SARE as well (we have valid mkey!) $customerData = Mage::getModel('creativestyle_sare/customer')->populateCustomerData($customer); if(is_object($sareSubscriberModel)&&$sareSubscriberModel->getMkey()!=''){ Mage::getModel('creativestyle_sare/sare')->updateCustomerData($customer, $customerData, $sareSubscriberModel->getMkey()); } return $observer; } public function updateCustomerData($observer, $customer = null){ if(!Mage::getStoreConfig('sare/settings/enabled')){ return $this; } if(!$customer){ $customer = $observer->getCustomer(); } // First, check if customer is subscribed in Magento NL $subscriberModel = Mage::getModel('newsletter/subscriber')->loadByEmail($customer->getEmail()); if(!$subscriberModel->isSubscribed()){ // When someone is now unsubscribed, we will not update data, to be fair. return false; } // Now check if we have mkey for this email address $sareSubscriberModel = Mage::getModel('creativestyle_sare/email')->loadByAttribute($customer->getEmail(), 'email'); // Now we know we have customer already subscribed in SARE as well (we have valid mkey!) // Let's populate customer data $customerData = Mage::getModel('creativestyle_sare/customer')->populateCustomerData($customer); // Update customer data at SARE side if(is_object($sareSubscriberModel)&&$sareSubscriberModel->getMkey()!=''){ Mage::getModel('creativestyle_sare/sare')->updateCustomerData($customer, $customerData, $sareSubscriberModel->getMkey()); } } // This is ugly hack for getting into dashboard blocks // Alan Storm allowed it, so blame him! public function coreBlockAbstractPrepareLayoutAfter(Varien_Event_Observer $observer) { if(!Mage::getStoreConfig('sare/settings/enabled')){ return $this; } if (is_object(Mage::app()->getFrontController()->getAction())&&Mage::app()->getFrontController()->getAction()->getFullActionName() === 'adminhtml_dashboard_index') { $block = $observer->getBlock(); if ($block->getNameInLayout() === 'dashboard') { $block->getChild('lastOrders')->setUseAsDashboardHook(true); } } } // This is ugly hack for getting into dashboard blocks // Alan Storm allowed it, so blame him! public function coreBlockAbstractToHtmlAfter(Varien_Event_Observer $observer) { if(!Mage::getStoreConfig('sare/settings/enabled')){ return $this; } if (is_object(Mage::app()->getFrontController()->getAction())&&Mage::app()->getFrontController()->getAction()->getFullActionName() === 'adminhtml_dashboard_index') { if ($observer->getBlock()->getUseAsDashboardHook()) { $html = $observer->getTransport()->getHtml(); $myBlock = $observer->getBlock()->getLayout() ->createBlock('sare/adminhtml_dashboard') ->setTheValuesAndTemplateYouNeed('HA!'); $html .= $myBlock->toHtml(); $observer->getTransport()->setHtml($html); } } } }<file_sep><?php class Creativestyle_Sare_Model_Mysql4_Email_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { public function _construct() { parent::_construct(); } } <file_sep><?php class Creativestyle_Sare_Block_Adminhtml_Dashboard_Grids_Subscribers extends Mage_Adminhtml_Block_Dashboard_Grid { public function __construct() { parent::__construct(); $this->setId('subscribers'); $this->setDefaultSort('subscriber_id', 'desc'); $this->setDefaultLimit(10); } /** * Prepare collection for grid * * @return Mage_Adminhtml_Block_Widget_Grid */ protected function _prepareCollection() { $collection = Mage::getResourceSingleton('newsletter/subscriber_collection'); /* @var $collection Mage_Newsletter_Model_Mysql4_Subscriber_Collection */ $collection ->showCustomerInfo(true) ->addSubscriberTypeField() ->showStoreInfo(); if($this->getRequest()->getParam('queue', false)) { $collection->useQueue(Mage::getModel('newsletter/queue') ->load($this->getRequest()->getParam('queue'))); } $this->setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this->addColumn('subscriber_id', array( 'header' => Mage::helper('newsletter')->__('ID'), 'index' => 'subscriber_id', 'sortable' => false )); $this->addColumn('email', array( 'header' => Mage::helper('newsletter')->__('Email'), 'index' => 'subscriber_email', 'sortable' => false )); $this->addColumn('type', array( 'header' => Mage::helper('newsletter')->__('Type'), 'index' => 'type', 'sortable' => false, 'type' => 'options', 'options' => array( 1 => Mage::helper('newsletter')->__('Guest'), 2 => Mage::helper('newsletter')->__('Customer') ) )); $this->addColumn('firstname', array( 'header' => Mage::helper('newsletter')->__('Customer First Name'), 'index' => 'customer_firstname', 'default' => '----' )); $this->addColumn('lastname', array( 'header' => Mage::helper('newsletter')->__('Customer Last Name'), 'index' => 'customer_lastname', 'default' => '----' )); $this->addColumn('status', array( 'header' => Mage::helper('newsletter')->__('Status'), 'index' => 'subscriber_status', 'sortable' => false, 'type' => 'options', 'options' => array( Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE => Mage::helper('newsletter')->__('Not Activated'), Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED => Mage::helper('newsletter')->__('Subscribed'), Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED => Mage::helper('newsletter')->__('Unsubscribed'), Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED => Mage::helper('newsletter')->__('Unconfirmed'), ) )); return parent::_prepareColumns(); } /** * Convert OptionsValue array to Options array * * @param array $optionsArray * @return array */ protected function _getOptions($optionsArray) { $options = array(); foreach ($optionsArray as $option) { $options[$option['value']] = $option['label']; } return $options; } /** * Retrieve Website Options array * * @return array */ protected function _getWebsiteOptions() { return Mage::getModel('adminhtml/system_store')->getWebsiteOptionHash(); } /** * Retrieve Store Group Options array * * @return array */ protected function _getStoreGroupOptions() { return Mage::getModel('adminhtml/system_store')->getStoreGroupOptionHash(); } /** * Retrieve Store Options array * * @return array */ protected function _getStoreOptions() { return Mage::getModel('adminhtml/system_store')->getStoreOptionHash(); } }<file_sep><?php class Creativestyle_Sare_Model_Mysql4_Email extends Mage_Core_Model_Mysql4_Abstract { protected function _construct() { $this->_init('sare/email', 'id'); } } <file_sep><?php class Creativestyle_Sare_Model_AdminNotification_Feed extends Mage_AdminNotification_Model_Feed { /** * Returns feed URL * @return string URL where feed is located under */ public function getFeedUrl() { $url = Mage::getStoreConfigFlag(self::XML_USE_HTTPS_PATH) ? 'https://' : 'http://www.creativestyle.de/email-marketing/feed.rss'; return $url; } /** * Performs feed update */ public function observe() { $this->checkUpdate(); } } <file_sep><?php /** * Author: <NAME> <<EMAIL>> * Date: 23.06.13 Time: 11:33 * For questions, issues - please visit: http://www.creativestyle.de/email-marketing.html */ class Creativestyle_Sare_Helper_Data extends Mage_Core_Helper_Abstract { /** * Sends notification mail to addresses defined in backend. * * @param string $title * @param string $description * @param array $modelData * @param string $apiUrl */ public function sendProblemNotification($title, $description, $modelData, $apiUrl){ if(!Mage::getStoreConfig('sare/settings/send_problem_mails')){ return false; } Mage::getDesign()->setArea('frontend'); $dynamicContent = array( '%TITLE%'=> Mage::helper('sare')->__($title), '%MESSAGE%'=> Mage::helper('sare')->__($description), '%REQUEST%'=> $modelData, '%FOOTER%'=>Mage::helper('sare')->__('You receive these emails, because your address was entered in Magento configuration panel. You can disable them in Magento backend - Newsletter / SARE integration / Settings. <br/><br/>Have a nice day!<br/>SARE team.'), '%API_URL%'=>trim($apiUrl) ); $htmlBlock = Mage::app()->getLayout()->createBlock('core/template')->setTemplate('sare/problemnotification.phtml')->toHtml(); foreach($dynamicContent as $placeholder=>$text){ if(is_array($text)){ $text = ltrim(print_r($text, true)); } $htmlBlock = str_replace($placeholder, $text, $htmlBlock); } $email = Mage::getModel('core/email_template'); $email->setSenderEmail(Mage::getStoreConfig('sare/settings/notification_senderemail')); $email->setSenderName(Mage::getStoreConfig('sare/settings/notification_sendername')); $email->setTemplateSubject(Mage::helper('sare')->__('SARE integration problem notification')); $email->setTemplateText(str_replace(" ","",$htmlBlock)); $receivers = explode(",", Mage::getStoreConfig('sare/settings/exceptions_sent_to')); foreach($receivers as $receiver){ $name = Mage::getStoreConfig('trans_email/'.$receiver.'/name'); $emailAddress = Mage::getStoreConfig('trans_email/'.$receiver.'/email'); $email->send($emailAddress, $name); } } }<file_sep><?php class Creativestyle_Sare_Block_Adminhtml_Abandonedcarts extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface { public function __construct(){ $this->setTemplate("sare/abandonedcarts.phtml"); } public function render(Varien_Data_Form_Element_Abstract $element){ return $this->toHtml(); } public function getInterfaceUrl(){ $url = Mage::getUrl('sare/index/abandonedcarts', array('key'=>Mage::getStoreConfig('sare/settings/key'))); return $url; } }<file_sep><?php class Creativestyle_Sare_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action { private $_fieldSeparator = ";"; private $_lineSeparator = "\n"; /** * @deprecated This is not needed now... */ public function csvAction(){ return $this; $collection = Mage::getResourceSingleton('newsletter/subscriber_collection'); $collection->showCustomerInfo(true) ->addSubscriberTypeField() ->showStoreInfo(); $csv = ''; $csvArr = array(); $subscribersArr = $collection->toArray(); foreach($subscribersArr['items'] as $subscriberArray){ $csvArr[] = implode($this->_fieldSeparator, $subscriberArray); } $csvContent = implode($this->_lineSeparator, $csvArr); $this->getResponse() ->clearHeaders() ->setHeader('Content-Disposition', 'attachment; filename=sare_subscribers.csv') ->setHeader('Content-Type', 'text/csv') ->setBody($csvContent); } /** * This one is used for generating last-added subscribers in dashboard grid. */ public function subscribersgridAction(){ $this->loadLayout(); $this->renderLayout(); } /** * View used for displaying logs in nicely formatted view. */ public function logsAction(){ $logContent = file_get_contents(getcwd().DS.'var'.DS.'log'.DS.'sare.log'); echo '<link rel="stylesheet" type="text/css" media="screen" href="'.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'/adminhtml/base/default/css/sare.css" />'; $logEntries = explode("\n", $logContent); foreach($logEntries as $logEntry){ echo '<div class="logEntry">'.$logEntry.'</div>'; } die(); } public function synchroAction(){ $processMode = $this->getRequest()->getParam('process'); if($processMode==1){ $subscriberId = $this->getRequest()->getParam('subscriber_id'); $responseArr = array(); // Logic for subscribe $collection = Mage::getResourceSingleton('newsletter/subscriber_collection'); $collection->showCustomerInfo(true) ->addSubscriberTypeField() ->showStoreInfo(); $collection->getSelect()->order('subscriber_id ASC'); $collection->addFieldToFilter('subscriber_id', array('gt'=>$subscriberId)); $currentSubscriber = $collection->getFirstItem(); if(!$currentSubscriber->getId()){ echo json_encode($responseArr); Mage::log('Batch process finished!', null, 'sare.log'); return false; } $responseArr['messages'][] = array('text'=>$this->__('Processing: %s', $currentSubscriber->getSubscriberEmail()), 'class'=>'user'); if($currentSubscriber->getSubscriberStatus()==Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED){ // Should be subscriber $responseArr['messages'][] = array('text'=>$this->__('<b>%s</b> should be subscribed...', $currentSubscriber->getSubscriberEmail()), 'class'=>'info'); $sare = Mage::getModel('creativestyle_sare/sare'); $mkey = $sare->subscribe($currentSubscriber->getEmail(), $currentSubscriber->getCustomerId(), $currentSubscriber->getUnsubscriptionLink()); if($mkey){ $responseArr['messages'][] = array('text'=> $this->__('Subscribed with mkey = %s', $mkey), 'class'=>'success'); if($currentSubscriber->getCustomerId()>0){ // This is existing customer, let's generate his data! $customerData = Mage::getModel('creativestyle_sare/customer')->populateCustomerData(Mage::getModel('customer/customer')->load($currentSubscriber->getCustomerId())); Mage::getModel('creativestyle_sare/sare')->updateCustomerData(Mage::getModel('customer/customer')->load($currentSubscriber->getCustomerId()), $customerData, $mkey); $responseArr['messages'][] = array('text'=>$this->__('Populated detailed customer data and sent to SARE'), 'class'=>'success'); } $responseArr['class'] = 'success'; } else { if($sare->_responseCode){ $responseArr['messages'][] = array('text'=> $this->__('Failed to subscribe - SARE returned error %s (%s)', $sare->_responseCode, Mage::getModel('creativestyle_sare/response')->getErrorDescription($sare->_responseCode)), 'class'=>'error'); } else { $responseArr['messages'][] = array('text'=> $this->__('Failed to subscribe - check logs!'), 'class'=>'error'); } } } else { // Should be unsubscribed $responseArr['messages'][] = array('text'=>$this->__('<b>%s</b> should be unsubscribed...', $currentSubscriber->getSubscriberEmail()), 'class'=>'remove'); if(Mage::getModel('creativestyle_sare/sare')->unsubscribe($currentSubscriber->getEmail())){ $responseArr['messages'][] = array('text'=>$this->__('%s has been unsubscribed successfully', $currentSubscriber->getSubscriberEmail()), 'class'=>'success'); $responseArr['class'] = 'success'; } else { $responseArr['messages'][] = array('text'=>$this->__('Failed to unsubscribe - check logs!'), 'class'=>'error'); $responseArr['class'] = 'error'; } } $responseArr['subscriber_id'] = $currentSubscriber->getSubscriberId(); echo json_encode($responseArr); die(); } else { $html = '<script type="text/javascript" src="'.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS).'sare/synchro.js"></script>'; $html .= '<script type="text/javascript" src="'.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS).'sare/jquery-1.10.2.min.js"></script>'; $html .= '<link rel="stylesheet" type="text/css" media="screen" href="'.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN).'/adminhtml/base/default/css/sare.css" />'; $html .= '<style>* {font-family: Helvetica, "Tahoma", courier;font-size:12px;} </style>'; $html .= '<div id="wrapper">'; $collection = Mage::getResourceSingleton('newsletter/subscriber_collection'); $collection->showCustomerInfo(true) ->addSubscriberTypeField() ->showStoreInfo(); $html .= '<div class="transfer"><div class="saretext"><b>'.$this->__('Whats going on?').'</b><ul class="sare-batch"> <li>'.$this->__('every confirmed subscriber is added to SARE').'</li> <li>'.$this->__('if subscriber is not confirmed - appropriate status is set in SARE').'</li> <li>'.$this->__('if subscriber is a customer - detailed data is populated and sent to SARE').'</li> </ul> <br/>'.$this->__('<b>NOTE:</b> Do not close this window.').' </div></div>'; $html .= '<div class="row">'.$this->__('Started mass synchro...').'</div>'; $html .= '<div class="row">'.$this->__('Subscribers to process: <b>%s</b>', $collection->getSize()).'</div>'; $collection->getSelect()->order('subscriber_id ASC'); $subscriber = $collection->getFirstItem(); if($collection->getSize()>0){ $html.= '<script type="text/javascript"> finalMessage = "'.$this->__("<div class='row complete'>All done! <a href='https://ww0.enewsletter.pl/index2.php'>Login to SARE panel</a> now</div>").'"; currentUrl = "'.Mage::helper('core/url')->getCurrentUrl().'";sareProcessSubscriber("0");</script>'; } $html .= '</div>'; echo $html; } } }<file_sep><?php class Creativestyle_Sare_Model_Sare{ private $_requestParams = array(); private $_apiEndPoint = ''; private $_method = ''; private $_currentApiUrl = ''; public $_responseCode = null; const SARE_API_SUBSCRIBE_METHOD = 'acq.php'; const SARE_API_UNSUBSCRIBE_METHOD = 'rm.php'; const SARE_API_UPDATE_METHOD = 'upd.php'; const SETTINGS_KEY_CUSTOMER = 'customer'; const SETTINGS_KEY_GUEST = 'guest'; private function validateSettings(){ if(!Mage::getStoreConfig('sare/settings/uid') || !Mage::getStoreConfig('sare/settings/key')){ Mage::log('Wrong settings, cannot do anything...', Zend_Debug::ALERT, 'sare.log'); return false; } return true; } private function buildDefaultParamsForRemoval(){ $this->_requestParams['u'] = Mage::getStoreConfig('sare/settings/uid'); $this->_requestParams['key'] = Mage::getStoreConfig('sare/settings/key'); $this->_apiEndPoint = Mage::getStoreConfig('sare/settings/sare_endpoint_url'); } private function buildDefaultParams(){ $now = Mage::getModel('core/date')->timestamp(time()); $this->_requestParams['s_uid'] = Mage::getStoreConfig('sare/settings/uid'); $this->_requestParams['s_key'] = Mage::getStoreConfig('sare/settings/key'); $this->_requestParams['s_rv'] = 1; // This one will force numerical response from SARE side $this->_requestParams['s_status'] = Mage::getStoreConfig('sare/settings/save_as'); $this->_requestParams['s_cust_data_last_updated_at'] = date('Y-m-d H:i:s', $now); $this->_apiEndPoint = Mage::getStoreConfig('sare/settings/sare_endpoint_url'); if(!Mage::getStoreConfig('sare/settings/send_confirmation_email')){ // s_no_send = 1 will not trigger default confirmation emails $this->_requestParams['s_no_send'] = 1; } } private function send(){ $url = $this->_apiEndPoint.$this->_method; $pairs = array(); foreach($this->_requestParams as $key => $value){ $pairs[] = $key.'='.urlencode($value); } $url .= '?'.implode('&', $pairs); $this->_currentApiUrl = $url; Mage::log(' Sent request / : '.$this->_method.' - '.$url,1,'sare.log'); try{ $response = file_get_contents($url); } catch (Exception $e){ Mage::log('Fatal exception: '.$e->getMessage(),null, 'sare.log'); return false; } return $this->processResponse($response); } private function processResponse($response, $email = null){ if(is_numeric($response)){ $this->_responseCode = $response; } $keyArr = explode('=', $response); if($this->_method==self::SARE_API_SUBSCRIBE_METHOD){ if(count($keyArr)==2){ $model = Mage::getModel('creativestyle_sare/email'); $collection = $model->getCollection()->addFieldToFilter('email', array('eq'=>$this->_requestParams['s_email'])); foreach($collection as $item){ $modeItem = Mage::getModel('creativestyle_sare/email')->load($item->getId()); $modeItem->delete(); } $model->setId(NULL)->setEmail($this->_requestParams['s_email'])->setCreatedAt(date('Y-m-d H:i:s'))->setMkey($keyArr[1])->save(); Mage::log(' -> Got acq response: '.$keyArr[1].' / '.$this->_requestParams['s_email'],Zend_Log::INFO,'sare.log'); // Populate customer data $customersCollection = Mage::getModel('customer/customer')->getCollection()->addFieldToFilter('email', array('eq'=>$this->_requestParams['s_email'])); foreach($customersCollection as $customerModel){ $customerData = Mage::getModel('creativestyle_sare/customer')->populateCustomerData(Mage::getModel('customer/customer')->load($customerModel->getId())); Mage::getModel('creativestyle_sare/sare')->updateCustomerData($customerModel, $customerData, $keyArr[1]); } return $keyArr[1]; } else { if(is_numeric($response)){ Mage::log(' --> System returned problem: #'.$response, null, 'sare.log'); $this->_responseCode = $response; } Mage::helper('sare')->sendProblemNotification('Subscribe problem', Mage::getModel('creativestyle_sare/response')->getErrorDescription($this->_responseCode).' ('.$this->_responseCode.')', $this->_requestParams, $this->_currentApiUrl); return false; } } if($this->_method==self::SARE_API_UPDATE_METHOD){ if(trim($response)=="1"){ Mage::log(' -> Got upd response: '.$response, Zend_Log::INFO, 'sare.log'); return true; } else { Mage::helper('sare')->sendProblemNotification('Update problem', Mage::getModel('creativestyle_sare/response')->getErrorDescription($this->_responseCode).' ('.$this->_responseCode.')', $this->_requestParams, $this->_currentApiUrl); Mage::log(' -> Got upd response (failed): '.$response, Zend_Log::ALERT,'sare.log'); return false; } } if($this->_method==self::SARE_API_UNSUBSCRIBE_METHOD){ if(!empty($this->_requestParams['mkey'])){ $model = Mage::getModel('creativestyle_sare/email')->loadByAttribute($this->_requestParams['mkey'], 'mkey'); $fullModel = Mage::getModel('creativestyle_sare/email')->load($model->getId()); $fullModel->delete(); Mage::log(' -> Got rm.php response: '.htmlentities(nl2br($response)), Zend_Log::ALERT, 'sare.log'); return false; } // We're just gonna assume it was ok return true; } } public function subscribe($email, $customerId, $unsubscriptionUrl){ if(!$this->validateSettings()){ return false; } if($customerId==0){ // Guest subscriber $settingsKey = self::SETTINGS_KEY_GUEST; } else { // Customer subscriber $settingsKey = self::SETTINGS_KEY_CUSTOMER; } $this->buildDefaultParams(); $this->_requestParams['s_email'] = $email; $this->_requestParams['s_cust_unsubscription_link'] = $unsubscriptionUrl; // Unsubscription link MUST BE always sent! $targetGroups = explode(',', Mage::getStoreConfig('sare/'.$settingsKey.'_settings/group_id')); foreach($targetGroups as $targetGroup){ $this->_requestParams['s_group_'.$targetGroup] = 1; } $this->_method = self::SARE_API_SUBSCRIBE_METHOD; return $this->send(); } public function unsubscribe($email){ if(!$this->validateSettings()){ return false; } $this->buildDefaultParamsForRemoval(); $emailsCollection = Mage::getModel('creativestyle_sare/email')->getCollection()->addFieldToFilter('email', array('eq'=>$email)); $emailObject = $emailsCollection->getFirstItem(); $this->_requestParams['mkey'] = $emailObject->getMkey(); $this->_requestParams['s_status'] = 7; $this->_method = self::SARE_API_UNSUBSCRIBE_METHOD; if(empty($this->_requestParams['mkey'])){ if(!empty($email)){ Mage::log(Mage::helper('sare')->__('Cant unsubscribe this address: %s, missing mkey!', $email), null, 'sare.log'); return false; } } return $this->send(); } public function updateCustomerData($customer, $customerData, $key){ if(!$this->validateSettings()){ return false; } $this->buildDefaultParams(); $this->_method = self::SARE_API_UPDATE_METHOD; $this->_requestParams['s_mkey'] = $key; foreach($customerData as $key=>$value){ $this->_requestParams['s_cust_'.$key] = $value; } $this->send(); } }<file_sep>function sareProcessSubscriber(subscriber_id){ $.ajax({ dataType: "json", url: currentUrl+'process/1/subscriber_id/'+subscriber_id, data: null, success: function(msg){ if(msg.subscriber_id){ $.each(msg.messages, function(i, item) { $('#wrapper').append('<div class="row '+item.class+'">'+item.text+'</div>'); }); sareProcessSubscriber(msg.subscriber_id); } else { $('#wrapper').append(finalMessage); } }, error: function(msg){ alert(msg); } }); }<file_sep><?php class Creativestyle_Sare_Block_Adminhtml_Infoblock extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface { public function __construct(){ $this->setTemplate("sare/infoblock.phtml"); } public function render(Varien_Data_Form_Element_Abstract $element){ return Mage::app()->getLayout()->createBlock('Mage_Core_Block_Template', 'Sare_Infoblock', array('template' => 'sare/infoblock.phtml'))->toHtml(); } }<file_sep><?php class Creativestyle_Sare_Model_Customer extends Mage_Core_Model_Abstract{ public $_attributes = array('customer_id', 'store_id', 'website_id', 'last_logged_in', 'registered_on', 'firstname', 'lastname', 'last_order_at', 'last_order_value', 'total_orders_count', 'total_orders_value', 'average_sale','city', 'postcode', 'customer_group_id','company', 'country_id','last_bought_products','last_order_at_unix','telephone','fax','dob','gender','wishlist_items', 'unsubscription_link','data_last_updated_at'); public $labels = array(); public function __construct(){ $this->labels = array( 'customer_id'=>array('label'=>Mage::helper('sare')->__('Magento internal customer_id (entity_id)'), 'description'=>Mage::helper('sare')->__('')), 'store_id'=>array('label'=>Mage::helper('sare')->__('Store ID in which customer registered in'), 'description'=>Mage::helper('sare')->__('')), 'registered_on'=>array('label'=>Mage::helper('sare')->__('Register datetime'), 'description'=>Mage::helper('sare')->__('Holds date and time when customer has registered.')), 'last_logged_in'=>array('label'=>Mage::helper('sare')->__('Last login date'), 'description'=>Mage::helper('sare')->__('Holds data when customer was logged in webshop.')), 'unsubscription_link'=>array('label'=>Mage::helper('sare')->__('Unsubscribe URL'), 'description'=>Mage::helper('sare')->__('Contains unsubscribe URL, this field is required.')), 'firstname'=>array('label'=>Mage::helper('sare')->__('Customer\'s firstname'), 'description'=>Mage::helper('sare')->__('Customer\'s firstname.')), 'lastname'=>array('label'=>Mage::helper('sare')->__('Customer\'s lastname'), 'description'=>Mage::helper('sare')->__('Customer\'s lastname.')), 'dob'=>array('label'=>Mage::helper('sare')->__('Date of birth'), 'description'=>Mage::helper('sare')->__('')), 'gender'=>array('label'=>Mage::helper('sare')->__('Customer\'s gender'), 'description'=>Mage::helper('sare')->__('')), 'company'=>array('label'=>Mage::helper('sare')->__('Customer\'s company'), 'description'=>Mage::helper('sare')->__('')), 'postcode'=>array('label'=>Mage::helper('sare')->__('Customer\'s postcode (billing address)'), 'description'=>Mage::helper('sare')->__('')), 'city'=>array('label'=>Mage::helper('sare')->__('Customer\'s city (billing address)'), 'description'=>Mage::helper('sare')->__('')), 'telephone'=>array('label'=>Mage::helper('sare')->__('Customer\'s telephone number (billing address)'), 'description'=>Mage::helper('sare')->__('')), 'fax'=>array('label'=>Mage::helper('sare')->__('Customer\'s fax number (billing address)'), 'description'=>Mage::helper('sare')->__('')), 'country_id'=>array('label'=>Mage::helper('sare')->__('Customer\'s country id (f.e: DE, PL)'), 'description'=>Mage::helper('sare')->__('')), 'customer_group_id'=>array('label'=>Mage::helper('sare')->__('Customer\'s group id'), 'description'=>Mage::helper('sare')->__('')), 'last_order_at'=>array('label'=>Mage::helper('sare')->__('Last order datetime'), 'description'=>Mage::helper('sare')->__('Customer\'s lastname.')), 'last_order_value'=>array('label'=>Mage::helper('sare')->__('Last order value (grand total)'), 'description'=>Mage::helper('sare')->__('Customer\'s last order value (grand total, incl. shipment, tax, dicount, etc)')), 'total_orders_count'=>array('label'=>Mage::helper('sare')->__('Total orders count'), 'description'=>Mage::helper('sare')->__('')), 'total_orders_value'=>array('label'=>Mage::helper('sare')->__('Total orders value'), 'description'=>Mage::helper('sare')->__('')), 'average_sale'=>array('label'=>Mage::helper('sare')->__('Customer\'s average order value'), 'description'=>Mage::helper('sare')->__('')), 'last_bought_products'=>array('label'=>Mage::helper('sare')->__('List of last bought items (sku1, sku2, ...)'), 'description'=>Mage::helper('sare')->__('')), 'wishlist_items'=>array('label'=>Mage::helper('sare')->__('Products put in customer\'s wishlist (sku1, sku2, etc)'), 'description'=>Mage::helper('sare')->__('')), 'data_last_updated_at'=>array('label'=>Mage::helper('sare')->__('Timestamp of last datachange'), 'description'=>Mage::helper('sare')->__('')), ); } /** * Populates customer data and returns it in associative array * @param $customer Customer object for which data is populated * @return array Consumer's data array */ public function populateCustomerData($customer){ $data = array(); foreach($this->_attributes as $attribute){ if(is_object($customer)&&$customer->getId()){ if($value = call_user_func(array($this, $attribute), $customer)){ $data[$attribute] = $value; } else { // Well, nothing :) } } else { $data[$attribute] = call_user_func('Creativestyle_Sare_Model_Customer::'.$attribute, Mage::getModel('customer/customer')); } } // Zend_Debug::dump($data);die(); return $data; } /** * Returns customer's unsubsubcription URL * @param Mage_Customer_Model_Customer $customer * @return string $unsubscroptionLink */ static function unsubscription_link($customer){ return Mage::getModel('newsletter/subscriber')->loadByEmail($customer->getEmail())->getUnsubscriptionLink(); } /** * Returns last login date. If not logged in yet- retuns actual time * @param $customer * @return string */ static function last_logged_in($customer){ $version = Mage::getVersionInfo(); $logCustomer = Mage::getModel('log/customer')->load($customer->getId(), 'customer_id'); $lastVisited = $logCustomer->getLoginAtTimestamp(); if(empty($lastVisited)){ // Not logged in yet $lastVisited = Mage::getModel('core/date')->date('Y-m-d H:i:s'); } else { if($version['minor']<6){ $lastVisited = Mage::getModel('core/date')->date('Y-m-d H:i:s', $lastVisited); } else { $lastVisited = date('Y-m-d H:i:s', $lastVisited); } } return $lastVisited; } /** * @param Mage_Customer_Model_Customer $customer * @return datetime Datetime of last user login (Y-m-d H:i:s) */ static function data_last_updated_at($customer){ $now = Mage::getModel('core/date')->timestamp(time()); return date('Y-m-d H:i:s', $now); } /** * Return customer's ID (entity_id) * @param Mage_Customer_Model_Customer $customer * @return int customer_id */ static function customer_id($customer){ return $customer->getId(); } /** * Returns customer's firstname * @param Mage_Customer_Model_Customer $customer * @return string firstname */ static function firstname($customer){ return $customer->getFirstname(); } /** * Returns customer's lastname * @param Mage_Customer_Model_Customer $customer * @return string lastname */ static function lastname($customer){ return $customer->getLastname(); } /** * Returns customer's date-of-birth * @param Mage_Customer_Model_Customer $customer * @return string firstname */ static function dob($customer){ return $customer->getDob(); } /** * @param Mage_Customer_Model_Customer $customer * @return mixed Customer's gender or empty if nothing specified */ static function gender($customer){ if($customer->getGender()){ return $customer->getGender(); } else { return ""; } } /** * Returns collction of orders for specified customer * @param Mage_Customer_Model_Customer $customer * @return Mage_Sales_Order_Collection $orders */ static function getAllOrders($customer){ $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id', array('eq'=>$customer->getId()))->setOrder('created_at'); return $orders; } /** * Returns last placed order or null (in case there are no order for this customer yet) * @param Mage_Customer_Model_Customer $customer * @return mixed datetime or null */ static function getLastOrder($customer){ $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id', array('eq'=>$customer->getId()))->setOrder('created_at'); $order = $orders->getFirstItem(); if($order->getId()){ return $order; } return false; } /** * Returns datetime of last order for specified customer * @param Mage_Customer_Model_Customer $customer * @return datetime */ static function last_order_at($customer){ $order = self::getLastOrder($customer); if($order&&$order->getId()){ $sTime = Mage::app() ->getLocale() ->date(strtotime($order->getCreatedAtStoreDate()), null, null, false) ->toString('YYYY-MM-dd H:m:s'); return $sTime; } return ''; } /** * Fetches list of SKUs for products placed in customer's wishlist. * @param Mage_Customer_Model_Customer$customer * @return string skus (separated by ,) */ static function wishlist_items($customer){ $wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer); $wishListItemCollection = $wishList->getItemCollection(); $arrProductSkus = array(); if (count($wishListItemCollection)) { foreach ($wishListItemCollection as $item) { $product = $item->getProduct(); $arrProductSkus[] = $product->getSku(); } } return implode(',', $arrProductSkus); } /** * Returns last order's datetima as timestamp * @param $customer * @return int|string */ static function last_order_at_unix($customer){ $lastOrderAr = self::last_order_at($customer); if($lastOrderAr!=''){ return strtotime($lastOrderAr); } return ''; } /** * Returns last order value (grand total) * @param $customer * @return float order value (grand total) */ static function last_order_value($customer){ $order = self::getLastOrder($customer); if($order&&$order->getId()){ return (float)$order->getGrandTotal(); } return ''; } /** * Returns customer registration datetime * @param Mage_Customer_Model_Customer $customer * @return mixed */ static function registered_on($customer){ if(!$customer->getCreatedAt()){ return ""; } $sTime = Mage::app() ->getLocale() ->date(strtotime($customer->getCreatedAt()), null, null, false) ->toString('YYYY-MM-dd H:m:s'); return $sTime; } /** * Returns customer city (using default billing address) * @param Mage_Customer_Model_Customer $customer * @return string */ static function city($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getCity(); } return ''; } /** * Returns storeID where customer has registered in * @param $customer * @return mixed */ static function store_id($customer){ return $customer->getStoreId(); } /** * Returns websiteID where customer has registered in * @param $customer * @return mixed */ static function website_id($customer){ return $customer->getWebsiteId(); } static function company($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getCompany(); } return ''; } /** * Returns customer's telephone number * @param $customer * @return string */ static function telephone($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getTelephone(); } return ''; } /*** * Returns customer's fax number * @param $customer * @return string */ static function fax($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getFax(); } return ''; } /** * Returns customer's group ID * @param $customer * @return mixed */ static function customer_group_id($customer){ return $customer->getGroupId(); } /** * Returns list of last bought products as comma separated list of SKUs * @param $customer * @return string */ static function last_bought_products($customer){ $orders = self::getAllOrders($customer); $items = array(); foreach($orders as $order){ foreach($order->getAllItems() as $item){ $items[] = $item->getSku(); } } return implode(',', $items); } /** * Returns customer's postcody (billing address) * @param $customer * @return string */ static function postcode($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getPostcode(); } return ''; } /** * @param $customer * @return string */ static function country_id($customer){ if(is_object($customer->getDefaultBillingAddress())){ return $customer->getDefaultBillingAddress()->getCountryId(); } return ''; } static function total_orders_count($customer){ $orders = self::getAllOrders($customer); return $orders->getSize(); } static function total_orders_value($customer){ $orders = self::getAllOrders($customer); $value = 0; foreach($orders as $order){ $value += $order->getGrandTotal(); } return $value; } static function average_sale($customer){ $orders = self::getAllOrders($customer); $value = 0; $count = 0; foreach($orders as $order){ $value += $order->getGrandTotal(); $count ++; } if($count>0){ return round($value/$count,2); } return 0; } }<file_sep><?php /** * Created by JetBrains PhpStorm. * User: Adam * Date: 10.09.13 * Time: 08:57 * To change this template use File | Settings | File Templates. */ class Creativestyle_Sare_Block_Adminhtml_Dashboard_Grids extends Mage_Adminhtml_Block_Dashboard_Grids { public function _prepareLayout(){ parent::_prepareLayout(); $this->addTab('subscribers', array( 'label' => $this->__('Recent subscribers'), 'url' => $this->getUrl('sare/adminhtml_index/subscribersgrid', array('_current'=>true)), 'class' => 'ajax' )); return parent::_prepareLayout(); } }<file_sep><?php class Creativestyle_Sare_Model_Response{ public $ERROR_CODES = array(); public function __construct(){ $this->ERROR_CODES = array(1=>Mage::helper('sare')->__('Address added successfully.'), 4=>Mage::helper('sare')->__('Address already exists, but has not been confirmed yet.'), 7=>Mage::helper('sare')->__('Address already exists, but it is blocked by SARE operator.'), 8=>Mage::helper('sare')->__('Address already exists, and it is confirmed already.'), -1=>Mage::helper('sare')->__('One the required parameters is missing.'), -2=>Mage::helper('sare')->__('E-mail address is not formed correctly.'), -3=>Mage::helper('sare')->__('UID number is not formed correctly.'), -4=>Mage::helper('sare')->__('Wrong integration key.'), -5=>Mage::helper('sare')->__('GSM number is not formed correctly.'), -97=>Mage::helper('sare')->__('API limit is set.'), -98=>Mage::helper('sare')->__('Wrong UID.'), -99=>Mage::helper('sare')->__('Database connection error.'), ); } public function getErrorDescription($errorCode){ return isset($this->ERROR_CODES[$errorCode]) ? $this->ERROR_CODES[$errorCode] : Mage::helper('sare')->__('Unknown error.'); } }<file_sep><?php $installer = $this; $installer->startSetup(); $sql = "INSERT INTO ".$this->getTable('core_translate')." (`string`, `store_id`, `translate`, `locale`) VALUES ('Mage_Adminhtml::<div class=\"sare-settings-headline\"> integration</div>', 0, '<div class=\"sare-settings-headline\"> integracja</div>', 'pl_PL');"; $installer->run($sql); $installer->endSetup();<file_sep><?php class Creativestyle_Sare_Block_Adminhtml_Targetinginfoblock extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface { public function __construct(){ $this->setTemplate("sare/targeting.phtml"); } public function render(Varien_Data_Form_Element_Abstract $element){ return $this->toHtml(); } public function getList(){ $model = new Creativestyle_Sare_Model_Customer(); return $model->labels; } }<file_sep><?php class Creativestyle_Sare_Model_Email extends Mage_Core_Model_Abstract { public function __construct() { $this->_init('sare/email', 'id'); } public function loadByAttribute($attributeValue, $attributeCode){ $collection = Mage::getModel('creativestyle_sare/email')->getCollection()->addFieldToFilter($attributeCode, array('eq'=>$attributeValue)); if($collection->getSize()>0){ return $collection->getFirstItem(); } return false; } }<file_sep><?php class Creativestyle_Sare_Block_Abandonedcartitems extends Mage_Core_Block_Template { public function __construct(){ $this->setTemplate("sare/abandonedcarts.phtml"); } public function getItems(){ $customerId = $this->getRequest()->getParam('customer_id'); $collection = Mage::getResourceModel('reports/quote_collection'); $collection->prepareForAbandonedReport($this->_storeIds)->addFieldToFilter('customer_id', array('eq'=>$customerId)); $this->collection = $collection; return $collection; } }<file_sep><?php class Creativestyle_Sare_Model_Status{ public function toOptionArray() { // This is list of statuses available in SARE with corresponding labels // Source: http://dev.sare.pl/sare-api/rest-api/aneks/ return array( 2=>Mage::helper('sare')->__('Removed by SARE operator'), 3=>Mage::helper('sare')->__('Willing to sign off'), 4=>Mage::helper('sare')->__('Willing to sign off (by link)'), 5=>Mage::helper('sare')->__('Not confirmed, confirmation email not sent'), 6=>Mage::helper('sare')->__('Saved, waiting to be confirmed'), 7=>Mage::helper('sare')->__('Subscriber blocked'), 8=>Mage::helper('sare')->__('Saved and confirmed') ); } }
2f163bf7cbfe11ae932adc99414b9da69a69e490
[ "JavaScript", "PHP" ]
22
PHP
OpenMageModuleFostering/creativestyle_sare
5f7385ec4d63d091bbb4afb209e82d97c68b5179
9b7d01ba197643ecaf0234c12628817cb935dff8
refs/heads/master
<file_sep>import numpy as np def runChop(score, action, displ = 0): """ Takes Current Score and action and returns resulting Score in: score: Array of 4 numbers [p1 left, p1 right, p2 left, p2 right] action: options 1 thru 4 (LL, LR, RL, RR) out: score: array size 4 """ fingers = 5 if action == 1: score[2] = (score[2] + score[0]) % fingers elif action == 2: score[3] = (score[3] + score[0]) % fingers elif action == 3: score[2] = (score[2] + score[1]) % fingers elif action == 4: score[3] = (score[3] + score[1]) % fingers if displ: print("final score", score) if(sum(score[0:2]) == 0 or sum(score[2:4]) == 0): score[0] = -1 return score initScore = np.ones(4) myScore = initScore.copy() while(myScore[0] != -1): temp = myScore[0:2].copy() myScore[0:2] = myScore[2:4] myScore[2:4] = temp print(myScore) myaction = int(input("enter action 1-4 (LL, LR, RL, RR)")) runChop(myScore, myaction, 1) print(myScore, initScore) <file_sep>from gym_chop.envs.chop_env import ChopStick <file_sep>from gym.envs.registration import register register( id='chop-v0', entry_point='gym_chop.envs:ChopStick', ) <file_sep>import gym from gym import error, spaces, utils from gym.utils import seeding class ChopStick(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): self.state = [] for i in range(2): self.state += [[]] for j in range(2): self.state[i] += [1] self.fingers = 5 self.counter = 0 self.done = 0 self.add = [0, 0] #Player win self.reward = 0 def setFingers(self, f): self.fingers = f def check(self): if(self.counter<5): #minimal number to reach game completion return 0 if (self.state[0][0] + self.state[0][1]) == 0: return 2 #p2 wins if (self.state[1][0] + self.state[1][1]) == 0: return 1 #p1 wins return 0 def step(self, action): #Action 0:4 (LL, LR, RL, RR, Split) p = self.counter%2 #player o = (p+1)%2 #opponent c = action%2 #target card if self.done == 1: print("Game Over", self.counter) return [self.state, self.reward, self.done, self.add, self.counter] if action < 2: #LL, LR if self.state[p][0] == 0: #Prevent add 0 moves print("Invalid Step") # self.reward = -1000 #TO BE IMPLEMENTED -- TRAIN TO RECOGNIZE INVALID MOVES return [self.state, self.reward, self.done, self.add, self.counter] self.state[o][c] = (self.state[o][c] + self.state[p][0]) %self.fingers elif action < 4: #RL, RR if self.state[p][1] == 0: # self.reward = -1000 print("Invalid Step") return [self.state, self.reward, self.done, self.add, self.counter] self.state[o][c] = (self.state[o][c] + self.state[p][1]) %self.fingers elif action == 4: #Split if ((self.state[p][0] == 0 and (self.state[p][1]%2) == 0) or (self.state[p][1] == 0 and (self.state[p][0]%2)==0) ): temp = (self.state[p][1]+self.state[p][0])/2 self.state[p][0] = temp self.state[p][1] = temp else: print("Invalid Step") # self.reward = -1000 return [self.state, self.reward, self.done, self.add, self.counter] #Time penalty # if(self.counter > 40): # self.done = 1 # self.reward = -100 # print("too long!") self.counter += 1 win = self.check() if(win): self.done = 1 print("player ", win, " wins", self.counter) self.add[win-1] = 1 if win == 1: self.reward = 100 else: self.reward = -100 self.render() return [self.state, self.reward, self.done, self.add, self.counter] def reset(self): for i in range(2): for j in range(2): self.state[i][j] = 1 self.counter = 0 self.done = 0 self.add = [0, 0] self.reward = 0 return self.state def render(self): print(self.state) return
f1cf88b5ee00a4d0d1d9ecac3338a7251d369ab4
[ "Python" ]
4
Python
jzcs/ML_Winter2019
bfc1da179efe009758ff4f4e19c09fb9a58379b9
7fd6f8cd395681aa7b1f8ffeb19775bc496705c9
refs/heads/main
<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Fornecimento(BaseModel): franquia_id: int fornecedor_id: int data: str def get_fornecimento(): return query("SELECT * FROM FORNECIMENTO;") def insert_fornecimento(forncimento: Fornecimento): return mutation(f'INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values ({forncimento.franquia}, {forncimento.fornecedor}, \'{forncimento.data}\');') def delete_fornecimento(fornecimento_id: int): return mutation(f'DELETE FROM FORNECIMENTO f WHERE f.FORNECIMENTO_ID = {fornecimento_id};')<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Produto(BaseModel): secao_id: int franquia_id: int fornecimento_id: int marca: str preco: str nome: str def get_produtos_by_secao(secaoId: int): produtos = query(f'SELECT p.nome_produto, p.preco_unitario, p.marca_produto, s.nome_sec\ FROM PRODUTO p INNER JOIN SECAO s ON p.secao_id = s.secao_id\ WHERE s.secao_id = {secaoId};') return produtos def get_produtos_vendidos(): return query("SELECT p.*, s.nome_sec FROM PRODUTO p INNER JOIN SECAO s ON p.secao_id = s.secao_id WHERE p.VENDA_ID IS NOT NULL;") def get_produtos_nao_vendidos(): return query("SELECT p.*, s.nome_sec FROM PRODUTO p INNER JOIN SECAO s ON p.secao_id = s.secao_id WHERE p.VENDA_ID IS NULL;") def insertProduto(produto: Produto): return mutation(f'INSERT INTO PRODUTO(SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values ({produto.secao_id}, {produto.franquia_id}, {produto.fornecimento_id}, \'{produto.marca}\', \'{produto.preco}\', \'{produto.nome}\');') def add_produto_na_venda(produto_id: int, venda_id: int): return mutation(f'UPDATE PRODUTO SET VENDA_ID = {venda_id} WHERE PRODUTO_ID = {produto_id};') def deleteProduto(produto_id: int): return mutation(f'DELETE FROM PRODUTO p WHERE p.PRODUTO_ID = {produto_id};')<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Endereco(BaseModel): rua: str bairro: str cidade: str estado: str cep: str def getEnderecos(): enderecos = query("SELECT * FROM ENDERECO;") return enderecos def insertEnderecos(endereco: Endereco): response = mutation(f'insert into endereco(rua, bairro, cidade, estado, cep) values (\'{endereco.rua}\', \'{endereco.bairro}\', \'{endereco.cidade}\', \'{endereco.estado}\', \'{endereco.cep}\');') return response def deleteEnderecos(endereco_id: int): response = mutation(f'DELETE FROM ENDERECO c WHERE c.ENDERECO_ID = {endereco_id};') return response <file_sep>from typing import Optional from fastapi import FastAPI from carroService import Carro, deleteCarro, getCarros, insertCarro from clienteService import Cliente, delete_cliente, get_clientes, insert_cliente from enderecoService import Endereco, deleteEnderecos, getEnderecos, insertEnderecos from entregaService import Entrega, deleteEntrega, getEntrega, insertEntrega from fornecedorService import Fornecedor, deleteFornecedor, getFornecedor, insertFornecedor from fornecimentoService import Fornecimento, delete_fornecimento, get_fornecimento, insert_fornecimento from fraquiaService import get_franquias from funcionarioService import Funcionario, deleteFunc, getFuncionarios, insertFuncionario from secaoService import get_all_secoes from produtoService import Produto, add_produto_na_venda, get_produtos_by_secao, get_produtos_nao_vendidos, get_produtos_vendidos, insertProduto from promocaoService import get_all_promo, insert_promo, Promocao, delete_promo from fastapi.middleware.cors import CORSMiddleware from vendaService import Venda, insert_venda app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/{entidade}") def get_entidade(entidade: str): if entidade == "carro": return getCarros() elif entidade == "cliente": return get_clientes() elif entidade == "endereco": return getEnderecos() elif entidade == "entrega": return getEntrega() elif entidade == "fornecedor": return getFornecedor() elif entidade == "fornecimento": return get_fornecimento() elif entidade == "franquia": return get_franquias() elif entidade == "funcionario": return getFuncionarios() elif entidade == "promocao": return get_all_promo() elif entidade == "secao": return get_all_secoes() elif entidade == "venda": return getFuncionarios() @app.delete("/{entidade}/{item_id}") def get_entidade(entidade: str, item_id): if entidade == "carro": return deleteCarro(item_id) elif entidade == "cliente": return delete_cliente(item_id) elif entidade == "endereco": return deleteEnderecos(item_id) elif entidade == "entrega": return deleteEntrega(item_id) elif entidade == "fornecedor": return deleteFornecedor(item_id) elif entidade == "fornecimento": return delete_fornecimento(item_id) elif entidade == "funcionario": return deleteFunc(item_id) elif entidade == "promocao": return delete_promo(item_id) @app.post("/insert/carro") def newCarro(carro: Carro): return insertCarro(carro) @app.post("/insert/cliente") def new_cliente(cliente: Cliente): return insert_cliente(cliente) @app.post("/insert/endereco") def new_endereco(endereco: Endereco): return insertEnderecos(endereco) @app.post("/insert/entrega") def new_entrega(entrega: Entrega): return insertEntrega(entrega) @app.post("/insert/fornecedor") def new_fornecedor(fornecedor: Fornecedor): return insertFornecedor(fornecedor) @app.post("/insert/fornecimento") def new_fornecimento(fornecimento: Fornecimento): return insert_fornecimento(fornecimento) @app.post("/insert/funcionario") def new_funcionario(funcionario: Funcionario): return insertFuncionario(funcionario) @app.post("/insert/funcionario") def new_funcionario(funcionario: Funcionario): return insertFuncionario(funcionario) @app.post("/insert/produto") def new_produto(produto: Produto): return insertProduto(produto) @app.post("/insert/promocao") def new_promo(promocao: Promocao): return insert_promo(promocao) @app.post("/insert/venda") def new_venda(venda: Venda): return insert_venda(venda) @app.get("/produto/{secao_id}") def get_produto(secao_id: int): return get_produtos_by_secao(secao_id) @app.get("/produto/vendidos") def get_vendidos(): return get_produtos_vendidos() @app.get("/produto/nao-vendidos") def get_nao_vendidos(): return get_produtos_nao_vendidos() @app.put("/venda/add-produto/{prod_id}") def add_prod_venda(prod_id: int): return add_produto_na_venda(prod_id) <file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Funcionario(BaseModel): nome: str sobrenome: str cargo: str supervisor_id: int franquia_id: int data_admissao: str cpf: str def getFuncionarios(): return query('SELECT * FROM FUNCIONARIO') def insertFuncionario(funcionario: Funcionario): return mutation(f"INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values (\'{funcionario.nome}\', \'{funcionario.sobrenome}\', \'{funcionario.cargo}\', {funcionario.franquia_id}, \'{funcionario.data_admissao}\', \'{funcionario.cpf}\');") def deleteFunc(funcionario_id: int): return mutation(f"DELETE FROM FUNCIONARIO f WHERE f.FUNCIONARIO_ID = {funcionario_id};")<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Carro(BaseModel): franquia_id: int placa: str modelo: str ano: int marca: str def getCarros(): carros = query("SELECT * FROM CARRO;") return carros def insertCarro(carro: Carro): response = mutation(f'INSERT INTO CARRO (FRANQUIA_ID, PLACA, MODELO, ANO, MARCA_CARRO) values ({carro.franquia_id}, \'{carro.placa}\', \'{carro.modelo}\', {carro.ano}, \'{carro.marca}\');') return response def deleteCarro(carro_id: int): response = mutation(f'DELETE FROM CARRO c WHERE c.CARRO_ID = {carro_id};') return response <file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Promocao(BaseModel): porcentagem: int secaoId: int def get_all_promo(): promos = query("SELECT * FROM PROMOCAO;") return promos def insert_promo(promocao: Promocao): response = mutation(f'insert into PROMOCAO (porcentagem, secao_id) values ({promocao.porcentagem}, {promocao.secaoId});') return response def delete_promo(promoId: int): response = mutation(f'DELETE FROM PROMOCAO p WHERE p.promocao_id = {promoId};') return response<file_sep># BD2-Sistema-BackEnd Projeto de disciplina Banco de Dados 2 <file_sep>ALTER SEQUENCE endereco_ENDERECO_ID_seq RESTART WITH 1; insert into endereco(rua, bairro, cidade, estado, cep) values ('Avenida Tiradentes','Morumbi','São Paulo','São Paulo','08260-310'); insert into endereco(rua, bairro, cidade, estado, cep) values ('Avenida Paulista','Bom Clima','São Paulo','São Paulo','08420-220'); insert into endereco(rua, bairro, cidade, estado, cep) values ('Avenida Brasil','Tatuapé','São Paulo','São Paulo','08485-501'); insert into endereco(rua, bairro, cidade, estado, cep) values ('Avenida Tupinamba','Penha','São Paulo','São Paulo','04736-050'); ALTER SEQUENCE GERENTE_GERENTE_ID_seq RESTART WITH 1; INSERT INTO GERENTE (EMAIL, CPF_GERENTE, NOME_GER, SOBRENOME_GER) values ('<EMAIL>','99698151214','Leandro','<NAME>'); ALTER SEQUENCE FRANQUIA_FRANQUIA_ID_seq RESTART WITH 1; INSERT INTO FRANQUIA (GERENTE_ID, ENDERECO_ID, UNIDADE_FRANQUIA) values (1,1,'Morumbi'); ALTER SEQUENCE CARRO_CARRO_ID_seq RESTART WITH 1; INSERT INTO CARRO (FRANQUIA_ID, PLACA, MODELO, ANO, MARCA_CARRO) values (1,'MYE-5324','HOVER', '2011', 'GREAT WALL'); INSERT INTO CARRO (FRANQUIA_ID, PLACA, MODELO, ANO, MARCA_CARRO) values (1,'KET-5988','ULC PICAPE', '2017', 'EFFA'); INSERT INTO CARRO (FRANQUIA_ID, PLACA, MODELO, ANO, MARCA_CARRO) values (1,'BEL-8931','Camper', '2006', 'Envemo'); ALTER SEQUENCE CLIENTE_CLIENTE_ID_seq RESTART WITH 1; INSERT INTO CLIENTE (CPF_CLIENTE, CELULAR, ENDERECO_ID, NOME_CLI, SOBRENOME_CLI) values ('76740949522','79998368381',2,'Aline', '<NAME>'); INSERT INTO CLIENTE (CPF_CLIENTE, CELULAR, ENDERECO_ID, NOME_CLI, SOBRENOME_CLI) values ('69396135283','96995710062',3,'Benjamin', 'Ian'); INSERT INTO CLIENTE (CPF_CLIENTE, CELULAR, ENDERECO_ID, NOME_CLI, SOBRENOME_CLI) values ('34515611909','94988242210',4,'Guilherme', 'Antonio'); ALTER SEQUENCE FUNCIONARIO_FUNCIONARIO_ID_seq RESTART WITH 1; INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Francisco', 'Lorenzo', 'repositor', 1, '23/08/1961', '90086033301'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Nicolas', 'Henry', 'repositor', 1, '26/02/1963', '52588732771'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Marlene', 'Luana', 'repositor', 1, '22/08/1961', '28268557516'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Danilo', 'Elias', 'repositor', 1, '20/04/1965', '02589683898'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Clara', 'Aurora', 'repositor', 1, '05/02/1960', '65431718398'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Eliane', 'Amanda', 'caixa', 1, '08/09/1969', '46090565776'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Carolina', 'Carolina', 'caixa', 1, '14/06/1957', '14799449125'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Luiz', 'Arthur', 'caixa', 1, '01/04/1986', '82795860406'); INSERT INTO FUNCIONARIO (NOME_FUNC, SOBRENOME_FUNC, CARGO, FRANQUIA_ID, DATA_ADMISSAO, CPF_FUNC) values ('Rafael', 'Caue', 'caixa', 1, '02/08/1974', '51186969172'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (1, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (2, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (3, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (4, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (5, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (6, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (7, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (8, '1650'); INSERT INTO CLT (FUNCIONARIO_ID, SALARIO) values (9, '1650'); ALTER SEQUENCE VENDA_VENDA_ID_seq RESTART WITH 1; INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (1, 1, 1, '3', '443', '22/05/2020', 1); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (2, 1, 2, '5', '229', '22/05/2020', 2); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (3, 1, 3, '2', '250', '22/05/2020', 2); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (4, 1, 2, '4', '485', '22/05/2020', 3); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (5, 1, 3, '4', '402', '22/05/2020', 2); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (6, 1, 3, '4', '319', '22/05/2020', 5); INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values (7, 1, 1, '3', '375', '22/05/2020', 4); ALTER SEQUENCE FORNECEDOR_FORNECEDOR_ID_seq RESTART WITH 1; INSERT INTO FORNECEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values ('Limpeza SA', '50328594000132', '<EMAIL>'); INSERT INTO FORNECEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values ('Bebidas SA', '75847095000182', '<EMAIL>'); INSERT INTO FORNECEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values ('Alimentos SA', '74125597000137', '<EMAIL>'); INSERT INTO FORNECEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values ('Panelas SA', '42212013000174', '<EMAIL>'); INSERT INTO FORNECEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values ('Verduras SA', '01153338000146', '<EMAIL>'); ALTER SEQUENCE FORNECIMENTO_FORNECIMENTO_ID_seq RESTART WITH 1; INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 1, '12/05/2020'); INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 2, '12/05/2020'); INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 3, '12/05/2020'); INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 5, '12/05/2020'); INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 4, '12/05/2020'); INSERT INTO FORNECIMENTO (FRANQUIA_ID, FORNECEDOR_ID, DATA_FORN) values (1, 4, '12/05/2020'); ALTER SEQUENCE SECAO_SECAO_ID_seq RESTART WITH 1; INSERT INTO secao (NOME_SEC) values ('Comestiveis'); INSERT INTO secao (NOME_SEC) values ('Limpeza'); INSERT INTO secao (NOME_SEC) values ('Utensilios'); ALTER SEQUENCE PRODUTO_PRODUTO_ID_seq RESTART WITH 1; INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (1, 1, 6, 1, 'Tramontina', '23', 'Panela de Pressao'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (1, 1, 6, 2, 'Tramontina', '75', 'Chaleira'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (1, 1, 5, 3, 'Tramontina', '5', 'Garfo e faca'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (2, 1, 5, 4, 'Tramontina', '4', 'Colher'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (2, 1, 1, 5, 'Candida', '36', 'detegente neutro'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (2, 1, 1, 6, 'Vanish', '44', 'Alvejante'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (2, 1, 2, 7, 'Skol', '67', 'Cerveja lata'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (3, 1, 2, 2, 'Brahma', '85', '<NAME>'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, VENDA_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (3, 1, 3, 3, 'Adria', '26', 'Macarrao'); INSERT INTO PRODUTO (SECAO_ID, FRANQUIA_ID, FORNECIMENTO_ID, MARCA_PRODUTO, PRECO_UNITARIO, NOME_PRODUTO) values (3, 1, 4, 'marca 10', '89', 'Produto 10'); ALTER SEQUENCE PROMOCAO_PROMOCAO_ID_seq RESTART WITH 1;<file_sep>from typing import List from funcionarioService import Funcionario from postgreConnection import query, mutation from pydantic import BaseModel class Venda(BaseModel): funcionario_id: int fraquia_id: int cliente_id: int caixa: str valor: str data: str parcelas: int def get_vendas(): return query("SELECT * FROM VENDA;") def insert_venda(venda: Venda): return mutation(f'INSERT INTO VENDA (FUNCIONARIO_ID, FRANQUIA_ID, CLIENTE_ID, CAIXA, VALOR, DATA_VENDA, PARCELAS) values ({venda.funcionario_id}, {venda.franquia_id}, {venda.cliente_id}, \'{venda.caixa}\', \'{venda.valor}\', \'{venda.data}\', {venda.parcelas});') <file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Fornecedor(BaseModel): nome: str cnpj: str email: str def getFornecedor(): fornecedores = query("SELECT * FROM FORNECEDOR;") return fornecedores def insertFornecedor(fornecedor: Fornecedor): response = mutation(f'INSERT INTO FORNCEDOR (NOME_FORN, CNPJ_FORNECEDOR, EMAIL_FORNECEDOR) values (\'{fornecedor.nome}\', \'{fornecedor.cnpj}\', \'{fornecedor.email}\');') return response def deleteFornecedor(forn_id: int): return mutation(f'DELETE FROM FORNECEDOR f WHERE f.FORNECEDOR_ID = {forn_id};')<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Cliente(BaseModel): cpf: str celular: str endereco: str nome: str sobrenome: str def get_clientes(): clientes = query("SELECT * FROM CLIENTE;") return clientes def insert_cliente(cliente: Cliente): response = mutation(f'INSERT INTO CLIENTE (CPF_CLIENTE, CELULAR, ENDERECO_ID, NOME_CLI, SOBRENOME_CLI) values (\'{cliente.cpf}\',\'{cliente.celular}\',{cliente.endereco},\'{cliente.nome}\', \'{cliente.sobrenome}\');') return response def delete_cliente(cliente_id: int): response = mutation(f'DELETE FROM CLIENTE c WHERE c.CLIENTE_ID = {cliente_id};') return response<file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Franquia(BaseModel): gerente_id: int endereco_id: int unidade: str def get_franquias(): return query('SELECT * FROM FRANQUIA;')<file_sep>import psycopg2 from psycopg2.extras import RealDictCursor connection = psycopg2.connect(host='localhost', database='mercados', user='postgres', password='<PASSWORD>') cursor = connection.cursor(cursor_factory=RealDictCursor) def mutation(sql): try: cursor.execute(sql) connection.commit() print("Mutation realizada com sucesso") return except Exception as e: raise Exception("Erro na mutation: " + str(e)) def query(sql): try: cursor.execute(sql) response = cursor.fetchall() print("Query realizada com sucesso") return response except Exception as e: raise Exception("Erro na query: " + str(e)) <file_sep>from postgreConnection import query, mutation from pydantic import BaseModel class Entrega(BaseModel): carro_id: int venda_id: int endereco_id: int funcionario_id: int date: str def getEntrega(): entregas = query("SELECT * FROM ENTREGA;") return entregas def insertEntrega(entrega: Entrega): response = mutation(f'INSERT INTO ENTREGA (CARRO_ID, VENDA_ID, ENDERECO_ID, FUNCIONARIO_ID, DATA_ENTREGA) values ({entrega.carro_id}, {entrega.venda_id}, {entrega.endereco_id}, {entrega.funcionario_id}, {entrega.date});') return response def deleteEntrega(entrega_id: int): response = mutation(f'DELETE FROM ENTREGA e WHERE e.ENTREGA_ID = {entrega_id};') return response <file_sep>from postgreConnection import query def get_all_secoes(): secoes = query("SELECT s.secao_id, s.nome_sec, array_agg(p.produto_id) as produtos\ FROM SECAO s INNER JOIN produto p ON p.secao_id = s.secao_id\ GROUP BY s.secao_id, s.nome_sec;") return secoes
972848010afd7760e39fe79a5b02cb4153017bb2
[ "Markdown", "SQL", "Python" ]
16
Python
Joao-Pinheiro07/BD2-Sistema-BackEnd
00d335e0e7791b72b4904c2122f55a8e00247678
964215d8369d7501d73b4116e95c9e5aa950e309
refs/heads/master
<repo_name>Yeonji-Lee/Member0628<file_sep>/src/main/java/kh/spring/chat/HttpSessionSetter.java package kh.spring.chat; import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; public class HttpSessionSetter extends ServerEndpointConfig.Configurator{ //extends 한거 : 이너클래스 @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession hsession = (HttpSession) request.getHttpSession(); //로그인한 사람만 채팅에 접속하도록하고, 고정된 아이디로 채팅함. //1. 이 세션값을 sec에 저장해놓고, sec.getUserProperties().put("hsession", hsession); System.out.println(hsession); System.out.println(sec); System.out.println(sec.getUserProperties()); //2. onOpen 에 EndpointConfig 를 매개변수로 받는다. // Handshake 해주는 이 클래스가 연결고리! // 꼭 이 방법만 있는건 아니다. } } <file_sep>/src/main/java/kh/spring/impl/MemberDAOImpl.java package kh.spring.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.stereotype.Component; import kh.spring.dao.MemberDAO; import kh.spring.dto.MemberDTO; @Component public class MemberDAOImpl implements MemberDAO { //1. JdbcTemplate @Autowired private JdbcTemplate template; //2. SqlSessionTemplate @Autowired private SqlSessionTemplate sst; public int insertMem(MemberDTO dto) { // String sql = "insert into member values (?,?,?,?,?,?,?,?,?)"; // return template.update(sql, dto.getId(), dto.getPw(), dto.getName(), dto.getImage(), dto.getPhone(), dto.getEmail(), // dto.getZipcode(), dto.getAddr1(), dto.getAddr2()); return sst.insert("MemberDAO.insert", dto); } public int idCheck(String id) { // String sql = "select count(*) from member where id = ?"; // return template.queryForObject(sql, Integer.class, id); return sst.selectOne("MemberDAO.idCheck", id); } public int loginCheck(String id, String pw) { // String sql = "select count(*) from member where id = ? and pw = ?"; // return template.queryForObject(sql, Integer.class, id, pw); Map<String, String> map = new HashMap<String, String>(); map.put("id", id); map.put("pw", pw); return sst.selectOne("MemberDAO.loginCheck", map); } public MemberDTO myPage(String id) { // String sql = "select * from member where id = ?"; // // return template.query(sql, new Object[] {id}, new ResultSetExtractor<MemberDTO>() { // @Override // public MemberDTO extractData(ResultSet rs) throws SQLException, DataAccessException { // MemberDTO dto = new MemberDTO(); // if(rs.next()) { // dto.setPw(rs.getString(2)); // dto.setName(rs.getString(3)); // dto.setImage(rs.getString(4)); // dto.setPhone(rs.getString(5)); // dto.setEmail(rs.getString(6)); // dto.setZipcode(rs.getInt(7)); // dto.setAddr1(rs.getString(8)); // dto.setAddr2(rs.getString(9)); // } // return dto; // } // }); return sst.selectOne("MemberDAO.myPage", id); } public int update(String id, String modifiedImg) { // String sql = "update member set image=? where id=?"; // return template.update(sql, modifiedImg, id); Map<String,String> map = new HashMap<String, String>(); map.put("id", id); map.put("modifiedImg", modifiedImg); return sst.update("MemberDAO.update",map); } public int modify(MemberDTO dto, String id) { String sql = "update member set pw=?, name=?, phone=?, email=?, zipcode=?, addr1=?, addr2=? where id=?"; return template.update(sql, dto.getPw(), dto.getName(), dto.getPhone(), dto.getEmail(), dto.getZipcode(), dto.getAddr1(), dto.getAddr2(), id); //return sst.update("MemberDAO.modify"); } } <file_sep>/src/main/java/kh/spring/impl/BoardDAOImpl.java package kh.spring.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import kh.spring.dao.BoardDAO; import kh.spring.dto.BoardDTO; @Repository public class BoardDAOImpl implements BoardDAO{ @Autowired private JdbcTemplate template; public int insert(BoardDTO dto) { String sql = "insert into board values (board_seq.nextval,?,?,?,?,?)"; return template.update(sql, dto.getTitle(), dto.getContents(), dto.getWriter(), dto.getWritedate(), dto.getViewcount()); } // public String writer(String id) { // String sql = "select name from member where id=?"; // return template.queryForObject(sql, String.class); // } public List<BoardDTO> boardList(int start, int end){ String sql = "select * from (select row_number() over(order by seq desc) as rown, board.* from board) where rown between ? and ?"; return template.query(sql, new Object[] {start,end}, new RowMapper<BoardDTO>() { @Override public BoardDTO mapRow(ResultSet rs, int rowNum) throws SQLException { BoardDTO dto = new BoardDTO(); dto.setSeq(rs.getInt(2)); dto.setTitle(rs.getString(3)); dto.setContents(rs.getString(4)); dto.setWriter(rs.getString(5)); dto.setWritedate(rs.getString(6)); dto.setViewcount(rs.getInt(7)); return dto; } }); } public int viewCount(int seq) { String sql = "update board set viewcount=viewcount+1 where seq=?"; return template.update(sql, seq); } public BoardDTO read(int seq) { String sql = "select * from board where seq = ?"; return template.query(sql, new Object[]{seq}, new ResultSetExtractor<BoardDTO>() { @Override public BoardDTO extractData(ResultSet rs) throws SQLException, DataAccessException { BoardDTO dto = new BoardDTO(); if(rs.next()) { dto.setSeq(rs.getInt(1)); dto.setTitle(rs.getString(2)); dto.setContents(rs.getString(3)); dto.setWriter(rs.getString(4)); dto.setWritedate(rs.getString(5)); dto.setViewcount(rs.getInt(6)); } return dto; } }); } public int modify(String title, String contents, int seq) { String sql = "update board set title=?, contents=? where seq=?"; return template.update(sql, title, contents, seq); } public int recordTotalCount() { String sql = "select count(*) from board"; return template.queryForObject(sql, int.class); } public int delete(int seq) { String sql = "delete board where seq = ?"; return template.update(sql, seq); } static int recordCountPerPage = 5; public static int startNavi = 0; public static int endNavi = 0; public List<String> getNavi(int currentPage) throws Exception { int recordTotalCount = this.recordTotalCount(); //DAO 로 리턴값받아오기 System.out.println(recordTotalCount); int recordCountPerPage = 5; int naviCountPerPage = 3; int pageTotalCount = 0; // 변수만드는 용 if(recordTotalCount % recordCountPerPage == 0) { pageTotalCount = recordTotalCount / recordCountPerPage; }else{ pageTotalCount = recordTotalCount / recordCountPerPage + 1 ; } // 현재페이지 오류 검출 및 정정 (공격을 막기 위해 작성하는 일종의 보안코드) if(currentPage < 1) { currentPage = 1; }else if(currentPage > pageTotalCount) { currentPage = pageTotalCount; } // 최소페이지 == currntPage / 최대페이지 == pageTotalCount // 내가 위치한 기준으로 네비게이터의 위치가 1~10 이라는것을 알아야함 // int startNavi; // int endNavi; startNavi = (currentPage-1)/naviCountPerPage*naviCountPerPage+1; // 10의자리는 그대로, 1의자리는 1 // 현재페이지에서 1을 빼야 한다. --> 30페이지가 21~30 에 있어야 하기 때문!! 31은 31~40에 있어야하는데, 계산하면 31이 된다. //(currentPage-1)/10*10+1; endNavi = startNavi + (naviCountPerPage-1); if(endNavi>pageTotalCount) { endNavi = pageTotalCount; } //총페이지가 15인데, endNavi가 20이라면 말이 안되기 때문에. System.out.println("현재위치 : " + currentPage); System.out.println("네비시작 : " + startNavi); System.out.println("네비 끝 : " + endNavi); boolean needPrev = true; boolean needNext = true; if(startNavi == 1) { needPrev = false; } if(endNavi == pageTotalCount) { needNext = false; } //StringBuilder sb = new StringBuilder(); List<String> list = new ArrayList<String>(); //지금까지 만든걸 String에 담아서 보낸다. if(needPrev) { list.add("<이전 "); } for(int i = startNavi ; i <= endNavi ; i++) { //sb.append("<a href='list.board?currentPage="+i+"'>"+i + "</a>"); //sb.append(i+""); list.add(i+""); } if(needNext) { //sb.append("다음>"); list.add("다음>"); } //return sb.toString(); return list; } } <file_sep>/src/main/java/kh/spring/ao/PerfCheckAdvice.java package kh.spring.ao; import java.util.Arrays; import javax.servlet.http.HttpSession; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Aspect public class PerfCheckAdvice { @Autowired public HttpSession session; @Pointcut("execution(* kh.spring.practice.HomeController.m*(..))") public void homeAll() {}; // @Pointcut("execution(* kh.spring.practice.HomeController.modify*(..))") // public void modifyAll() {}; @Around("homeAll()") public Object perfCheck(ProceedingJoinPoint pjp) { //before long startTime = System.currentTimeMillis(); Object retVal = null; Signature sign = pjp.getSignature(); if(session.getAttribute("loginID")==null) { return "home"; } try { retVal=pjp.proceed(); } catch (Throwable e) { e.printStackTrace(); } //after System.out.println(sign.getName()+" 배열값 : "+Arrays.toString(pjp.getArgs())); //if(sign.getName().equals("login")) long endTime = System.currentTimeMillis(); System.out.println(sign.getName()+" : "+(endTime-startTime)/1000.0 + "초 간 수행"); return retVal; } } <file_sep>/src/main/java/kh/spring/dto/MemberDTO.java package kh.spring.dto; import org.springframework.web.multipart.MultipartFile; public class MemberDTO { private String id; private String pw; private String name; private String image; private String phone; private String email; private int zipcode; private String addr1; private String addr2; public MemberDTO() { super(); // TODO Auto-generated constructor stub } public MemberDTO(String id, String pw, String name, String image, String phone, String email, int zipcode, String addr1, String addr2) { super(); this.id = id; this.pw = pw; this.name = name; this.image = image; this.phone = phone; this.email = email; this.zipcode = zipcode; this.addr1 = addr1; this.addr2 = addr2; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPw() { return pw; } public void setPw(String pw) { this.pw = pw; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getZipcode() { return zipcode; } public void setZipcode(int zipcode) { this.zipcode = zipcode; } public String getAddr1() { return addr1; } public void setAddr1(String addr1) { this.addr1 = addr1; } public String getAddr2() { return addr2; } public void setAddr2(String addr2) { this.addr2 = addr2; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
455a448ad988526cb260496eacb5560da16d5f19
[ "Java" ]
5
Java
Yeonji-Lee/Member0628
3d9f0b020da67819d825dcd5cac065455fccd883
aee7d862081e2e7d66b44fd56ba2745a626da9c3
refs/heads/master
<repo_name>mrJson01/Twilight.com<file_sep>/README.md # It is repository of site Twilight.com ~ NodeJS modules used as a environment for further development. <file_sep>/controllers/index-1.js const fs = require("fs"); var SibApiV3Sdk = require('sib-api-v3-sdk'); exports.home = (req,res)=>{ var svg = new Array(6); for(var i=1;i<=6;i++) { svg[i] = fs.readFileSync(`\public/homepage-images/svg/${i}.svg`,{encoding:'utf8'}); //encoding is neccesary } var script = fs.readFileSync('\public/homepageScript.js'); res.render("home",{svg:svg,script:script}); } exports.emailSender = (req,res)=>{ var defaultClient = SibApiV3Sdk.ApiClient.instance; // Configure API key authorization: api-key var apiKey = defaultClient.authentications['api-key']; apiKey.apiKey = '<KEY>'; // Uncomment below two lines to configure authorization using: partner-key // var partnerKey = defaultClient.authentications['partner-key']; // partnerKey.apiKey = 'YOUR API KEY'; var apiInstance = new SibApiV3Sdk.TransactionalEmailsApi(); var sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail(); // SendSmtpEmail | Values to send a transactional email sendSmtpEmail = { to: [{ email: '<EMAIL>', name: '<NAME>' }], templateId: 6, params: { name: req.body.name, content: req.body.content }, headers: { 'X-Mailin-custom': 'custom_header_1:custom_value_1|custom_header_2:custom_value_2' } }; apiInstance.sendTransacEmail(sendSmtpEmail).then(function(data) { console.log('API called successfully. Returned data: ' + data); }, function(error) { console.error(error); }); res.redirect('/'); }<file_sep>/public/homepageScript.js const contentplate = document.querySelectorAll('#contentbox .contentplate'); window.onscroll = function(){ var scrollY = window.scrollY; var menuTop = document.querySelector('#stickymenu').offsetTop; //BOTH ARE NUMBERS var menuBottom = menuTop+(document.querySelector('#stickymenu').offsetHeight); var menu = document.querySelector('#stickymenu .sticky'); var stickymenuHeight = menu.offsetHeight; if(scrollY>menuTop){ menu.classList.add('stickytrue'); menu.classList.remove('stickybottom'); if(scrollY+stickymenuHeight>menuBottom){ menu.classList.remove('stickytrue'); menu.classList.add('stickybottom'); } } else { menu.classList.remove('stickytrue'); menu.classList.remove('stickybottom'); } //CHECK WHICH PARAGRAPH IS ON SCREEN for( val of contentplate){ if(( scrollY >=val.offsetTop)&&(scrollY<=(val.offsetTop+val.offsetHeight))) { var queue = val.getAttribute('data-queue'); var indicator = document.querySelector(`#stickymenu .sticky .contentindicator[data-indicate="${queue}"]`); if(previous===undefined)previous = indicator; else{ previous.classList.remove("clicked"); previous = indicator; } indicator.classList.add('clicked'); } } } const contentindicator= document.querySelectorAll("#stickymenu .sticky .contentindicator"); var previous; for(val of contentindicator){ val.onclick = function(event){ var item = event.target.parentElement; var ishas = item.classList.contains("clicked"); if(!ishas) { //FIRST REMOVE PREVIOUS CLICK if(previous===undefined)previous=item; else{ previous.classList.remove('clicked'); previous = item; } item.classList.add('clicked'); } } }
55aec636481557a18d904aac7ce3109ce9ae2e9a
[ "Markdown", "JavaScript" ]
3
Markdown
mrJson01/Twilight.com
75c0582f036181eadaf2c3c256ef47385fd5f59b
962ae78ac5daea9782be8aa3c09d462d228cf809
refs/heads/master
<repo_name>ferdirn/learnyounode<file_sep>/myfirstio.js var fs = require('fs') var file = process.argv[2] var buf = fs.readFileSync(file) var str = buf.toString() var strArray = str.split('\n') console.log(strArray.length - 1) <file_sep>/program.js if (process.argv.length > 2) { var total = 0; for (i=2; i<process.argv.length; i++) { total += +process.argv[i]; } } console.log(total);
6648bea3c914595c304ea7e355689eef168374dd
[ "JavaScript" ]
2
JavaScript
ferdirn/learnyounode
dec21ac8321d8d51447f3f6b200a1e9d85253688
bf57737b7bc1d6dd1760be07d68da6678c6544fe
refs/heads/main
<file_sep># cka-material This repo contains information for CKA exams. It has vagrant files and tests that can be used for practice. It takes inspiration on other repositories and tries to provide real 'practice-like' sessions with the use of custom vagrant boxes. It provides no answers, but feel free to open a PR and we'll review it for you. Sessions are taken weekly, and that's about the time this repo shall be updated. # Links and References * https://github.com/mmumshad/kubernetes-the-hard-way * https://github.com/kelseyhightower/kubernetes-the-hard-way * https://github.com/ContainerSolutions/kubernetes-examples<file_sep>#! /bin/bash cmd_b64="<KEY> # To see the command being executed, you can run this line # echo -ne $( echo -ne $cmd_b64 | base64 -d) $(echo -ne $cmd_b64 | base64 -d)<file_sep>Create a pod running a multi container pod with the following spec: pod name: multi-container container1 : c1 image: busybox container 2 : c2 image: redis container 3 : c3 imabe busybox Make container 1 prints out `date` command to /var/log/current_date.log Make container 3 prints /var/log/current_date.log content. ### Create imperatively a pod named nginx with image nginx:1.16 and QoS Guaranteed with memory limit of 100Mi and CPU limit of 0.3 ### Create a deployment named nginx with image nginx:1.16-alkine and replicas=3 Adjust the image to nginx:1.16-alpine and record the changes <file_sep>## Session Links Session video link: https://drive.google.com/file/d/1J1i1vjvaV2E4CSSsM2ew1KhJuX_IkmBJ/view?usp=drive_web Links used during the session: * [Kubernetes Docs](https://kubernetes.io/docs/home/) * [Walidshaari Guide](https://github.com/walidshaari/Kubernetes-Certified-Administrator?utm_source=pocket_mylist) * [Certification Site](https://training.linuxfoundation.org/certification/certified-kubernetes-administrator-cka/) ## Reproducing this session: First of all, install [vagrant](https://www.vagrantup.com/docs/installation) in your local machine using the appropriate package manager. After that, just do ``` cd vagrant vagrant up master-1 ``` After the machine is provisioned, just type ` vagrant ssh master-1 ` and you're ready to repeat the commands ran in this session. ### Command History ```language: bash sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list sudo apt-get update sudo apt-get install -y kubelet kubeadm kubectl sudo apt-get install docker.io -y sudo kubeadm config images pull sudo kubeadm init # Wont work because of not configured cgroup driver sudo journalctl -xeu kubelet sudo apt-get install -y kubelet=1.21.0-00 kubeadm=1.21.0-00 kubectl=1.21.0-00 --allow-downgrades sudo kubeadm reset #Now it works! sudo kubeadm init mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config kubectl get pods -A kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml kubectl get pods -A kubectl describe pod -n kube-system kube-flannel-ds-t2rst kubectl logs -n kube-system kube-flannel-ds-t2rst sudo kubeadm reset sudo kubeadm init --pod-network-cidr=10.1.0.0/24 sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml kubectl get pods -A kubectl run nginx --image=nginx kubectl get pods -A kubectl describe pods nginx kubectl get nodes kubectl get pod -o yaml nginx > pod.yaml #Adding a toleration to master Taint : NoSchedule vi pod.yaml kubectl apply -f pod.yaml kubectl describe node master-1 #[NOT SAFE FOR PRODUCTION ENVIRONMENTS] - Alternatively, remove the taint from master-1 kubectl taint master-1 node-role.kubernetes.io/master:NoSchedule- kubectl taint node master-1 node-role.kubernetes.io/master:NoSchedule- kubectl run nginx2 --image=nginx kubectl get pods -A ``` ## Session "Good Script" ``` sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kubernetes.list sudo apt-get update sudo apt-get install -y kubelet=1.21.0-00 kubeadm=1.21.0-00 kubectl=1.21.0-00 --allow-downgrades sudo kubeadm init --pod-network-cidr=10.1.0.0/24 mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml kubectl run nginx --image=nginx kubectl get pod -o yaml nginx > pod.yaml vi pod.yaml # and add a new toleration. ``` ## Practice tests After having node `master-1` up, bring up node `worker-1` with `vagrant up worker-1`. You can access `worker-1` with `vagrant ssh worker-1` Install kubeadm and join worker node `worker-1` into the cluster we just deployed. Will it work? Are there any necessary steps that need to be done? <details> <summary>Hint</summary> Only using <b>kubeadm join</b> from the worker node won't work, because kube-apiserver on <i>master-1</i> is only being advertised to an ip address that <i>worker-1</i> cannot reach. In order to make <i>master-1</i> available for worker-1, you should add the flag <b>--apiserver-advertise-address=192.168.5.11</b> to kubeadm init (can you find out why this ip address?). ``` </details> ## Disclaimer This vagrant file used in this session is provided by a port of kubernetes hard way to vagrant by @mmumshad (https://github.com/mmumshad/kubernetes-the-hard-way) <file_sep>### Volumes Create a PV with type ReadWriteOnce storage of 100Mi using hostpath `/tmp/logs` Run a pod named `processer` with image `busybox` in namespace `mynamespace` that writes the output of the command `ps -ef` to the file `/var/log/my.log` Make this file available at `/tmp/logs` Find the file on the virtual machine. Increase the capacity of the volume claim to 300Mi. What is going to happen ? ### RBAC Create a serviceAccount named `mysa` in namespace `mynamespace` make sure that service account can `list,get` the resources `pods,deployments,services,persistentvolumeclaims` from `mynamespace` and `that-other-namespace`. Check if the permissions are appropriate. ### Certificates Check when certificates expire on the cluster using kubeadm. renew apiserver certificate ### Ingress run `minikube addons enable ingress` Create a ConfigMap with a custom index.html(https://github.com/ContainerSolutions/k8s-hackathon-files/blob/main/session_2/index.html) file - Configmap name: front-end-content - Configmap content: index.html file Configure an nginx deployment with three replicas that mounts the configmap on `/usr/share/nginx/html` . Label it with `tier=frontend` Create a service called `nginx-service` that exposes this deployment as a `ClusterIp` Create an ingress that exposes `nginx-service` for host `*` and path `/twisted` test it using `curl http://$(minikube ip)/twisted` test it in your browser. ### Metrics run `minikube addons enable metrics-server` Write the command that gets the pods with label `tier=frontend` consuming the most cpus.<file_sep># Scheduling ## Preparation In order to run these practice exercises, have minikube installed. you can then start minikube with ``` minikube start ``` After that, check that your kubectl is currently pointed to minikube environment. this can be done with ``` kubectl get-contexts ``` Run the command below to mess with minikube scheduler ``` bash pre_script.sh ``` <details> <summary>Command content</summary> This command changes manifests definitions for kube-scheduler.yaml it is base64 encoded, but runs the following lines: <details> <summary>Command lines (Spoiler)</summary> pre_script.sh: minikube ssh --native-ssh=false -- sudo mv /etc/kubernetes/manifests/kube-scheduler.yaml /etc/kubernetes/kube-scheduler.yaml post_script.sh: minikube ssh --native-ssh=false -- sudo mv /etc/kubernetes/kube-scheduler.yaml /etc/kubernetes/manifests/kube-scheduler.yaml </details> </details> ## Exercise 1 * Create a nginx pod with image nginx. Why is it not running? * Manually assign the pod to a minikube node. Make sure the pod ends up running. ## Exercise 2 * try to fix the issue in the cluster yourself. You can ssh to the node with `minikube ssh`. You can fix it with `bash post_script.sh` if you like to skip this exercise. ## Exercise 3 * Taint the node `minikube` with the taint on-maintenance=yes:NoExecute. What happens to the pods created before? * Create a pod called nginx-tol with image nginx and tolerations for the specified taint above. Make sure the pod is running * Remove the taint from `minikube` node. Are all pods back to running? Why? ## Exercise 4 * Create pod `box-pod` from yaml file `pod_ex3.yml`. There is something wrong with it. Fix it without changing the file definition. <details> <summary> Hint </summary> Try labelling the node with kubectl label nodes </details> <file_sep>one="<KEY>" $(echo $one | base64 -d) <file_sep>## Session Links Session video link: https://drive.google.com/file/d/1MXbktXdN87y3f0Jp4G4EdgY1LV8D4Axy/view?usp=drive_web Slide Share: https://docs.google.com/presentation/d/1KqX4npvxOnZKG2ZBLpc5YShADzr5cAUPnC2gHI0pxC8/edit?usp=sharing Links used during the session: * [Scheduling Reference](https://kubernetes.io/docs/home/) * [KubeAPI Reference](https://github.com/walidshaari/Kubernetes-Certified-Administrator?utm_source=pocket_mylist) ## Reproducing this session: The session was recorded using two GCE VM instances. You can have set up a two-cluster node either following session1 practice exercise, spinning up two VMs in your favorite cloud, or (if your local machine handles it), using minikube: ``` minikube start --nodes=2 ``` To access your Node with minikube, simply type `minikube ssh <node-name>` ### Command History ```language: bash alias k=kubectl k run mgx --image=nginx --dry-run=client -o yaml > ngx.yaml k get nodes -o wide k run nginx --image=nginx k delete pod mgx nginx touch binding.json nano binding.json curl -X POST https://192.168.3.11:8080/api/v1/namespaces/default/pods/ngx/binding \\ -H "Content-Type: application/json" \\ -d @binding.json curl -X POST https://192.168.3.11:6443/api/v1/namespaces/default/pods/ngx/binding \\ -H "Content-Type: application/json" \\ -d @binding.json k get node ls -l k label node node01 app=nginx #k taint node controlplane k describe node controlplane | grep -i taint k taint node controlplane node-role.kubernetes.io/master:NoSchedule-\ k label node node01 node=master k label node controlplane node=master k label node node01 node=worker k label node node01 node=worker --overwrite k describe node controlplane | grep -i label k describe node node01 | grep -i label k describe node node01 | grep label k describe node node01 | grep Label k describe node node01 k describe node controlplane nano ngx.yaml k get pods k delete pod ngx k apply -f ngx.yaml k get pods -o wide k get pods --all-namespaces ``` ## Practice tests See practice folder.
ff9ecb9d8e1fd2a31b054f6946d09dfce72c6ca5
[ "Markdown", "Shell" ]
8
Markdown
ContainerSolutions/cka-material
d7f242f4a6f12accaee9a5fe95c2a99be6cd912f
832a78ee4744fd5d28cf134050bc1cfe27e40a42
refs/heads/master
<repo_name>jcarlnel/jcnelson_assignment2_mini2<file_sep>/Assignment2/jcnelson.assignment2/src/main/java/com/example/jacobnelson/assignment2/db/DatabaseConnector.java package com.example.jacobnelson.assignment2.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class DatabaseConnector { // database name private static final String DATABASE_NAME = "Mortgages"; private SQLiteDatabase database; // database object private DatabaseOpenHelper databaseOpenHelper; // database helper // public constructor for DatabaseConnector public DatabaseConnector(Context context) { // create a new DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(context, DATABASE_NAME, null, 1); } // end DatabaseConnector constructor // open the database connection public void open() throws SQLException { // create or open a database for reading/writing database = databaseOpenHelper.getWritableDatabase(); } // end method open // close the database connection public void close() { if (database != null) database.close(); // close the database connection } // end method close // inserts a new mortgage in the database public void insertMortgage(double payment, double total, String month, String year) { ContentValues newMortgage = new ContentValues(); newMortgage.put("monthlyPayment", payment); newMortgage.put("payoffTotal", total); newMortgage.put("payoffMonth", month); newMortgage.put("payoffYear", year); open(); // open the database database.insert("mortgages", null, newMortgage); System.out.println("Mortgage added: " + month + " " + year); close(); // close the database } // end method insertContact private class DatabaseOpenHelper extends SQLiteOpenHelper { // public constructor public DatabaseOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } // end DatabaseOpenHelper constructor // creates the contacts table when the database is created @Override public void onCreate(SQLiteDatabase db) { // query to create a new table named contacts String createQuery = "CREATE TABLE mortgages" + "(_id integer primary key autoincrement," + "monthlyPayment FLOAT, payoffTotal FLOAT, payoffMonth TEXT," + "payoffYear TEXT);"; db.execSQL(createQuery); // execute the query } // end method onCreate @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } // end method onUpgrade } // end class DatabaseOpenHelper } // end class DatabaseConnector <file_sep>/Assignment2/jcnelson.assignment2/src/main/java/com/example/jacobnelson/assignment2/ui/MainActivity.java package com.example.jacobnelson.assignment2.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Spinner; import com.example.jacobnelson.assignment2.R; import com.example.jacobnelson.assignment2.db.DatabaseConnector; import com.example.jacobnelson.assignment2.model.Calculator; import com.example.jacobnelson.assignment2.ui.CalculatedActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { DatabaseConnector db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); View v = findViewById(R.id.SubmitButton); v.setOnClickListener(this); db = new DatabaseConnector(MainActivity.this); } @Override public void onClick(View arg0){ if(arg0.getId() == R.id.SubmitButton){ int mortgage = Integer.valueOf(((EditText) findViewById(R.id.PurchasePrice)).getText().toString()).intValue(); int down = Integer.valueOf(((EditText) findViewById(R.id.DownPayment)).getText().toString()).intValue(); int term = Integer.valueOf(((EditText) findViewById(R.id.MortgageTerm)).getText().toString()).intValue(); float interest = Float.valueOf(((EditText) findViewById(R.id.InterestRate)).getText().toString()); int tax = Integer.valueOf(((EditText) findViewById(R.id.PropertyTax)).getText().toString()).intValue(); int insurance = Integer.valueOf(((EditText) findViewById(R.id.PropertyInsurance)).getText().toString()).intValue(); String month = ((Spinner) findViewById(R.id.Month)).getSelectedItem().toString(); int year = Integer.valueOf(((Spinner) findViewById(R.id.Year)).getSelectedItem().toString()).intValue(); //int year = ((Spinner) findViewById(R.id.Year)).getSelectedItemPosition() + 2000; Calculator c = new Calculator(mortgage, down, term, interest, tax, insurance, month, year); c.calculate(); db.insertMortgage(c.monthlyPayment, c.payoffTotal, c.endMonth, Integer.toString(c.endYear)); Intent intent = new Intent(this, CalculatedActivity.class); intent.putExtra("Calculator", c); this.startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } <file_sep>/Assignment2/settings.gradle include ':jcnelson.assignment2' <file_sep>/Assignment2/jcnelson.assignment2/src/main/java/com/example/jacobnelson/assignment2/ui/CalculatedActivity.java package com.example.jacobnelson.assignment2.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.example.jacobnelson.assignment2.R; import com.example.jacobnelson.assignment2.model.Calculator; public class CalculatedActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculated); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Calculator c = (Calculator) getIntent().getSerializableExtra("Calculator"); TextView monthlyPaymentText = (TextView) findViewById(R.id.monthlyPaymentVal); monthlyPaymentText.setText("$" + c.monthlyPayment); TextView totalPaymetText = (TextView) findViewById(R.id.totalPaymentVal); totalPaymetText.setText("$" + c.payoffTotal); TextView monthText = (TextView) findViewById(R.id.payoffMonth); monthText.setText(c.endMonth); TextView yearText = (TextView) findViewById(R.id.payoffYear); yearText.setText(Integer.toString(c.endYear)); View v = findViewById(R.id.backButton); v.setOnClickListener(this); } @Override public void onClick(View arg0){ if(arg0.getId() == R.id.backButton){ Intent intent = new Intent(this, MainActivity.class); this.startActivity(intent); } } }
d11f037c77d2375136b7f57f4321528bc801ed5e
[ "Java", "Gradle" ]
4
Java
jcarlnel/jcnelson_assignment2_mini2
f90095b5a33fe9b3267a83240488eacbfc9f2a2e
d4520f98ec50e2d7e732663a75806b42fb76ddf8
refs/heads/master
<file_sep>class PatchPanel < Trema::Controller def start(_args) @patch = [] File.open( "./patch-panel.conf" ).each_line do | each | if /~(\d+)\s+(\d+)$/=~ each @patch << [ $1.to_i, $2.to_i ] end end end def switch_ready( datapath_id ) @patch.each do | port_a, port_b | make_patch datapath_id, port_a, port_b end end private def make_patch( datapath_id, port_a, port_b ) send_flow_mod_add( datapath_id, :match => Match.new( :in_port => port_a), :action => SendOutPort.new( port_b ) ) send_flow_mod_add( datapath_id, :match => Match.new( :in_port => port_b), :action => SendOutPort.new( port_a ) ) end end <file_sep>class SwitchMonitor < Trema::Controller timer_event :show_switches, interval: 10.sec def start(_args) @switches = [] end def switch_ready( datapath_id ) @switches << datapath_id.to_hex logger.info "Switch #{ datapath_id.to_hex } is UP" end def switch_disconnected( datapath_id ) @swtich -= [datapath_id.to_hex] logger.info "Switch #{ datapath_id.to_hex } is DOWN" end private def show_switches logger.info "All switches = " + @switches.sort.join( ",") end end <file_sep>class LearningSwitch < Controller def start @fdb = { } end def packet_in( datapath_id, message ) @fdb[ message.macsa ] = message.in_port port_no = @fdb[ message.macda ] if port_no flow_mod datapath_id, message, port_no packet_out datapath_id, message, port_no else flood datapath_id, message end end private def flow_mod( datapath_id, message, port_no ) # ExactMatch includes mac, ip, tcp/udp... in real cases it shuold not ExactMatch send_flow_mod_add( datapath_id, :match => ExactMatch.from( message ), :action => SendOutPort.new( port_no ) ) end def packet_out( datapath_id, message, port_no ) send_packet_out( datapath_id, :packet_in => message, :actions => SendOutPort.new( port_no ) ) end def flood( datapath_id, message ) packet_out datapath_id, message, OFPP_FLOOD end end <file_sep># # Author: <NAME> <<EMAIL>> # # Copyright (C) 2008-2012 NEC Corporation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # $LOAD_PATH << File.join( File.dirname( __FILE__ ), "..", "ruby" ) $LOAD_PATH.unshift File.expand_path( File.join File.dirname( __FILE__ ), "..", "vendor", "ruby-ifconfig-1.2", "lib" ) require "rubygems" require "rspec" require "trema" require "trema/dsl/configuration" require "trema/dsl/context" require "trema/ofctl" require "trema/shell" require "trema/util" # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir[ "#{ File.dirname( __FILE__ ) }/support/**/*.rb" ].each do | each | require File.expand_path( each ) end include Trema def controller name Trema::App[ name ] end def vswitch name Trema::Switch[ name ] end def vhost name Trema::Host[ name ] end def send_packets source, dest, options = {} Trema::Shell.send_packets source, dest, options end include Trema::Util class Network def initialize &block @context = Trema::DSL::Parser.new.eval( &block ) end def run controller_class, &test begin trema_run controller_class test.call ensure trema_kill end end ################################################################################ private ################################################################################ def trema_run controller_class controller = controller_class.new if not controller.is_a?( Trema::Controller ) raise "#{ controller_class } is not a subclass of Trema::Controller" end Trema::DSL::Context.new( @context ).dump app_name = controller.name rule = { :port_status => app_name, :packet_in => app_name, :state_notify => app_name } sm = SwitchManager.new( rule, @context.port ) sm.no_flow_cleanup = true sm.run! @context.links.each do | name, each | each.add! end @context.hosts.each do | name, each | each.run! end @context.switches.each do | name, each | each.run! drop_packets_from_unknown_hosts each end @context.links.each do | name, each | each.up! end @context.hosts.each do | name, each | each.add_arp_entry @context.hosts.values - [ each ] end @th_controller = Thread.start do controller.run! end sleep 2 # FIXME: wait until controller.up? end def trema_kill cleanup_current_session @th_controller.join if @th_controller sleep 2 # FIXME: wait until switch_manager.down? end def drop_packets_from_unknown_hosts switch ofctl = Trema::Ofctl.new ofctl.add_flow switch, :priority => 0, :actions => "drop" @context.hosts.each do | name, each | ofctl.add_flow switch, :dl_type => "0x0800", :nw_src => each.ip, :priority => 1, :actions => "controller" end end end def network &block Network.new &block end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End: <file_sep># Trema Study ## Purpose To study openflow with Trema by myself. ## References - [OpenFlow実践入門](http://yasuhito.github.io/trema-book/) - [クラウド時代のネットワーク技術 OpenFlow実践入門 (Software Design plus)](http://www.amazon.co.jp/dp/4774154652/ref%3Dcm_sw_r_tw_dp_0SlTqb1NGYDN9) <file_sep># Traffic Monitor ## Description - Traffic Monitor count packets and packets sizes by MAC - Traffic Monitor show counters on terminal every 10 seconds ## How to run - Run a controller - % trema run ./traffic-monitor.rb -c ./traffic-monitor.conf - Send packets to hosts - % trema send_packets --source host1 --dest host2 --n_pkts 10 --pps 10 - % trema send_packets --source host2 --dest host1 --n_pkts 10 --pps 10 ## How to test - Run a test - % rspec -fs -c ./spec/traffic-monitor_spec.rb ## Reference - [Test first Trema-ja](https://github.com/trema/testfirst-trema-ja) <file_sep>class Counter def initialize @db = { } end def add( mac, packet_count, byte_count ) @db[ mac ] ||= { :packet_count => 0, :byte_count => 0 } @db[ mac ][ :packet_count ] += packet_count @db[ mac ][ :byte_count ] += byte_count end def each_pair( &block ) @db.each_pair &block end def get_packet_count( mac ) @db[ mac ] ||= { :packet_count => 0 } @db[ mac ][ :packet_count ] end def get_packet_size( mac ) @db[ mac ] ||= { :byte_count => 0 } @db[ mac ][ :byte_count ] end end <file_sep>require 'counter' class TrafficMonitor < Trema::Controller timer_event :show_counter, interval: 10.sec def start(_args) @fdb = {} @counter = Counter.new end def packet_in(datapath_id, message) @fdb[message.macsa] = message.in_port port_no = @fdb[message.macda] if port_no flow_mod datapath_id, message, port_no packet_out datapath_id, message, port_no else flood datapath_id, message end @counter.add message.macsa, 1, message.total_len end def flow_removed(_datapath_id, message) @counter.add message.match.dl_src, message.packet_count, message.byte_count end def get_packet_count(mac) @counter.get_packet_count Mac.new(mac) end def get_packet_size(mac) @counter.get_packet_size Mac.new(mac) end private def show_counter puts Time.now @counter.each_pair do | mac, counter | s = "#{mac} #{counter[:packet_count]} packets" s += "(#{counter[:byte_count]} bytes)" puts s end end def flow_mod(datapath_id, message, port_no) # ExactMatch includes mac, ip, tcp/udp... # in real cases it shuold not be ExactMatch send_flow_mod_add(datapath_id, hard_timeout: 10, match: ExactMatch.from(message), actions: SendOutPort.new(port_no)) end def packet_out(datapath_id, message, port_no) send_packet_out(datapath_id, packet_in: message, actions: SendOutPort.new(port_no)) end def flood(datapath_id, message) packet_out(datapath_id, message, OFPP_FLOOD) end end <file_sep>require File.join( File.dirname( __FILE__ ), "spec_helper" ) require "traffic-monitor" describe TrafficMonitor do around do | example | network { vswitch ( "tmsw" ) { datapath_id "0xabc" } vhost ( "host1" ) { mac "00:00:00:01:00:01" } vhost ( "host2" ) { mac "00:00:00:01:00:02" } link "tmsw", "host1" link "tmsw", "host2" }.run( TrafficMonitor ) { example.run } end it "transfers all packets" do send_packets "host1", "host2", :n_pkts => 10, :pps => 10 sleep 1 vhost( "host2" ).stats( :rx ).should have( 10 ).packets end it "counts sent packets" do send_packets "host1", "host2", :n_pkts => 10, :pps => 10 sleep 1 controller("TrafficMonitor").get_packet_count( "00:00:00:01:00:01" ).should == 10 end it "counts sent packet sizes" do send_packets "host1", "host2", :n_pkts => 10, :pps => 10 sleep 1 controller("TrafficMonitor").get_packet_size( "00:00:00:01:00:01" ).should == 640 end end <file_sep>Vagrant.configure('2') do |config| trema_home = '/home/vagrant/trema/' config.vm.box = 'hfm4/centos7' config.vbguest.auto_update = false config.vm.synced_folder '.', trema_home config.vm.provision 'shell', inline: <<-SHELL sudo yum update sudo yum install -y ruby ruby-devel gcc gcc-c++ git sudo yum install -y https://rdoproject.org/repos/rdo-release.rpm sudo yum install -y openvswitch sudo systemctl start openvswitch.service sudo systemctl enable openvswitch.service sudo gem install bundler SHELL config.vm.provision 'shell', privileged: false, inline: <<-SHELL mkdir -p #{trema_home} cd #{trema_home} bundle install --binstubs --path=vendor/bundle SHELL end
574be8ffe9038b1c18c95af2726c886b988e8bc6
[ "Markdown", "Ruby" ]
10
Ruby
otahi/trema-study
672922f2f1f5121b60bd4133ce542ebb8e37f189
cb58968b55c417fe72e34080b5304f4c85ff357a
refs/heads/master
<repo_name>GUH52/OldNetflix<file_sep>/contentBuilder.js $(document).ready(function(){ $.get("navigation.html", function(data){ $("body").prepend(data); $("body").append("<section id=\"vids\"></section>"); $.get("footer.html", function(data2){ $("body").append(data2); $.get("definetlynotadds.html", function(data3){ $("body").append(data3); }); }); }); $.get("clips.xml", function(xml){ var xmlDoc = $.parseXML(xml); $xml = $(xmlDoc); $video = $xml.find("show"); $video.each(function(){ $("#vids").append("<p>"+"<h3>"+$(this).find("title").text()+"</h3>"+"</p>"); }); }); });
ba859762a84dbafd497667603e6e4b204bbfef04
[ "JavaScript" ]
1
JavaScript
GUH52/OldNetflix
ab0b7f67934b6302536276eef13943eee9594300
9309cf19c2a4fe5f6ec8c5818b79b5a79f6c8bae
refs/heads/master
<repo_name>YugineS/PythonArkanoid<file_sep>/Paddle.py from State import State import Config import pygame class Paddle(object): def __init__(self): self.x = 0 self.y = 0 self.speed = 10 self.width = 120 self.height = 10 self.states = {Paddle.MoveLeft: Paddle.MoveLeft(self), Paddle.MoveRight: Paddle.MoveRight(self), Paddle.Stay: Paddle.Stay(self)} self.currentSate = self.states[Paddle.Stay] self.image = self.createPaddleImage() def draw(self, surface): surface.blit(self.image, (self.x, self.y)) def update(self, dt): self.currentSate.update(dt) def createPaddleImage(self): surface = pygame.Surface((self.width, self.height)) surface.fill((255, 255, 255)) return surface class MoveLeft(State): def __init__(self, paddle): self.paddle = paddle def update(self, dt): dx = self.paddle.speed / dt if self.paddle.x - dx >= 0: self.paddle.x = self.paddle.x - dx class MoveRight(State): def __init__(self, paddle): self.paddle = paddle def update(self, dt): dx = self.paddle.speed / dt if self.paddle.x + self.paddle.width + dx <= Config.SCREEN_WIDTH: self.paddle.x = self.paddle.x + dx class Stay(State): def __init__(self, paddle): self.paddle = paddle def update(self, dt): pass <file_sep>/GameLoop.py import Config import pygame from Paddle import Paddle x = pygame.init() print(x) screen = pygame.display.set_mode((Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT), pygame.DOUBLEBUF) clock = pygame.time.Clock() paddle = Paddle() def start(): while True: dt = clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: return screen.fill((0,0,0)) paddle.update(dt) paddle.draw(screen) pygame.display.update() start()
fb19b42e0305504f89239399a05e76d2c8c37737
[ "Python" ]
2
Python
YugineS/PythonArkanoid
633368fdeaf74c5f944a7b69d7d49d78e8beb2fb
bcd700c3aade13c8ac0721b5799ca1660a53ac61
refs/heads/master
<repo_name>sejaldua/intellivo<file_sep>/Intellivo-app/README.md ## Structure of intellivo-app ### This directory contains the content for the flask app. The structure is as follows: ```bash . ├── README.md ├── intellivo_package │   ├── __init__.py │   ├── forms.py │   ├── intellivoUser.db │   ├── models.py │   ├── routes.py │   ├── static │   │   ├── assets │   │   │   ├── logo\ icon.jpg │   │   │   └── logo.png │   │   └── main.css │   └── templates │   ├── README.md │   ├── about.html │   ├── form.html │   ├── home.html │   ├── layout.html │   ├── login.html │   ├── prefForm.html │   ├── profile.html │   ├── register.html │   └── userChats.html ├── old │   ├── forms.py │   ├── userdatabase.db │   └── usermanager.py ├── requirements.txt └── run.py ``` * intellivoUser.db - current database being used * models.py - contains classes for app's databases * routes - all website urls * run.py - main python file, used to run the app * forms.py - where all user forms are configured * templates - the html files that can have embedded jinja (language to connect with flask app data) * static - currently just has the main.css file * assets - all logos, images ## To Run Application 1. Make sure Flask and all dependencies are installed - Flask - Flask-SQLAlchemy (pip install -U Flask-SQLAlchemy) - database ORM - Flask login (pip install flask-login) - for login validation - Flask-Bcrypt (pip install bcrypt) - for password encryption - Flask-SocketIO (pip install -U flask-socketio) - for chatting via web sockets - Flask-WTF (pip install Flask-WTF) - for login, registration, and preference forms 2. In terminal: ```bash export FLASK_APP=run.py export export FLASK_DEBUG=1 flask run -h localhost -p (port you want to run application on) ``` Or you can do: ```bash python run.py ``` <file_sep>/Dockerfile FROM python:3 LABEL MAINTAINER="<NAME>" ENV FLASK_APP=run.py COPY Intellivo-app /intellivo-app COPY matching-algorithm/intellivo-matching-algo.ipynb /intellivo-app/intellivo-matching-algo.ipynb WORKDIR /intellivo-app RUN pip install -r requirements.txt CMD [ "flask", "run", "--host", "0.0.0.0" ] <file_sep>/run.sh #!/bin/bash docker run -p 8888:5000 sejaldua/intellivo <file_sep>/README.md # Intellivo ## Introduction Intellivo is a web application built with the Flask framework. The app facilitates an intellectual conversation between two users by providing starter questions in the chat room. Our matching algorithm intelligently matches users based on differences, similar to the idea behind a dating-app. ## Why Intellivo? While important intellectual conversations have been happening on social media platforms, the problem is that these difficult discussions tends to happen over social media, where we have platforms such as Instagram composed of friends and other like-minded individuals whose beliefs and values tend to align with their own. Intellivo works to elimintate the creation of this echo chamber by providing a safe place to both better educate ourselves and understand the origins of various perspectives. ## Our Awesome Team * [<NAME>](https://github.com/madhuakula) - mentor * [<NAME>](https://github.com/JSchechner) - mentor * [<NAME>](https://github.com/ccfernandes) - product manager * [<NAME>](https://github.com/ishani-chakraborty) - software developer * [<NAME>](https://github.com/sejaldua) - software developer * [<NAME>](https://github.com/ramir262) - software developer * [<NAME>](https://github.com/adelineleung) - UI/UX designer ## Setup There are 4 main features that we want to have implemented for our MVP 1. User authentication - Oauth 2.0 (not yet integrated) + Flask-Login 2. Chat room backend - Flask-SocketIO (not completely integrated) + SQLALCHEMY 3. Matching algorithm - Principle Component Analysis + K-Means Clustering in Python (not yet integrated) 4. Website interface - Flask, HTML, CSS, Bootstrap ## The simplest Docker setup * Anyone can pull the docker image and quickly run locally using the below command ```bash docker run --name intellivo-app -p 5000:5000 ishanichakraborty1/intellivo ``` * Then navigate to the [http://127.0.0.1:5000](http://127.0.0.1:5000) ## Roadmap This project is part of the internHacks 2020, a 6-week hackathon. Week 1: ideation & basic design Week 2: initial architectural and visual design Week 3: work on tasks asynchronously Week 4: user testing and structural implementation of the app Week 5: integration Week 6: deployment & design considerations ## Contributions <file_sep>/Intellivo-app/intellivo_package/forms.py from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, SelectMultipleField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from intellivo_package.models import User # class inherits FlaskForm class RegistrationForm(FlaskForm): firstname = StringField('Firstname', validators=[DataRequired(), Length(min=2, max=20)] ) lastname = StringField('Lastname', validators=[DataRequired(), Length(min=2, max=40)] ) email = StringField('Email', validators=[DataRequired(), Email()] ) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) confirm_password = PasswordField('<PASSWORD>', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Sign Up') # determines if email is unique/already taken def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('Email is taken. Register with a new one or log in.') class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) remember = BooleanField('Remember Me') submit = SubmitField('Log In') class ProfileForm(FlaskForm): age = SelectField(u"Your Age: ", [DataRequired()], choices=[("1", "Under 18"), ("2", "18-25"), ("3", "26-40"), ("4", "40+")], description=u"(Select an age range.)", render_kw={}) spirituality = SelectField(u"How would you describe your belief in a higher power?", [DataRequired()], choices=[("1", "atheist"),("2", "agnostic"), ("3", "spiritual but not religious"), ("4", "spiritual but also religious"), ("5", "devout religious")], description=u"(How spiritual are you?)", render_kw={}) location = SelectField(u"Location: ", [], choices=[("1", "West Coast (US)"), ("2", "Mountain Region (US)"), ("3", "Midwest (US)"), ("4", "East Coast (US)"), ("5", "Canada"), ("6", "South America"),("7", "Mexico"), ("8", "East Coast"), ("9", "Europe"), ("10", "Africa"), ("11", "Western Asia"), ("12", "Eastern Asia"), ("13", "Southern Asia"),("14", "Australia"),("15", "Other"),], description=u"(Your general place of residence)") engagement = SelectField(u"When newsworthy things are happening in the world, at what level do you engage?", [DataRequired()], choices=[("1", "I do not engage"), ("2", "I educate myself to understand the gist of it"), ("3", "In addition to educating myself, I initiate hard conversations with family and friends"), ("4", "I participate in community-wide events surrounding social justice issues"), ("5", "I am a full on activist: I organize events, create social media content, etc.")], description=u"(Your engagement to events around you.)", render_kw={}) submit = SubmitField('Save') <file_sep>/Intellivo-app/intellivo_package/routes.py from flask import render_template, request, url_for, flash, redirect # import the Flask class from intellivo_package import app, db, bcrypt, socketio from intellivo_package.models import User, UserPref from intellivo_package.forms import RegistrationForm, LoginForm, ProfileForm from flask_login import login_user, current_user, logout_user, login_required # home page @app.route("/") @app.route("/home") def home(): return render_template('home.html', title='Home') # about page @app.route("/about") def about(): return render_template('about.html', title='About') # register page @app.route("/register", methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('user')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = <PASSWORD>.generate_password_hash(form.password.data).decode('utf-8') user = User(firstname=form.firstname.data, lastname=form.lastname.data, email=form.email.data, password=<PASSWORD>) db.session.add(user) db.session.commit() flash('Your account has been created. You are now able to log in!', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) # login page @app.route("/login", methods=['GET', 'POST']) def login(): form=LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user) next_page = request.args.get('next') # redirect to next page if it exits (user tried accessing and is now logging in) return redirect(next_page) if next_page else redirect(url_for('profile')) else: flash('Login unsucessful. Please check credentials.', 'danger') return render_template('login.html', title='Login', form=form) # Preferences form (connected to UserPref). Access through profile page @app.route("/preferences", methods=['GET', 'POST']) def preferences(): form=ProfileForm() if form.validate_on_submit(): if current_user.is_authenticated: # check if row with user_id already exists. if exits, update row. else make new row user=current_user if UserPref.query.filter_by(user_id = user.id).first(): UserPref.query.filter_by(user_id = user.id).delete() userpref = UserPref(age=int(form.age.data), spirituality=int(form.spirituality.data), location=int(form.location.data), engagement=int(form.engagement.data), user=user) db.session.add(user) db.session.commit() return redirect(url_for('profile')) # was 'home' return render_template('form.html', title='Preferences', form=form) # profile page @app.route("/profile") @login_required def profile(): user = current_user userpref = UserPref.query.filter_by(user_id = user.id).first() return render_template('profile.html', title='Profile', userpref=userpref) # logout @app.route("/logout") def logout(): logout_user() return redirect(url_for('home')) #################### chat routes #################### @app.route('/chat', methods=["POST", "GET"]) @login_required def user(): return render_template('userChats.html', title='User Home') def messageReceived(methods=['GET', 'POST']): print('message was received!!!') @socketio.on('my event') def handle_my_custom_event(json, methods=['GET', 'POST']): print('received my event: ' + str(json)) socketio.emit('my response', json, callback=messageReceived) #################### end chat routes ####################<file_sep>/Intellivo-app/run.py from intellivo_package import app, socketio import os # run the app if __name__ == '__main__': # init_db() # Change the debug to False when deploying to production socketio.run(app, debug=False) port = int(os.environ.get('PORT', 5000)) app.run(debug=False, host='0.0.0.0', port=port)
2363d5007e9d9e2ca10541c815eeb11cfbd96334
[ "Markdown", "Python", "Dockerfile", "Shell" ]
7
Markdown
sejaldua/intellivo
7f6ed87576adbec5373be12a2ae7f7945046b0b6
6add8e1645a7d570ce0f0066303ffd806e4e2564
refs/heads/main
<file_sep>import java.util.Queue; public class Consumer implements Runnable{ Queue<Double> sharedQueue; public Consumer(Queue<Double> sharedQueue) { this.sharedQueue = sharedQueue; } @Override public void run() { while (true) { try { System.out.println("Consumer " + consumer()); } catch (InterruptedException e) { e.printStackTrace(); } } } private Double consumer() throws InterruptedException{ synchronized (sharedQueue) { if(sharedQueue.isEmpty()) { //если очередь пуста - ждем sharedQueue.wait(); } sharedQueue.notifyAll(); return sharedQueue.poll(); } } }
5983cddb6014e0a04c068fa5c269c646777fce58
[ "Java" ]
1
Java
tom-ato-s/8.2_habr
5d42065cb693f3e140cd806be91abdd457545210
ea99c82d565298d6de52ca1b4aa783d4b62cf916
refs/heads/master
<repo_name>fiedor92/PersonalTrainer<file_sep>/PersonalTrainer WatchKit Extension/InterfaceController.swift // // InterfaceController.swift // PersonalTrainer WatchKit Extension // // Created by <NAME> on 15/08/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { var exceriseCount = 0 @IBOutlet weak var exceriseLabel: WKInterfaceLabel! @IBOutlet weak var image: WKInterfaceImage! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() //image.startAnimatingWithImagesInRange(NSMakeRange(0, 17), duration: 2, repeatCount: 2) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func stopAnimation() { image.stopAnimating() } @IBAction func exceriseCounter(value: Float) { exceriseCount = Int(value) exceriseLabel.setText("\(exceriseCount) repeats") } override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? { if(segueIdentifier == "crunchesSegway"){ return ["excercise": "crunch", "repeats": exceriseCount] } else { return ["excercise": "twist", "repeats": exceriseCount] } } } <file_sep>/PersonalTrainer WatchKit Extension/AnimationController.swift // // AnimationController.swift // PersonalTrainer // // Created by appacmp on 15/08/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import Foundation import WatchKit class AnimationController: WKInterfaceController { @IBOutlet weak var animation: WKInterfaceImage! override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? { if(segueIdentifier == "crunchesSegway"){ animation.startAnimatingWithImagesInRange(<#imageRange: NSRange#>, duration: <#NSTimeInterval#>, repeatCount: <#Int#>) animation.startAnimatingWithImagesInRange(NSMakeRange(1, 17) duration: 2, repeatCount: 3) } else if (segueIdentifier == "twistsSegway"){ } } }<file_sep>/PersonalTrainer WatchKit Extension/PresentExcerciseController.swift // // PresentExcerciseController.swift // PersonalTrainer // // Created by appacmp on 15/08/15. // Copyright (c) 2015 <NAME>. All rights reserved. // import WatchKit import Foundation class PresentExcerciseController: WKInterfaceController { @IBOutlet weak var excerciseImage: WKInterfaceImage! @IBOutlet weak var wellDoneLabel: WKInterfaceLabel! var excerciseTime = 0 override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. if let dictionary = context as? NSDictionary, excercise = dictionary["excercise"] as? String, repeats = dictionary["repeats"] as? Int { excerciseImage.setImageNamed(excercise) excerciseImage.startAnimatingWithImagesInRange(NSMakeRange(0, 17), duration: 2, repeatCount: repeats) excerciseTime = 2 * repeats //excerciseTime = 2 } var timer = NSTimer.scheduledTimerWithTimeInterval(Double(excerciseTime), target: self, selector: Selector("endOfExcercise"), userInfo: nil, repeats: false) } func endOfExcercise(){ if excerciseTime > 0{ wellDoneLabel.setText("Well done!") } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
9c9bac2abb04e02d802a9f567c44a3fd1c26aee8
[ "Swift" ]
3
Swift
fiedor92/PersonalTrainer
33739c18053b28511d415f8d6846c541db265f35
61527333b2f89118698b7203b73f022b117c55ca
refs/heads/master
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "fa5a61508e5785f407bcbcaaf3564a64", "url": "/Cultist-Simulator-Translation-Tool/browserconfig.xml" }, { "revision": "6680d6da974e0229d247", "url": "/Cultist-Simulator-Translation-Tool/css/app.481c036f.css" }, { "revision": "<KEY>", "url": "/Cultist-Simulator-Translation-Tool/css/chunk-vendors.bb2c1d04.css" }, { "revision": "eeed63e5594d14af31b11f8686e16edd", "url": "/Cultist-Simulator-Translation-Tool/index.html" }, { "revision": "6680d6da974e0229d247", "url": "/Cultist-Simulator-Translation-Tool/js/app.9468c2ee.js" }, { "revision": "<KEY>", "url": "/Cultist-Simulator-Translation-Tool/js/chunk-vendors.23f4f98b.js" }, { "revision": "9734c66c2dc9dfeb191e5ec430f73aed", "url": "/Cultist-Simulator-Translation-Tool/manifest.json" }, { "revision": "b6216d61c03e6ce0c9aea6ca7808f7ca", "url": "/Cultist-Simulator-Translation-Tool/robots.txt" } ]);
b8777f6271ab0d96ef6db27573840ed488cac1d3
[ "JavaScript" ]
1
JavaScript
Genroa/Cultist-Simulator-Translation-Tool
d06ceeec491f8c927c7faccef17ec511742311ac
48297bc420ceac80237e0b9e8fa392cb255e811a
refs/heads/master
<file_sep>sfToDoList[![Stories in Ready](https://badge.waffle.io/jjbernal/sfToDoList.png?label=ready&title=Ready)](http://waffle.io/jjbernal/sfToDoList) ========== A Symfony project to manage TODO lists. Requirements: -- * PHP 5.3 and up. * Database: SQLite. * Check if your system meets the software requirements for Symfony by browsing http://localhost:8000/sfcheck. How to run: -- 1. Execute the php bin/console server:run command. 2. Browse to the http://localhost:8000 URL. <file_sep>sfTODOList ========== Functional Specification -- <NAME> Last Updated: March, 20th 2016 Disclaimer -- This specification is by no means complete, and will be updated to reflect the state of the product. Overview -- A TODO list consists of several **tasks** ordered in a linear manner from top to bottom. The purpose of such a list is tracking tasks until completion. Users of the app are able to **view** their TODO lists, **add** tasks, **modify** and **tick** them off as complete. **Deleting** and **reordering** tasks are a plus. >### Technical note To be able to hide tasks instead of deleting them, there is a boolean **complete** field that is set to *false* when the task has been ticked off. There is also implicit an **id** unique for each task. In order to reorder tasks there is a numeric **position** field that holds the current order of the task in the TODO list. Main features -- * Add, modify, complete and reorder tasks. * Each **task** has a *title*, a *description*, and *deadline*, being *title* the only mandatory input, and the rest optional. * (Enhancements) * To better classify tasks, they can also have a *category* and *tags* associated. * Tracking of *created date* and *finished date*. ### Viewing tasks Just after login, the user can see his/her TODO list. By default, only unfinished tasks are visible. If there are no tasks in the TODO list yet, the user is invited to enter a new one. >#### Technical note API endpoint: /task/list method: GET ### Adding tasks To add a new task, the user clicks on the + button at the bottom of the list (or top if it is empty) and a text input appears on spot, letting the user type the title. Then the user can add the task by clicking the button *Add task* or hitting the *enter* key. More advanced users can click the *Show details* button and fill the form inputs at will, then add the task by clicking *Add* or hitting the *Enter* key when the focus is in the last field. Anyways, the **Title** field is mandatory. If the user does not input any title, a message error appears to inform the user of the problem and no task is added to the list. >#### Technical note API endpoint: /task/new/{title}/{description}/{...} method: POST ### Modifying tasks To modify a task, the user clicks on the *title* text, and editing controls analogous to adding a task appear. >#### Technical note API endpoint: /task/modify/{id}/{title}/{description}/{...} method: POST ### Ticking (finishing) tasks off The user can tick a task off just by clicking the checkbox located to the left of it. Then an animation makes the task's text get striked through and the whole box that represents the task dissapears from view. >#### Technical note API endpoint: /task/complete/{id} method: POST ### Reordering tasks >#### Technical note API endpoint: /task/reorder/{id1}/{order1}/{id2}/{order2} method: POST Screen design -- These are just quick mockups for reference. ### Empty list ![Empty list image](images/empty_list.png) ### Simple form for adding a task ![Simple form image](images/simple_form.png) ### Complete form for adding a task ![Complete form image](images/complete_form.png) <file_sep><?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Task * * @ORM\Table(name="task") * @ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository") */ class Task { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="title", type="string", length=255) */ private $title; /** * @var string * * @ORM\Column(name="description", type="text", nullable=true) */ private $description; /** * @var \DateTime * * @ORM\Column(name="deadline", type="datetime", nullable=true) */ private $deadline; /** * @var bool * * @ORM\Column(name="complete", type="boolean") */ private $complete; /** * @var int * * @ORM\Column(name="position", type="integer", nullable=true, unique=true) */ private $position; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set title * * @param string $title * * @return Task */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set description * * @param string $description * * @return Task */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set deadline * * @param \DateTime $deadline * * @return Task */ public function setDeadline($deadline) { $this->deadline = $deadline; return $this; } /** * Get deadline * * @return \DateTime */ public function getDeadline() { return $this->deadline; } /** * Set complete * * @param boolean $complete * * @return Task */ public function setComplete($complete) { $this->complete = $complete; return $this; } /** * Get complete * * @return bool */ public function getComplete() { return $this->complete; } /** * Set position * * @param integer $position * * @return Task */ public function setPosition($position) { $this->position = $position; return $this; } /** * Get position * * @return int */ public function getPosition() { return $this->position; } }
0bcaddea614e916409c0c1be9d40d209ef4cf118
[ "Markdown", "PHP" ]
3
Markdown
jjbernal/sfToDoList
640f9295e63f43f5b663d49dc70f153707d48b5b
fd7e60d2aca12f785716aef0b233f25f913471b8
refs/heads/main
<repo_name>matiascoronados/mineriaLab4<file_sep>/lab3.R #install.packages('bnlearn') require(bnlearn) #################################################################################### #################################################################################### #################################################################################### ######### NUESTRO ######### #################################################################################### #################################################################################### #################################################################################### require(bnlearn) #install.packages("usethis") #usethis::use_course("https://goo.gl/x9rdpD") data(alarm) bif <- read.bif("/Users/matiascoronado/Desktop/mineriaLab4/ALARM/alarm.bif") net <- read.net("/Users/matiascoronado/Desktop/mineriaLab4/ALARM/alarm.net") dsc <- read.dsc("/Users/matiascoronado/Desktop/mineriaLab4/ALARM/alarm.dsc") rds <- readRDS("/Users/matiascoronado/Desktop/mineriaLab4/ALARM/alarm.rds") #""""""""""Pre-procesamiento"""""""""" data = alarm[,c(1:37)] #Lo vamos a entregar. modelstring = paste0("[HIST|LVF][CVP|LVV][PCWP|LVV][HYP][LVV|HYP:LVF][LVF]", "[STKV|HYP:LVF][ERLO][HRBP|ERLO:HR][HREK|ERCA:HR][ERCA][HRSA|ERCA:HR][ANES]", "[APL][TPR|APL][ECO2|ACO2:VLNG][KINK][MINV|INT:VLNG][FIO2][PVS|FIO2:VALV]", "[SAO2|PVS:SHNT][PAP|PMB][PMB][SHNT|INT:PMB][INT][PRSS|INT:KINK:VTUB][DISC]", "[MVS][VMCH|MVS][VTUB|DISC:VMCH][VLNG|INT:KINK:VTUB][VALV|INT:VLNG]", "[ACO2|VALV][CCHL|ACO2:ANES:SAO2:TPR][HR|CCHL][CO|HR:STKV][BP|CO:TPR]") dag = model2network(modelstring) graphviz.plot(dag, layout = "dot") # BLACK LIST bl1 = tiers2blacklist(list("HYP", "LVF", "APL","ANES", c("PMB","INT","KINK","DISC"))) bl2 = tiers2blacklist(list("PMB","INT","KINK","DISC", c("HYP", "LVF", "APL","ANES"))) bl3 = tiers2blacklist(list("HYP", "LVF", c("APL","ANES"))) bl4 = tiers2blacklist(list("APL","ANES", c("HYP", "LVF"))) bl5 = tiers2blacklist(list("HYP", c("LVF"))) bl6 = tiers2blacklist(list("LVF", c("HYP"))) bl7 = tiers2blacklist(list("APL", c("ANES"))) bl8 = tiers2blacklist(list("ANES", c("APL"))) bl9 = tiers2blacklist(list("PMB", "INT", c("KINK","DISC"))) bl10 = tiers2blacklist(list("KINK", "DISC", c("PMB","INT"))) bl11 = tiers2blacklist(list("PMB", c("INT"))) bl12 = tiers2blacklist(list("INT", c("PMB"))) bl13 = tiers2blacklist(list("KINK", c("DISC"))) bl14 = tiers2blacklist(list("DISC", c("KINK"))) bl15 = tiers2blacklist(list("LVF", c("CVP"))) bl16 = tiers2blacklist(list("LVF", c("PCWP"))) bl17 = tiers2blacklist(list("PCWP", c("LVF"))) bl =rbind(bl1,bl2,bl3,bl4,bl5,bl6,bl7,bl8,bl9,bl10,bl11,bl12,bl13,bl14) #WHITE LIST wl1 <- tiers2blacklist(list("CO",c("STKV","HR"))) wl2 <- tiers2blacklist(list("HYP",c("BP","PRSS"))) wl3 <- tiers2blacklist(list("LVF",c("HRBP","HREK","HRSA","HR"))) wl4 <- tiers2blacklist(list("PMB",c("PAP","PVS"))) wl <- rbind(wl1,wl2,wl3,wl4) ####################### Algoritmo Hill-Climbing #UTILIZANDO BLACK/WHITE LIST res1 <- hc(data,blacklist = bl, whitelist = wl) fittedbn1 <- bn.fit(res1,data=data) par(mfrow = c(1, 2)) graphviz.compare(dag, res1, layout = "fdp" ,shape = "ellipse", main = c("DAG original", "DAG propio")) BIC1 <- score(res1,data) BIC1 #SIN BLACK/WHITE LIST res2 <- hc(data) fittedbn1 <- bn.fit(res2,data=data) par(mfrow = c(1, 2)) graphviz.compare(res2, res1, layout = "fdp" ,shape = "ellipse", main = c("Sin restricciones", "Con restricciones")) BIC2 <- score(res2,data) BIC2 #########uscar que es esto############### #logLik.hc1 <- logLik(res1, data) ######################### Algoritmo Max-Min Hill Climbing res1 <- mmhc(data,blacklist = bl, whitelist = wl) fittedbn1 <- bn.fit(res1,data=data) par(mfrow = c(1, 2)) graphviz.compare(dag, res1, layout = "fdp" ,shape = "ellipse", main = c("DAG original", "DAG propio")) logLik.hc1 <- logLik(res1, data) BIC1 <- score(res1,data) BIC1 ######### NO SIRVE PARA NUESTRO CONTEXTO ##Max-Min Parents & Children (NO SIRVE) res1 <- mmpc(data,blacklist = bl, whitelist = wl) fittedbn1 <- bn.fit(res1,data=data) par(mfrow = c(1, 2)) graphviz.compare(dag, res1, layout = "fdp" ,shape = "ellipse", main = c("DAG original", "DAG propio")) BIC1 <- score(res1,data) #BIC3 #calculoF3 ################ # Metodo definitivo ############### res1 <- hc(data,blacklist = bl, whitelist = wl) fittedbn1 <- bn.fit(res1,data=data) fittedbn2 <- bn.fit(res2,data=data) par(mfrow = c(1, 2)) graphviz.compare(res1, dag, layout = "circo" ,shape = "ellipse", main = c("DAG original", "DAG propio")) ### Query ### ######## Aqui demostramos propagacion de la evidencia #Da buena #Si el paciente necesita ser entubado cpquery(fittedbn1,evidence = (ACO2 == "LOW" & PAP == "LOW"),event = (INT == "NORMAL")) cpquery(fittedbn1,evidence = (ACO2 == "LOW"),event = (INT == "NORMAL")) #YO cpquery(fittedbn1,evidence = (PCWP == "HIGH" & LVF == "FALSE"),event = (HYP == "TRUE")) cpquery(fittedbn1,evidence = (LVF == "FALSE"),event = (HYP == "TRUE")) #BRYAN #cpquery(fittedbn1,evidence = (BP == "LOW" & CCHL == "HIGH"),event = (LVF == "TRUE")) #Da buena cpquery(bif,evidence = (ARTCO2 == "LOW" & PAP == "LOW"),event = (INTUBATION == "NORMAL")) #YO cpquery(bif,evidence = (ARTCO2 == "LOW"),event = (INTUBATION == "NORMAL")) cpquery(bif,evidence = (PCWP == "HIGH" & LVFAILURE == "FALSE"),event = (HYPOVOLEMIA == "TRUE")) #BRYAN #cpquery(bif,evidence = (BP == "LOW" & CATECHOL == "HIGH"),event = (LVFAILURE == "TRUE"))
13ac2017315fd139063d0b68582c218aa89e93ee
[ "R" ]
1
R
matiascoronados/mineriaLab4
c661f73e303eb43ea34651d75999b82b33fbaa14
c59b2d4dd683935ad651d8d798b371e58b1f291c
refs/heads/master
<file_sep>// // sonucCV.swift // bilgiYarismasi // // Created by <NAME> on 4.05.2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class sonucCV: UIViewController { @IBOutlet weak var cikisBtn: UIButton! @IBOutlet weak var anamenuBtn: UIButton! @IBOutlet weak var dogruSayisi: UILabel! @IBOutlet weak var yanlisSayisi: UILabel! @IBOutlet weak var toplamPuan: UILabel! var dogru = String() var yanlis = String() var toplamp = String() override func viewDidLoad() { super.viewDidLoad() anamenuBtn.layer.cornerRadius = 10 cikisBtn.layer.cornerRadius = 10 dogruSayisi.text = dogru yanlisSayisi.text = yanlis toplamPuan.text = toplamp } @IBAction func cikisActionBtn(_ sender: Any) { exit(0) } } <file_sep>// // kategoriViewController.swift // bilgiYarismasi // // Created by <NAME> on 12.05.2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class kategoriViewController: UIViewController { var isim = "" @IBAction func androidbtn(_ sender: Any) { isim = "ANDROID" } @IBAction func iosBtn(_ sender: UIButton) { isim = "IOS" } @IBAction func javaBtn(_ sender: UIButton) { isim = "JAVA" } @IBAction func csharpBtn(_ sender: UIButton) { isim = "C-SHARP" } /*@IBAction func phpBtn(_ sender: UIButton) { isim = "Php" }*/ @IBAction func htmlBtn(_ sender: UIButton) { isim = "HTML/CSS" } override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let dest : soruViewController = segue.destination as! soruViewController dest.kategoriAd = isim } } <file_sep>// // soruViewController.swift // bilgiYarismasi // // Created by <NAME> on 11.05.2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit struct soru { var soru : String! var cevaplar : [String]! var cevap : Int! } class soruViewController: UIViewController { @IBOutlet weak var sorusay: UILabel! @IBOutlet weak var soruText: UILabel! @IBOutlet var buttons: [UIButton]! @IBOutlet weak var kategori: UILabel! @IBOutlet weak var puan: UILabel! @IBOutlet weak var sure: UILabel! var zaman = Timer() var saniye = 11 var kategoriAd = String() var sorular = [soru]() var SoruNumarasi = Int() var CevapNumarasi = Int() var puanSayac: Int = 0 var ss:Int = 0 override func viewDidLoad() { super.viewDidLoad() buttons[0].titleLabel!.font = UIFont(name: "Arial", size: 12.0) buttons[1].titleLabel!.font = UIFont(name: "Arial", size: 12.0) buttons[2].titleLabel!.font = UIFont(name: "Arial", size: 12.0) buttons[3].titleLabel!.font = UIFont(name: "Arial", size: 12.0) kategori.text = kategoriAd if kategoriAd == "ANDROID"{ androidBolum() } if kategoriAd == "IOS" { iosBolum() } if kategoriAd == "JAVA" { javaBolum() } if kategoriAd == "C-SHARP"{ csharpBolum() } /* if kategoriAd == "Php" { phpbolumleri() }*/ if kategoriAd == "HTML/CSS" { htmlBolum() } zaman = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(zamanlama), userInfo: nil, repeats: true) randomSorular() } func zamanlama(){ saniye -= 1 sure.text = String(saniye) if saniye == 0 { randomSorular() saniye = 11 } } func randomSorular() { if sorular.count > 0 { SoruNumarasi = 0 CevapNumarasi = sorular[SoruNumarasi].cevap soruText.text = self.sorular[SoruNumarasi].soru for i in 0..<buttons.count{ buttons[i].setTitle(sorular[SoruNumarasi].cevaplar[i], for: .normal) buttons[i].backgroundColor = UIColor.white } sorular.remove(at: SoruNumarasi) ss += 1 sorusay.text = self.ss.description puan.text = self.puanSayac.description } else{ NSLog("Tamam") self.performSegue(withIdentifier: "sonucID", sender: self) zaman.invalidate() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "sonucID"{ let sonuckontrol = segue.destination as! sonucCV sonuckontrol.dogru = self.dogruSayisi.description sonuckontrol.yanlis = self.yanlisSayisi.description sonuckontrol.toplamp = self.puanSayac.description } } var dogruSayisi: Int = 0 var yanlisSayisi: Int = 0 var toplamPuan: Int = 0 func dogruCevap(){ dogruSayisi += 1 puanSayac += 10 NSLog("Doğru!") } func yanlisCevap() { yanlisSayisi += 1 NSLog("Yanlış!") } @IBAction func btn1(_ sender: UIButton) { if CevapNumarasi == 0 { buttons[0].backgroundColor = UIColor.green dogruCevap() } else { buttons[0].backgroundColor = UIColor.red yanlisCevap() } saniye = 11 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.randomSorular() }) } @IBAction func btn2(_ sender: UIButton) { if CevapNumarasi == 1 { buttons[1].backgroundColor = UIColor.green dogruCevap() } else{ buttons[1].backgroundColor = UIColor.red yanlisCevap() } saniye = 11 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.randomSorular() }) } @IBAction func btn3(_ sender: UIButton) { if CevapNumarasi == 2 { buttons[2].backgroundColor = UIColor.green dogruCevap() } else{ buttons[2].backgroundColor = UIColor.red yanlisCevap() } saniye = 11 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.randomSorular() }) } @IBAction func btn4(_ sender: UIButton) { if CevapNumarasi == 3 { buttons[3].backgroundColor = UIColor.green dogruCevap() } else{ buttons[3].backgroundColor = UIColor.red yanlisCevap() } saniye = 11 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.randomSorular() }) } @IBAction func next(_ sender: UIButton) { randomSorular() } func csharpBolum(){ sorular = [ soru(soru: "1) Program içerisinde farklı değerler alabilen ifadelere ne ad verilir?", cevaplar: ["A) Sabit","B) Değişken","C) Program ","D) Hiçbiri"], cevap: 1), soru(soru: "2) Program içerisinde açıklama yapmak için hangi karakterler kullanılır?", cevaplar: ["A) /* */","B) {}","C) ()","D) [] "], cevap: 0), soru(soru: "3) Program içerisinde 1 satırlık açıklama için satır başına konulması gereken karakterler aşağıdakilerden hangisidir?", cevaplar: ["A) ;","B) //","D) '","d) ''"], cevap: 1), soru(soru: "4)m++; kod satırının işlevi hangi satırda doğru verilmiştir?", cevaplar: ["A) m değişkeninin değerini 1 artırır","B) m değişkeninin değerini 2 artırır","C) m değişkeninin değerini 1 azaltır","D) Hata oluşur"], cevap: 0), soru(soru: "5)Mod alma işlemi için kullanılan operatör aşağıdakilerden hangisidir?", cevaplar: ["A) +","B) #","C) %","D) *"], cevap: 2), soru(soru: "6)Aşağıdakilerden hangisi döngü komutudur?", cevaplar: ["A) Convert","B) if","C) Else if","D) for"], cevap: 3), soru(soru: "7) A=B; komut satırının anlamı nedir?", cevaplar: ["A) A değişkeninin değerini B değişkenine aktarır.","B) B değişkeninin değerini A değişkenine aktarır.","C) A değişkeninin değeri B değişkeninin değerine eşit ise ekrana yazar","D) Hata verir."], cevap: 1), soru(soru: "8) Karşılaştırma işlemlerinde kullanılan “eşit değildir” operatörü aşağıdakilerden hangisidir?", cevaplar: ["A) = ","B) <>","C) = = ","D) !="], cevap: 3), soru(soru: "9) Label1.text = “” komut satırının anlamı aşağıdakilerden hangisidir?", cevaplar: ["A) Label1 nesnesinde “ karakteri görüntüler","B) Label1 nesnesindeki mevcut yazıyı siler","C) Label1 nesnesinin adını siler","D) Label1 nesnesinin adını “” yapar"], cevap: 1), soru(soru: "10) int a; komut satırı ne anlama gelir?", cevaplar: ["A) a değişkenine 100 sayısını atar","B) a değişkenini integer tipinde tanımlar"," C) a değişkenini hafızadan siler","D) Hata verir"], cevap: 1)] } func androidBolum(){ sorular = [ soru(soru: "Android de bulunmayan layout hangisidir?", cevaplar: ["A) FrameLayout","B) LinearLayout","C) ReativeLayout","D) IntentLayout "], cevap: 3), soru(soru: "Aşağıdakilerin hangisi Android uygulamaların paketlenmiş halidir? ", cevaplar: ["A) APK","B) SDK","C) ART","D)AVD"], cevap: 0), soru(soru: "Android uygulamaları geliştirmek için kullanılan programlama dili hangisidir?", cevaplar: ["A) PHP","B) Java","C) HTML","D)Javascript"], cevap: 1), soru(soru: "Android işletim sistemi mimarisindeki en üst katman hangisidir ?", cevaplar: ["A) Applications Layer","B) Application Framework Layer","C) Libraries Layer","D)Runtime Layer"], cevap: 0), soru(soru: "Aşağıdakilerden hangisi Textview genişliğini içerdiği metin değerine göre düzenler ?", cevaplar: ["A) 60dp","B) 60sp","C) wrap_content","D)fill_parent"], cevap: 0), soru(soru: "Aşağıdalerden hangisi bir ekranın tasarımını layout dosyası ile oluşturur ? ", cevaplar: ["A) setAdater","B) onClick","C) onCreate","D)setContent View"], cevap: 3), soru(soru: "Bir android uygulamasında activity döngülerinden ilk hangi method devreye girer ?", cevaplar: ["A) onStart","B) onResume","C) onRestart","D)onCreate "], cevap: 3), soru(soru: "Aşağıdakilerden hangisi layout dosyalarında kullanılması tavsiye edilmeyen bir ebat belirtme yöntemidir ? ", cevaplar: ["A) android:layout_height:60d","B) android:layout_width:fill_parent","C) android:layout_height:60px","D)android:layout_width:match_parent"], cevap: 2), soru(soru: "Aşağıdakilerden hangisi android data saklama alanı değildir ?", cevaplar: ["A) Internal Storage","B) external storage","C) SQLite","D)Dalvik VM "], cevap: 3), soru(soru: "Android de görselliğin oluşturulduğu dosya tipi hangisidir ?", cevaplar: ["A) AndroidManifest dosyası","B) java dosyaları","C) XML dosyası","D).Gradle dosyası "], cevap: 2)] } func javaBolum(){ sorular = [ soru(soru: "Aşağıdakilerden hangisi short veri türünün değer aralığıdır ?", cevaplar: ["A) -2^7...2^7-1","B) 0...2^8-1","C) -2^15...2^15-1","D) 0...2^16-1"], cevap: 2), soru(soru: "float x = (float) 2.0; ifadesindeki float ile yapılan işleme ne ad verilir ?", cevaplar: ["A)tür dönüşümü","B)veri dönüşümü","C)sınıf dönüşümü","D)değişken dönüşümü"], cevap: 0), soru(soru: "Aşağıdakilerden hangisi bir java temel değişken türü değildir ?", cevaplar: ["A)int","B)decimal","C)Float","D)Boolean"], cevap: 1), soru(soru: "Aşağıdakilerden hangisi javanın mantıksal operatörlerinden biri değildir ?", cevaplar: ["A) <","B) ! ","C) &&","D)<= "], cevap: 1), soru(soru: "Sınıfların sahip olduğu fonksiyona ne ada verilir?", cevaplar: ["A)void","B)main","C)method","D)class"], cevap: 0), soru(soru: "Javada temel tipler ve bunların boyutlarıyla ilgili olarak aşağıdakilerin hangisinde hata vardır ?", cevaplar: ["A)byte-8bit","B)short-16bit","C)long-64bit","D)float-16bit"], cevap: 3), soru(soru: "asd adlı dosyayı Consolda derleme kodu nedir?", cevaplar: ["A)javac asd","B)asd.java javac","C)javac asd.java","D)java asd.java"], cevap: 2), soru(soru: "java dilinde degisken yerine sabit kullanmak istersek tanımın başına ______ sözcüğünü getiriniz .", cevaplar: ["A) void ","B) static ","C)define ","D)final "], cevap: 3), soru(soru: "Java classpath tanımlaması aşağıdakilerden hangisi için gereklidir ?", cevaplar: ["A) Konsolda java derlemek için ","B) Netbeans IDE sinin çalışması için ","C)Netbeans IDE sinin derlemek için","D)Javanın bilgisayarda çalışması"], cevap: 0), soru(soru: "Java ile ilgili ifadelerden hangisi yanlıştır ?", cevaplar: ["A) JVM byte code interpret eder .","B) javac derleyicisi .java dosyaları .class dosyalarına çevirir","C)Bir java programı içersinden bir .exe programı çalıştırılamaz.","D)Hiçbiri"], cevap: 2)] } /*func phpbolumleri() { sorular = [ soru(soru: ".Her türlü sistem bilgisini hangi değişkende bulabileceğimizi gösteren PHP fonksiyonu aşağıdakilerden hangisidir?", cevaplar: ["A) info()","B) infophp()","C) phpinfo()"," D) phphow()"], cevap: 2), soru(soru: "2.PHP’de sadece doğru ya da yanlış değerini alan veri tipi aşağıdakilerden hangisidir?", cevaplar: ["A) float","B) array ","C) string","D) boolean"], cevap: 3), soru(soru: "3. Aşağıdakilerden hangisi web programlama dili türlerinden biri değildir?", cevaplar: ["A) PHP ","B) HTML"," C) Perl "," D) ASP"], cevap: 1), soru(soru: "4. Aşağıdakilerden hangisi apache web sunucusunun konfigürasyon dosyasıdır?", cevaplar: ["A) httpd.conf "," B)config.php ","C)Php.conf","D)http.php"], cevap: 0), soru(soru: "5. Aşağıdakilerden hangisi bir veri tabanı türüdür?", cevaplar: ["A) MySQL","B) PHP ","C) Apache "," D) phpMyAdmin"], cevap: 0), soru(soru: " 6. Phpmyadmin klasörünü htdocs klasörü altına taşıdığımızda internet tarayıcımızda hangi adresten ulaşabiliriz?", cevaplar: [" A) http://phpmyadmin/ "," B) http://htdocs/phpmyadmin"," C) http://localhost/phpmyadmin","D) http://phpmyadmin/htdocs"], cevap: 2), soru(soru: "7. $a *=$b; komutunun anlamı nedir?", cevaplar: [" A) $a=$a*$b; ","B) $b=$a*$b;"," C) $a=$b*$b;"," D) $b=$a*$a;"], cevap: 0), soru(soru: " 19. PHP’de herhangi bir amaçla açılan dosyaların kapatılması gerekir. Bunun için hangi fonksiyon kullanılır?", cevaplar: [" A) fopen ( ) ","B) fclose ( ) ","C) fgets ( ) "," D) readfile ( )"], cevap: 1), soru(soru: " 20. PHP’de bir dosya silinecekse aşağıdaki komutlardan hangisi kullanılır?", cevaplar: [" A) del ( ) "," B) fclose ( ) "," C) unlink ( ) "," D) kill ( )"], cevap: 2), soru(soru: "21. Formlarda girilecek değerin karakter sayısını sınırlamak için hangi PHP fonksiyonu kullanılır?", cevaplar: [" A) empty ( )","B) strlen ( )","C) isset ( )"," D) eregi ( )"], cevap: 1)] }*/ func iosBolum(){ sorular = [ soru(soru: "IOS uygulamaları geliştirmek için kullanılan programlama dili hangisidir?", cevaplar: ["A) PHP","B) Java","C) Swift","D)Javascript"], cevap: 2), soru(soru: "Swift dilinde bir sabit tanımlamak için hangi keyword kullanılır ?", cevaplar: ["A)double ","B) var","C) int","D) let"], cevap: 3), soru(soru: "Swift dilinde bir değişken tanımlamak için hangi keyword kullanılır ?", cevaplar: ["A) let","B) var","C) int","D)double"], cevap: 1), soru(soru: "Swift programlama dilinde kullanılan kontrol transfer ifadelerinden biri değildir ?", cevaplar: ["A) continue","B) break","C) fallthrough ","D)if"], cevap: 3), soru(soru: "Swift dilinde sıralama yapmak için hangi method kullanırır ", cevaplar: ["A) sort","B) removeAll","C) aand ","D)insert"], cevap: 0), soru(soru: "Swift programlama dilinde kullancıya bilgilendirme veya uyarı verme işlemlerini yerine getiren fonksiyon hangisidir ?", cevaplar: ["A) viewDidload ","B) UIAlertView ","C) didReceiveMemoryWarning ","D)startAnimating"], cevap: 1), soru(soru: "View Controller üzerinde Label komponentini ortalamak için hangi özellik kullanılır ?", cevaplar: ["A) Shadow ","B) Lines ","C) Font ","D) Aligment"], cevap: 3), soru(soru: "IOS da kullanıcıdan bilgi gerektiği durumlarda hangi komponent kullanılır ?", cevaplar: ["A) TextField ","B) TextView ","C) IndıcatorView ","D)UIAlertView"], cevap: 0), soru(soru: "Swift programlama dilinde harita işlemleri için hangi komponent kullanılmaktadır ? ", cevaplar: ["A) IndicatorView","B) TextView ","C) Map Kit View ","D) UIAlertView "], cevap: 2), soru(soru: "TextField komponentine yazılan text'i labelin üzerine yazdırmak için hangi kod parçaçığı kullanılır ?", cevaplar: ["A)textField1.text=label1.text ","B)label1.text = textField1.text ","C) label1.text= açık","D) textField1.text=kaalı "], cevap: 1)] } func htmlBolum(){ sorular = [ soru(soru: "CSS (Cascading Style Sheet) ile aşağıdakilerden hangisi yapılamaz?", cevaplar: ["A)Bir tablonun border’ının rengi kırmızı yapılması","B)Bir yazının fontunun Arial yapılması","C) Bir link alt çizgisinin kaldırılması","D)Bir sayfanın yeniden yüklenmesi"], cevap: 2), soru(soru: "Bir tablo hücresinin genişliğini diğer hücrelerden daha büyük yapmak için td tag’inin hangi özelliği kullanılır?", cevaplar: [" A) cols","B)rows","C)colspan","D)rowspan"], cevap: 2), soru(soru: "test.css dosyalarındaki style’leri kullanmak için hangi tag kullanılmalıdır?", cevaplar: [" A)html","B)style"," C) link","D)body"], cevap: 2), soru(soru: "Resmin üzerine gelindiğinde istenilen mesajın çıkmasını sağlayan HTML tagı hangidir?", cevaplar: ["A) alt ","B) value","C) src ","D) top"], cevap: 0), soru(soru: "Bir sayfadaki tüm linklerin alt çizgisini kaldırmak için aşağıdaki hangi style’li kullanmamız gerekir?", cevaplar: [" A)a{text-line:none}"," B)a{text-line:none}","C)link{text-line:none}","D)a{text-decoration:none}"], cevap: 3), soru(soru: "Bir link tıklandığında bağlanılan sayfanın başka bir frame’de açılması için A tag’inin hangi attribute’si kullanılır?", cevaplar: ["A)link"," B)name ","C)target","D)base"], cevap: 2), soru(soru: "18.Aşağdaki kodlardan hangisiyle yazıyı ortalarız?", cevaplar: ["A) <center> ","B) < left> ","C) <body>","D) <align>"], cevap: 0), soru(soru: "FTP nedir?", cevaplar: ["A) Dosya transfer protokolü","B) İnternet protokolü"," C) Alan adı","D) Web sunucu"], cevap: 0), soru(soru: "Hangisi bir web tarayıcı yazılımıdır?", cevaplar: ["A) Apache"," B) Dreamweaver","C) Fireworks"," D) Firefox"], cevap: 3), soru(soru: "Bir yazının biçimlendirilmesi için kullanılan HTML etiketi aşağıdakilerden hangisidir?", cevaplar: [" A) <font> ","B) <body>"," C) <title>"," D) <table>"], cevap: 0)] } }
51d8b31adf70c8f2eaa7936fe47045b6b94f59a2
[ "Swift" ]
3
Swift
Bitgen6363/bilgiyarismasi-ios
00b6ef09685717ffafbfae027edf87cc3b3fba85
2aa2210813ee7ab5e85d63d62c388f9dc9565ff5
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Estado_Tramite extends Model { protected $table = "estado_tramite"; protected $fillable = ['nombre','color','font_icon']; public function emite_tramite_transferidos(){ return $this->hasMany('App\Tramite_Transferido'); } public function recibe_tramite_transferidos(){ return $this->hasMany('App\Tramite_Transferido'); } } <file_sep><?php use Illuminate\Database\Seeder; class Academico_2017_Seeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('anio_lectivo')->insert([ ['anio' => 2017,'nombre'=>'Año del Buen Servicio al Ciudadano','activo'=>true], ]); DB::table('periodo')->insert([ ['nombre'=>'I BIMESTRE','abreviatura'=>'I B','activo'=>true,'anio_lectivo_id'=> \App\Anio_Lectivo::all()->random()->id], ['nombre'=>'II BIMESTRE','abreviatura'=>'II B','activo'=>true,'anio_lectivo_id'=> \App\Anio_Lectivo::all()->random()->id], ['nombre'=>'III BIMESTRE','abreviatura'=>'III B','activo'=>true,'anio_lectivo_id'=> \App\Anio_Lectivo::all()->random()->id], ]); DB::table('nivel')->insert([ ['nombre'=>'SECUNDARIA','abreviatura'=>'S'] ]); DB::table('tipo_documento')->insert([ ['codigo'=>'01','descripcion'=>'DOCUMENTO NACIONAL DE IDENTIDAD','abreviatura'=>'DNI'], ['codigo'=>'04','descripcion'=>'CARNÉ DE EXTRANJERÍA','abreviatura'=>'CARNÉ EXT.'], ['codigo'=>'06','descripcion'=>'REG. ÚNICO DE CONTRIBUYENTES (1)','abreviatura'=>'RUC'], ['codigo'=>'07','descripcion'=>'PASAPORTE','abreviatura'=>'PASAPORTE'], ['codigo'=>'09','descripcion'=>'CARNÉ DE SOLICIT DE REFUGIO','abreviatura'=>'CARNÉ SOLIC REFUGIO'], ['codigo'=>'11','descripcion' =>'PARTIDA DE NACIMIENTO (2)','abreviatura'=>'PART. NAC.'], ]); DB::table('grado')->insert([ ['nombre'=>'PRIMERO','numero'=>1,'activo'=>true,'grado_anterior_id'=>null,'nivel_id'=>1], ['nombre'=>'SEGUNDO','numero'=>2,'activo'=>true,'grado_anterior_id'=>1,'nivel_id'=>1], ['nombre'=>'TERCERO','numero'=>3,'activo'=>true,'grado_anterior_id'=>2,'nivel_id'=>1], ['nombre'=>'CUARTO','numero'=>4,'activo'=>true,'grado_anterior_id'=>3,'nivel_id'=>1], ['nombre'=>'QUINTO','numero'=>5,'activo'=>true,'grado_anterior_id'=>4,'nivel_id'=>1], ['nombre'=>'SEXTO','numero'=>6,'activo'=>true,'grado_anterior_id'=>5,'nivel_id'=>1], ]); DB::table('turno')->insert([ ['nombre'=>'TARDE','abreviatura'=>'T'], ]); DB::table('seccion')->insert([ ['letra'=>'A','vacantes'=>30,'turno_id'=>1,'activo'=>true,'tipo_calificacion'=>'L','grado_id'=>\App\Grado::all()->random()->id,'anio_lectivo_id'=>\App\Anio_Lectivo::all()->random()->id,'trabajador_id'=>null], ['letra'=>'B','vacantes'=>30,'turno_id'=>1,'activo'=>true,'tipo_calificacion'=>'L','grado_id'=>\App\Grado::all()->random()->id,'anio_lectivo_id'=>\App\Anio_Lectivo::all()->random()->id,'trabajador_id'=>\App\Trabajador::all()->random()->id], ['letra'=>'B','vacantes'=>30,'turno_id'=>1,'activo'=>true,'tipo_calificacion'=>'L','grado_id'=>\App\Grado::all()->random()->id,'anio_lectivo_id'=>\App\Anio_Lectivo::all()->random()->id,'trabajador_id'=>\App\Trabajador::all()->random()->id] ]); DB::table('users')->insert([ ['name'=>'<NAME>','email'=>'admin','password'=>bcrypt('123')], ]); DB::table('user_info')->insert([ ['user_id'=> 1,'clave'=><PASSWORD>('123'),'tipo'=>'AD','activo'=>true], ]); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Testimonio extends Model { protected $table = "testimonio"; protected $fillable = ['nombres','url_Foto','empresa','ocupacion','publico']; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Persona_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //return view('intranet/mantenimientos/persona'); } /** * 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) { $persona = new \App\Persona(); $persona->nombres = $request->input('nombres'); $persona->apellido_paterno = $request->input('apellido_paterno'); $persona->apellido_materno = $request->input('apellido_materno'); $persona->numero_documento= $request->input('numero_documento'); $persona->tipo_documento= $request->input('tipo_documento'); $persona->fecha_nacimiento= $request->input('fecha_nacimiento'); $persona->sexo= $request->input('sexo'); $persona->direccion= $request->input('direccion'); $persona->email= $request->input('email'); $persona->telf_movil= $request->input('telf_movil'); $persona->telf_fijo= $request->input('telf_fijo'); $persona->save(); return $persona; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { $persona = \App\Persona::find($id); $persona->usuario; return $persona; }else if($id == "*"){ return \App\Persona::all(); } } public function buscar_numero_documento() { $numero_documento = Input::get('numero_documento'); if (is_numeric($numero_documento)) { $persona = \App\Persona::where('numero_documento',$numero_documento)->get(); return $persona; } } public function listar_no_alumnos() { return \App\Persona::where('alumno',false)->get(); } public function listar_no_trabajadores() { return \App\Persona::where('trabajador',false)->get(); } /** * 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) { $persona = \App\Persona::find($id); $persona->nombres = $request->input('nombres'); $persona->apellido_paterno = $request->input('apellido_paterno'); $persona->apellido_materno = $request->input('apellido_materno'); $persona->numero_documento= $request->input('numero_documento'); $persona->tipo_documento= $request->input('tipo_documento'); $persona->fecha_nacimiento= $request->input('fecha_nacimiento'); $persona->sexo= $request->input('sexo'); $persona->direccion= $request->input('direccion'); $persona->email= $request->input('email'); $persona->telf_movil= $request->input('telf_movil'); $persona->telf_fijo= $request->input('telf_fijo'); $persona->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $persona = \App\Persona::find($id); $persona->delete(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Tramite_Transferido extends Model { protected $table = "tramite_transferido"; protected $fillable = ['tramite_id','emite_trabajador_id','emite_puesto_trabajo_id','emite_observacion','emite_estado_tramite_id','recibe_trabajador_id','recibe_puesto_trabajo_id','recibe_observacion','recibe_estado_tramite_id','vigencia']; public function tramite(){ return $this->belongsTo('App\Tramite'); } public function emite_trabajador(){ return $this->belongsTo('App\Trabajador'); } public function emite_puesto_trabajo(){ return $this->belongsTo('App\Puesto_Trabajo'); } public function emite_estado_tramite(){ return $this->belongsTo('App\Estado_Tramite'); } public function recibe_trabajador(){ return $this->belongsTo('App\Trabajador'); } public function recibe_puesto_trabajo(){ return $this->belongsTo('App\Puesto_Trabajo'); } public function recibe_estado_tramite(){ return $this->belongsTo('App\Estado_Tramite'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Seccion extends Model { protected $table = "seccion"; protected $fillable = ['letra','vacantes','activo','tipo_calificacion','anio_lectivo_id','turno_id','grado_id','trabajador_id']; public function anio_lectivo(){ return $this->belongsTo('App\Anio_Lectivo'); } public function turno(){ return $this->belongsTo('App\Turno'); } public function grado(){ return $this->belongsTo('App\Grado'); } public function trabajador(){ return $this->belongsTo('App\Trabajador'); } public function ficha_matriculas(){ return $this->hasMany('App\Ficha_Matricula'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Apoderado_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/apoderado'); } /** * 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) { $apoderado = new \App\Apoderado(); $apoderado->nombres = $request->input('nombres'); $apoderado->apellido_paterno = $request->input('apellido_paterno'); $apoderado->apellido_materno = $request->input('apellido_materno'); $apoderado->numero_documento= $request->input('numero_documento'); $apoderado->tipo_documento= $request->input('tipo_documento'); $apoderado->fecha_nacimiento= $request->input('fecha_nacimiento'); $apoderado->sexo= $request->input('sexo'); $apoderado->direccion= $request->input('direccion'); $apoderado->email= $request->input('email'); $apoderado->telf_movil= $request->input('telf_movil'); $apoderado->telf_fijo= $request->input('telf_fijo'); $apoderado->apoderado = $request->input('apoderado'); $apoderado->vive_educando = $request->input('vive_educando'); $apoderado->estado_civil= $request->input('estado_civil'); $apoderado->ocupacion= $request->input('ocupacion'); $apoderado->lugar_trabajo= $request->input('lugar_trabajo'); $apoderado->activo= $request->input('activo'); $apoderado->alumno_id= $request->input('alumno_id'); $apoderado->nivel_educativo_id= $request->input('nivel_educativo_id'); $apoderado->parentesco_id= $request->input('parentesco_id'); $apoderado->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { $apoderado = \App\Apoderado::find($id); $apoderado->parentesco; $apoderado->alumno; $apoderado->nivel_educativo; return $apoderado; } } public function listar() { $alumno_id = Input::get('alumno_id'); $apoderados = \App\Apoderado::where('alumno_id',$alumno_id)->get(); foreach ($apoderados as $apoderado){ $apoderado->nivel_educativo; $apoderado->parentesco; $apoderado->alumno; } return $apoderados; } /** * 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) { $apoderado = \App\Apoderado::find($id); $apoderado->nombres = $request->input('nombres'); $apoderado->apellido_paterno = $request->input('apellido_paterno'); $apoderado->apellido_materno = $request->input('apellido_materno'); $apoderado->numero_documento= $request->input('numero_documento'); $apoderado->tipo_documento= $request->input('tipo_documento'); $apoderado->fecha_nacimiento= $request->input('fecha_nacimiento'); $apoderado->sexo= $request->input('sexo'); $apoderado->direccion= $request->input('direccion'); $apoderado->email= $request->input('email'); $apoderado->telf_movil= $request->input('telf_movil'); $apoderado->telf_fijo= $request->input('telf_fijo'); $apoderado->apoderado = $request->input('apoderado'); $apoderado->vive_educando = $request->input('vive_educando'); $apoderado->estado_civil= $request->input('estado_civil'); $apoderado->ocupacion= $request->input('ocupacion'); $apoderado->lugar_trabajo= $request->input('lugar_trabajo'); $apoderado->activo= $request->input('activo'); $apoderado->alumno_id= $request->input('alumno_id'); $apoderado->nivel_educativo_id= $request->input('nivel_educativo_id'); $apoderado->parentesco_id= $request->input('parentesco_id'); $apoderado->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $apoderado = \App\Apoderado::find($id); $apoderado->delete(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Testimonio_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/testimonio'); } /** * 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) { $testimonio = new \App\Testimonio(); $testimonio->nombres = $request->input('nombres'); $testimonio->url_foto= $request->input('url_foto'); $testimonio->descripcion = $request->input('descripcion'); $testimonio->ocupacion = $request->input('ocupacion'); $testimonio->empresa= $request->input('empresa'); $testimonio->publico= $request->input('publico'); $testimonio->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Testimonio::find($id); } else if($id == "*"){ return \App\Testimonio::all(); } } /** * 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) { $testimonio = \App\Testimonio::find($id); $testimonio->nombres = $request->input('nombres'); $testimonio->url_foto= $request->input('url_foto'); $testimonio->descripcion = $request->input('descripcion'); $testimonio->ocupacion = $request->input('ocupacion'); $testimonio->empresa= $request->input('empresa'); $testimonio->publico= $request->input('publico'); $testimonio->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $testimonio = \App\Testimonio::find($id); $testimonio->delete(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Familia extends Model { protected $table = "familia"; protected $fillable = ['padres_conviven']; public function miembro_familias(){ return $this->hasMany('App\Miembro_Familia'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class Control_Reunion_Controller extends Controller { public function index() { return view('intranet/procesos/control_reunion'); } public function create() { // } public function store(Request $request) { $control_reunion = new \App\Control_Reunion(); $control_reunion->ref_alumno = $request->input('ref_alumno'); $control_reunion->ref_seccion = $request->input('ref_seccion'); $control_reunion->sexo = $request->input('sexo'); $control_reunion->nombre_completo = $request->input('nombre_completo'); $control_reunion->numero_documento = $request->input('numero_documento'); $control_reunion->save(); } public function show($id) { if (is_numeric($id)) { return \App\Control_Reunion::find($id); } else if($id == "*"){ return \App\Control_Reunion::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $control_reunion = \App\Control_Reunion::find($id); $control_reunion->marcacion = DB::raw('now()'); $control_reunion->save(); } public function destroy($id) { $control_reunion = \App\Control_Reunion::find($id); $control_reunion->delete(); } public function listar() { $control_reunions = \App\Control_Reunion::all(); return $control_reunions; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Slider_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/slider'); } /** * 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) { $slider = new \App\Slider(); $slider->orden= $request->input('orden'); $slider->nombre = $request->input('nombre'); $slider->url_foto = $request->input('url_foto'); $slider->url_vinculo = $request->input('url_vinculo'); $slider->nombre_vinculo = $request->input('nombre_vinculo'); $slider->publico= $request->input('publico'); $slider->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Slider::find($id); } else if($id == "*"){ return \App\Slider::all(); } } /** * 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) { $slider = \App\Slider::find($id); $slider->orden= $request->input('orden'); $slider->nombre = $request->input('nombre'); $slider->url_foto = $request->input('url_foto'); $slider->url_vinculo = $request->input('url_vinculo'); $slider->nombre_vinculo = $request->input('nombre_vinculo'); $slider->publico= $request->input('publico'); $slider->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $slider = \App\Slider::find($id); $slider->delete(); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaFamiliar extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('familiar', function (Blueprint $table) { $table->increments('id'); $table->string('nombre_completo'); $table->enum('tipo_documento',['DN','CE','PA'])->default('DN')->nullable(); $table->string('numero_documento',15)->unique()->nullable(); $table->enum('sexo',['M','F']); $table->date('fecha_nacimiento')->nullable(); $table->string('direccion')->nullable(); $table->string('email')->nullable(); $table->string('telf_movil')->nullable(); $table->string('telf_fijo')->nullable(); $table->enum('estado_civil',['SO','CA','VI','DI'])->nullable(); $table->string('ocupacion')->nullable(); $table->string('lugar_trabajo')->nullable(); $table->boolean('activo')->default(true); $table->integer('nivel_educativo_id')->unsigned()->nullable(); $table->foreign('nivel_educativo_id')->references('id')->on('nivel_educativo'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('familiar'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaTramiteTransferido extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tramite_transferido', function (Blueprint $table) { $table->increments('id'); $table->integer('tramite_id')->unsigned(); $table->foreign('tramite_id')->references('id')->on('tramite'); //Trabajador : EMITE Y RECIBE $table->integer('emite_trabajador_id')->unsigned()->nullable(); $table->foreign('emite_trabajador_id')->references('id')->on('trabajador'); $table->integer('emite_puesto_trabajo_id')->unsigned()->nullable(); $table->foreign('emite_puesto_trabajo_id')->references('id')->on('puesto_trabajo'); $table->dateTime('emite_fecha')->nullable(); $table->string('emite_observacion')->nullable(); $table->integer('emite_estado_tramite_id')->unsigned()->nullable(); $table->foreign('emite_estado_tramite_id')->references('id')->on('estado_tramite'); $table->integer('recibe_trabajador_id')->unsigned()->nullable(); $table->foreign('recibe_trabajador_id')->references('id')->on('trabajador'); $table->integer('recibe_puesto_trabajo_id')->unsigned()->nullable(); $table->foreign('recibe_puesto_trabajo_id')->references('id')->on('puesto_trabajo'); $table->dateTime('recibe_fecha')->nullable(); $table->string('recibe_observacion')->nullable(); $table->integer('recibe_estado_tramite_id')->unsigned()->nullable(); $table->foreign('recibe_estado_tramite_id')->references('id')->on('estado_tramite'); $table->boolean('vigencia'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tramite_transferido'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Familiar extends Model { protected $table = "familiar"; protected $fillable = ['nombre_completo','tipo_documento','numero_documento','sexo','fecha_nacimiento','direccion','email','telf_movil','telf_fijo','estado_civil','ocupacion','lugar_trabajo','activo','nivel_educativo_id']; public function nivel_educativo(){ return $this->belongsTo('App\Nivel_Educativo'); } public function alumno_familiars(){ return $this->hasMany('App\Alumno_Familiar'); } } <file_sep><?php namespace App\Http\Controllers; use App\Library\SmsGateway; class Sms_Controller extends Controller { public function enviar() { $smsGateway = new SmsGateway('<EMAIL>', 'familia'); $deviceID = '47628'; $number = '968644416'; $message = 'hola'; $smsGateway-> $result = $smsGateway->sendMessageToNumber($number, $message, $deviceID); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaInstitucion extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('institucion', function (Blueprint $table) { $table->increments('id'); $table->string('telefonos'); $table->string('correo'); $table->string('ciudad'); $table->string('direccion'); $table->text('link_mapa')->nullable(); $table->text('bienvenida_texto')->nullable(); $table->text('bienvenida_url')->nullable(); $table->string('porque_nosotros_1')->nullable(); $table->string('porque_nosotros_2')->nullable(); $table->string('porque_nosotros_3')->nullable(); $table->string('porque_nosotros_4')->nullable(); $table->integer('anio_ficha')->default(2017); $table->boolean('mostrar_ficha')->default(true); $table->boolean('mostrar_tramite')->default(true); $table->string('sms_celular')->default('968644416'); $table->string('sms_cabecera')->default('PRUEBA 1'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('institucion'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaTrabajador extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('trabajador', function (Blueprint $table) { $table->increments('id'); $table->string('nombres'); $table->string('apellido_paterno'); $table->string('apellido_materno')->nullable(); $table->string('numero_documento',15)->unique(); $table->enum('tipo_documento',['DN','CE','PA']); $table->date('fecha_nacimiento'); $table->enum('sexo',['M','F']); $table->string('direccion'); $table->string('email')->unique(); $table->string('telf_movil'); $table->string('telf_fijo')->nullable(); $table->boolean('activo'); $table->integer('categoria_trabajador_id')->unsigned(); $table->foreign('categoria_trabajador_id')->references('id')->on('categoria_trabajador'); $table->integer('nivel_educativo_id')->unsigned(); $table->foreign('nivel_educativo_id')->references('id')->on('nivel_educativo'); $table->integer('especialidad_id')->unsigned(); $table->foreign('especialidad_id')->references('id')->on('especialidad'); $table->integer('user_info_id')->unsigned()->nullable()->unique(); $table->foreign('user_info_id')->references('id')->on('user_info'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('trabajador'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Institucion extends Model { protected $table = "institucion"; protected $fillable = ['telefonos','correo','ciudad','direccion','link_mapa','bienvenida_texto','bienvenida_url','porque_nosotros_1','porque_nosotros_2','porque_nosotros_3','porque_nosotros_4','anio_ficha','mostrar_ficha','mostrar_tramite']; } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Alumno_Familiar extends Model { protected $table = "alumno_familiar"; protected $fillable = ['apoderado','vive_educando','familiar_id','parentesco_id','alumno_id']; public function familiar(){ return $this->belongsTo('App\Familiar'); } public function parentesco(){ return $this->belongsTo('App\Parentesco'); } public function alumno(){ return $this->belongsTo('App\Alumno'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Opcion_Footer extends Model { protected $table = "opcion_footer"; protected $fillable = ['nombre','url','footer','publico']; } <file_sep><?php namespace App\Http\Controllers; use Tymon\JWTAuth\Facades\JWTAuth; use Illuminate\Http\Request; //use Tymon\JWTAuth\Exceptions\JWTException; use Illuminate\Support\Facades\Input; use Tymon\JWTAuth\Providers\JWT\NamshiAdapter; class Anio_Lectivo_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/anio_lectivo'); } /** * 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) { $anio_lectivo = new \App\Anio_Lectivo(); $anio_lectivo->anio = $request->input('anio'); $anio_lectivo->activo = $request->input('activo'); $anio_lectivo->nombre = $request->input('nombre'); $anio_lectivo->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Anio_Lectivo::find($id); } else if($id == "*"){ return \App\Anio_Lectivo::all(); } } /** * 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) { $anio_lectivo = \App\Anio_Lectivo::find($id); $anio_lectivo->anio = $request->input('anio'); $anio_lectivo->nombre = $request->input('nombre'); $anio_lectivo->activo = $request->input('activo'); $anio_lectivo->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $anio_lectivo = \App\Anio_Lectivoanio_lectivo::find($id); $anio_lectivo->delete(); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ use Illuminate\Http\Request; Route::get('/intranet/login', function () { return view('intranet/login'); }); Route::post('/intranet/authenticate',[ 'uses' => 'ApiAuthController@authenticate', 'as' => 'intranet.authenticate' ]); Route::post('/intranet/logout',[ 'uses' => 'ApiAuthController@logout', 'as' => 'intranet.logout' ])->middleware('jwt.auth'); Route::get('/intranet/inicio', function (Request $request) { return view('intranet/inicio',['token'=>$request->input('token')]); })->middleware('jwt.auth'); Route::resource('/','\App\Http\Controllers\Website_Controller'); Route::get('/noticias/{id}/ver', ['uses' => 'Noticia_Controller@ver_noticia', 'as' => 'noticia.ver_noticia']); Route::get('/eventos/{id}/ver', ['uses' => 'Evento_Controller@ver_evento', 'as' => 'evento.ver_evento']); Route::get('/paginas/{id}/ver', ['uses' => 'Pagina_Web_Controller@ver_pagina', 'as' => 'pagina_web.ver_pagina']); Route::get('/galeria', ['uses' => 'Album_Controller@ver_galeria', 'as' => 'album.ver_galeria']); Route::get('/videos', ['uses' => 'Video_Controller@ver_videos', 'as' => 'album.ver_videos']); Route::get('/ficha_matricula', ['uses' => 'Ficha_Matricula_Controller@ver_ficha_matricula', 'as' => 'ficha_matricula.ver_ficha_matricula']); Route::get('/mensaje_texto', ['uses' => 'Sms_Controller@enviar', 'as' => 'sms.enviar']); Route::group(['prefix'=>'intranet/mantenimientos','middleware' => 'jwt.auth'], function () { Route::resource('anio_lectivo','\App\Http\Controllers\Anio_Lectivo_Controller'); Route::get('periodo/listar', ['uses' => 'Periodo_Controller@listar', 'as' => 'periodo.listar']); Route::resource('periodo','\App\Http\Controllers\Periodo_Controller'); Route::resource('nivel','\App\Http\Controllers\Nivel_Controller'); Route::get('grado/listar', ['uses' => 'Grado_Controller@listar', 'as' => 'grado.listar']); Route::resource('grado','\App\Http\Controllers\Grado_Controller'); Route::resource('especialidad','\App\Http\Controllers\Especialidad_Controller'); Route::resource('categoria_trabajador','\App\Http\Controllers\Categoria_Trabajador_Controller'); Route::resource('parentesco','\App\Http\Controllers\Parentesco_Controller'); Route::resource('nivel_educativo','\App\Http\Controllers\Nivel_Educativo_Controller'); Route::resource('colegio_procedencia','\App\Http\Controllers\Colegio_Procedencia_Controller'); Route::get('trabajador/listar', ['uses' => 'Trabajador_Controller@listar', 'as' => 'trabajador.listar']); Route::get('trabajador/listar_usuarios', ['uses' => 'Trabajador_Controller@listar_usuarios', 'as' => 'trabajador.listar_usuarios']); Route::get('trabajador/buscar_numero_documento', ['uses' => 'Trabajador_Controller@buscar_numero_documento', 'as' => 'trabajador.buscar_numero_documento']); Route::resource('trabajador','\App\Http\Controllers\Trabajador_Controller'); Route::get('apoderado/listar', ['uses' => 'Apoderado_Controller@listar', 'as' => 'apoderado.listar']); Route::resource('apoderado','\App\Http\Controllers\Apoderado_Controller'); Route::get('alumno/listar', ['uses' => 'Alumno_Controller@listar', 'as' => 'alumno.listar']); Route::get('alumno/buscar_numero_documento', ['uses' => 'Alumno_Controller@buscar_numero_documento', 'as' => 'alumno.buscar_numero_documento']); Route::resource('alumno','\App\Http\Controllers\Alumno_Controller'); Route::resource('turno','\App\Http\Controllers\Turno_Controller'); Route::get('seccion/listar', ['uses' => 'Seccion_Controller@listar', 'as' => 'seccion.listar']); Route::resource('seccion','\App\Http\Controllers\Seccion_Controller'); Route::get('familiar/listar', ['uses' => 'Familiar_Controller@listar', 'as' => 'familiar.listar']); Route::resource('familiar','\App\Http\Controllers\Familiar_Controller'); Route::resource('user_info','\App\Http\Controllers\User_Info_Controller'); Route::get('ficha_matricula/listar', ['uses' => 'Ficha_Matricula_Controller@listar', 'as' => 'ficha_matricula.listar']); Route::get('ficha_matricula/buscar', ['uses' => 'Ficha_Matricula_Controller@buscar', 'as' => 'ficha_matricula.buscar']); Route::get('ficha_matricula/imprimir', ['uses' => 'Ficha_Matricula_Controller@imprimir', 'as' => 'ficha_matricula.imprimir']); Route::get('ficha_matricula/habilitar_edicion', ['uses' => 'Ficha_Matricula_Controller@habilitar_edicion', 'as' => 'ficha_matricula.habilitar_edicion']); Route::resource('ficha_matricula','\App\Http\Controllers\Ficha_Matricula_Controller'); Route::resource('tipo_documento','\App\Http\Controllers\Tipo_Documento_Controller'); Route::get('puesto_trabajo/listar', ['uses' => 'Puesto_Trabajo_Controller@listar', 'as' => 'puesto_trabajo.listar']); Route::resource('puesto_trabajo','\App\Http\Controllers\Puesto_Trabajo_Controller'); Route::resource('estado_tramite','\App\Http\Controllers\Estado_Tramite_Controller'); }); Route::group(['prefix'=>'intranet/procesos'], function () { Route::get('control_reunion/listar', ['uses' => 'Control_Reunion_Controller@listar', 'as' => 'control_reunion.listar']); Route::resource('control_reunion','\App\Http\Controllers\Control_Reunion_Controller'); }); Route::group(['prefix'=>'intranet/website'], function () { Route::resource('enlace_rapido','\App\Http\Controllers\Enlace_Rapido_Controller'); Route::resource('noticia','\App\Http\Controllers\Noticia_Controller'); Route::resource('evento','\App\Http\Controllers\Evento_Controller'); Route::resource('video','\App\Http\Controllers\Video_Controller'); Route::resource('comunicado','\App\Http\Controllers\Comunicado_Controller'); Route::resource('slider','\App\Http\Controllers\Slider_Controller'); Route::get('opcion_menu/listar', ['uses' => 'Opcion_Menu_Controller@listar', 'as' => 'opcion_menu.listar']); Route::resource('opcion_menu','\App\Http\Controllers\Opcion_Menu_Controller'); Route::resource('pagina_web','\App\Http\Controllers\Pagina_Web_Controller'); Route::get('foto/listar', ['uses' => 'Foto_Controller@listar', 'as' => 'foto.listar']); Route::resource('foto','\App\Http\Controllers\Foto_Controller'); Route::resource('album','\App\Http\Controllers\Album_Controller'); Route::resource('testimonio','\App\Http\Controllers\Testimonio_Controller'); Route::resource('opcion_footer','\App\Http\Controllers\Opcion_Footer_Controller'); Route::resource('institucion','\App\Http\Controllers\Institucion_Controller'); Route::resource('emergente','\App\Http\Controllers\Emergente_Controller'); //Route::get('periodo/listar', ['uses' => 'Periodo_Controller@listar', 'as' => 'periodo.listar']); }); //Route::resource('file', 'FileController'); <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Album extends Model { protected $table = "album"; protected $fillable = ['nombre','fecha','publico']; public function fotos(){ return $this->hasMany('App\Foto'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Nivel_Educativo extends Model { protected $table = "nivel_educativo"; protected $fillable = ['codigo','nombre','abreviatura']; public function trabajadors(){ return $this->hasMany('App\Trabajador'); } public function apoderados(){ return $this->hasMany('App\Apoderado'); } } <file_sep><?php use Illuminate\Database\Seeder; class Especialidad_Seeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('especialidad')->insert([ ['nombre' => "MATEMÁTICA",'abreviatura' => "MAT"], ['nombre' => "HISTORIA",'abreviatura' => "HIST"], ['nombre' => "LENGUA Y LITERATURA",'abreviatura' => "LENG"] ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Tipo_Documento_Controller extends Controller { public function index() { return view('intranet/mantenimientos/tipo_documento'); } public function create() { // } public function store(Request $request) { $tipo_documento = new \App\Tipo_Documento(); $tipo_documento->codigo = $request->input('codigo'); $tipo_documento->descripcion = $request->input('descripcion'); $tipo_documento->abreviatura = $request->input('abreviatura'); $tipo_documento->activo = $request->input('activo'); $tipo_documento->save(); } public function show($id) { if (is_numeric($id)) { return \App\Tipo_Documento::find($id); } else if($id == "*"){ return \App\Tipo_Documento::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $tipo_documento = \App\Tipo_Documento::find($id); $tipo_documento->codigo = $request->input('codigo'); $tipo_documento->descripcion = $request->input('descripcion'); $tipo_documento->abreviatura = $request->input('abreviatura'); $tipo_documento->activo = $request->input('activo'); $tipo_documento->save(); } public function destroy($id) { $tipo_documento = \App\Tipo_Documento::find($id); $tipo_documento->delete(); } public function listar() { $tipo_documentos = \App\Tipo_Documento::all(); foreach ($tipo_documentos as $tipo_documento){ } return $tipo_documentos; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Colegio_Procedencia extends Model { protected $table = "colegio_procedencia"; protected $fillable = ['nombre']; public function alumnos(){ return $this->hasMany('App\Alumno'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Anio_Lectivo extends Model { protected $table = "anio_lectivo"; protected $fillable = ['anio','activo']; public function periodos(){ return $this->hasMany('App\Periodo'); } public function seccions(){ return $this->hasMany('App\Seccion'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Ficha_Matricula_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/ficha_matricula'); } public function ver_ficha_matricula() { $opciones = \App\Opcion_Menu::where('publico',true)->orderBy('orden','asc')->get(); $opciones_footer = \App\Opcion_Footer::where('publico',true)->orderBy('id', 'desc')->get(); $institucion = \App\Institucion::take(1)->get()[0]; return view('website/ficha_matricula',['opciones_footer'=>$opciones_footer,'institucion'=>$institucion,'opciones'=>$opciones]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } public function store(Request $request) { $ficha_matricula = new \App\Ficha_Matricula(); $ficha_matricula->pem = $request->input('pem'); $ficha_matricula->tipo_matricula = $request->input('tipo_matricula'); $ficha_matricula->seccion_id = $request->input('seccion_id'); $ficha_matricula->alumno_nombres = $request->input('alumno_nombres'); $ficha_matricula->alumno_apellido_paterno = $request->input('alumno_apellido_paterno'); $ficha_matricula->alumno_apellido_materno = $request->input('alumno_apellido_materno'); $ficha_matricula->alumno_numero_documento = $request->input('alumno_numero_documento'); $ficha_matricula->alumno_tipo_documento_id = $request->input('alumno_tipo_documento_id'); /* $ficha_matricula->alumno_fecha_nacimiento = $request->input('alumno_fecha_nacimiento'); $ficha_matricula->alumno_sexo = $request->input('alumno_sexo'); $ficha_matricula->alumno_direccion = $request->input('alumno_direccion'); $ficha_matricula->alumno_telf_fijo = $request->input('alumno_telf_fijo'); $ficha_matricula->alumno_padres_juntos = $request->input('alumno_padres_juntos'); $ficha_matricula->alumno_colegio_procedencia_id = $request->input('alumno_colegio_procedencia_id'); $ficha_matricula->padre_nombres = $request->input('padre_nombres'); $ficha_matricula->padre_numero_documento = $request->input('padre_numero_documento'); $ficha_matricula->padre_tipo_documento = $request->input('padre_tipo_documento'); $ficha_matricula->padre_fecha_nacimiento = $request->input('padre_fecha_nacimiento'); $ficha_matricula->padre_sexo = $request->input('padre_sexo'); $ficha_matricula->padre_direccion = $request->input('padre_direccion'); $ficha_matricula->padre_email = $request->input('padre_email'); $ficha_matricula->padre_telf_movil = $request->input('padre_telf_movil'); $ficha_matricula->padre_telf_fijo = $request->input('padre_telf_fijo'); $ficha_matricula->padre_apoderado = $request->input('padre_apoderado'); $ficha_matricula->padre_vive_educando = $request->input('padre_vive_educando'); $ficha_matricula->padre_estado_civil = $request->input('padre_estado_civil'); $ficha_matricula->padre_ocupacion = $request->input('padre_ocupacion'); $ficha_matricula->padre_lugar_trabajo = $request->input('padre_lugar_trabajo'); $ficha_matricula->padre_parentesco_id = $request->input('padre_parentesco_id'); $ficha_matricula->padre_nivel_educativo_id = $request->input('padre_nivel_educativo_id'); $ficha_matricula->madre_nombres = $request->input('madre_nombres'); $ficha_matricula->madre_numero_documento = $request->input('madre_numero_documento'); $ficha_matricula->madre_tipo_documento = $request->input('madre_tipo_documento'); $ficha_matricula->madre_fecha_nacimiento = $request->input('madre_fecha_nacimiento'); $ficha_matricula->madre_sexo = $request->input('madre_sexo'); $ficha_matricula->madre_direccion = $request->input('madre_direccion'); $ficha_matricula->madre_email = $request->input('madre_email'); $ficha_matricula->madre_telf_movil = $request->input('madre_telf_movil'); $ficha_matricula->madre_telf_fijo = $request->input('madre_telf_fijo'); $ficha_matricula->madre_apoderado = $request->input('madre_apoderado'); $ficha_matricula->madre_vive_educando = $request->input('madre_vive_educando'); $ficha_matricula->madre_estado_civil = $request->input('madre_estado_civil'); $ficha_matricula->madre_ocupacion = $request->input('madre_ocupacion'); $ficha_matricula->madre_lugar_trabajo = $request->input('madre_lugar_trabajo'); $ficha_matricula->madre_parentesco_id = $request->input('madre_parentesco_id'); $ficha_matricula->madre_nivel_educativo_id = $request->input('madre_nivel_educativo_id'); $ficha_matricula->apoderado_nombres = $request->input('apoderado_nombres'); $ficha_matricula->apoderado_apellido_paterno = $request->input('apoderado_apellido_paterno'); $ficha_matricula->apoderado_apellido_materno = $request->input('apoderado_apellido_materno'); $ficha_matricula->apoderado_numero_documento = $request->input('apoderado_numero_documento'); $ficha_matricula->apoderado_tipo_documento = $request->input('apoderado_tipo_documento'); $ficha_matricula->apoderado_fecha_nacimiento = $request->input('apoderado_fecha_nacimiento'); $ficha_matricula->apoderado_sexo = $request->input('apoderado_sexo'); $ficha_matricula->apoderado_direccion = $request->input('apoderado_direccion'); $ficha_matricula->apoderado_email = $request->input('apoderado_email'); $ficha_matricula->apoderado_telf_movil = $request->input('apoderado_telf_movil'); $ficha_matricula->apoderado_telf_fijo = $request->input('apoderado_telf_fijo'); $ficha_matricula->apoderado_apoderado = $request->input('apoderado_apoderado'); $ficha_matricula->apoderado_vive_educando = $request->input('apoderado_vive_educando'); $ficha_matricula->apoderado_estado_civil = $request->input('apoderado_estado_civil'); $ficha_matricula->apoderado_ocupacion = $request->input('apoderado_ocupacion'); $ficha_matricula->apoderado_lugar_trabajo = $request->input('apoderado_lugar_trabajo'); $ficha_matricula->apoderado_parentesco_id = $request->input('apoderado_parentesco_id'); $ficha_matricula->apoderado_nivel_educativo_id = $request->input('apoderado_nivel_educativo_id'); */ $ficha_matricula->save(); } public function show($id) { if (is_numeric($id)) { return \App\Ficha_Matricula::find($id); } else if($id == "*"){ return \App\Ficha_Matricula::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $ficha_matricula = \App\Ficha_Matricula::find($id); if($ficha_matricula->pem == $request->input('pem') && $ficha_matricula->alumno_numero_documento == $request->input('alumno_numero_documento')){ $ficha_matricula->alumno_nombres = $request->input('alumno_nombres'); $ficha_matricula->alumno_apellido_paterno = $request->input('alumno_apellido_paterno'); $ficha_matricula->alumno_apellido_materno = $request->input('alumno_apellido_materno'); //$ficha_matricula->alumno_numero_documento = $request->input('alumno_numero_documento'); $ficha_matricula->alumno_tipo_documento_id = $request->input('alumno_tipo_documento_id'); $ficha_matricula->alumno_fecha_nacimiento = $request->input('alumno_fecha_nacimiento'); $ficha_matricula->alumno_sexo = $request->input('alumno_sexo'); $ficha_matricula->alumno_direccion = $request->input('alumno_direccion'); $ficha_matricula->alumno_telf_fijo = $request->input('alumno_telf_fijo'); $ficha_matricula->alumno_padres_juntos = $request->input('alumno_padres_juntos'); $ficha_matricula->alumno_colegio_procedencia = $request->input('alumno_colegio_procedencia'); $ficha_matricula->alumno_apoderado = $request->input('alumno_apoderado'); $ficha_matricula->padre_apellido_paterno = $request->input('padre_apellido_paterno'); $ficha_matricula->padre_apellido_materno = $request->input('padre_apellido_materno'); $ficha_matricula->padre_nombres = $request->input('padre_nombres'); $ficha_matricula->padre_numero_documento = $request->input('padre_numero_documento'); $ficha_matricula->padre_tipo_documento_id = $request->input('padre_tipo_documento_id'); $ficha_matricula->padre_fecha_nacimiento = $request->input('padre_fecha_nacimiento'); $ficha_matricula->padre_sexo = $request->input('padre_sexo'); $ficha_matricula->padre_direccion = $request->input('padre_direccion'); $ficha_matricula->padre_email = $request->input('padre_email'); $ficha_matricula->padre_telf_movil = $request->input('padre_telf_movil'); $ficha_matricula->padre_vive_educando = $request->input('padre_vive_educando'); $ficha_matricula->padre_estado_civil = $request->input('padre_estado_civil'); $ficha_matricula->padre_ocupacion = $request->input('padre_ocupacion'); $ficha_matricula->padre_cargo = $request->input('padre_cargo'); $ficha_matricula->padre_lugar_trabajo = $request->input('padre_lugar_trabajo'); $ficha_matricula->padre_nivel_educativo_id = $request->input('padre_nivel_educativo_id'); $ficha_matricula->madre_apellido_paterno = $request->input('madre_apellido_paterno'); $ficha_matricula->madre_apellido_materno = $request->input('madre_apellido_materno'); $ficha_matricula->madre_nombres = $request->input('madre_nombres'); $ficha_matricula->madre_numero_documento = $request->input('madre_numero_documento'); $ficha_matricula->madre_tipo_documento_id = $request->input('madre_tipo_documento_id'); $ficha_matricula->madre_fecha_nacimiento = $request->input('madre_fecha_nacimiento'); $ficha_matricula->madre_sexo = $request->input('madre_sexo'); $ficha_matricula->madre_direccion = $request->input('madre_direccion'); $ficha_matricula->madre_email = $request->input('madre_email'); $ficha_matricula->madre_telf_movil = $request->input('madre_telf_movil'); $ficha_matricula->madre_vive_educando = $request->input('madre_vive_educando'); $ficha_matricula->madre_estado_civil = $request->input('madre_estado_civil'); $ficha_matricula->madre_ocupacion = $request->input('madre_ocupacion'); $ficha_matricula->madre_cargo = $request->input('madre_cargo'); $ficha_matricula->madre_lugar_trabajo = $request->input('madre_lugar_trabajo'); $ficha_matricula->madre_nivel_educativo_id = $request->input('madre_nivel_educativo_id'); $ficha_matricula->apoderado_nombres = $request->input('apoderado_nombres'); $ficha_matricula->apoderado_apellido_paterno = $request->input('apoderado_apellido_paterno'); $ficha_matricula->apoderado_apellido_materno = $request->input('apoderado_apellido_materno'); $ficha_matricula->apoderado_numero_documento = $request->input('apoderado_numero_documento'); $ficha_matricula->apoderado_tipo_documento_id = $request->input('apoderado_tipo_documento_id'); $ficha_matricula->apoderado_fecha_nacimiento = $request->input('apoderado_fecha_nacimiento'); $ficha_matricula->apoderado_sexo = $request->input('apoderado_sexo'); $ficha_matricula->apoderado_direccion = $request->input('apoderado_direccion'); $ficha_matricula->apoderado_email = $request->input('apoderado_email'); $ficha_matricula->apoderado_telf_movil = $request->input('apoderado_telf_movil'); $ficha_matricula->apoderado_vive_educando = $request->input('apoderado_vive_educando'); $ficha_matricula->apoderado_estado_civil = $request->input('apoderado_estado_civil'); $ficha_matricula->apoderado_ocupacion = $request->input('apoderado_ocupacion'); $ficha_matricula->apoderado_cargo = $request->input('apoderado_cargo'); $ficha_matricula->apoderado_lugar_trabajo = $request->input('apoderado_lugar_trabajo'); $ficha_matricula->apoderado_parentesco_id = $request->input('apoderado_parentesco_id'); $ficha_matricula->apoderado_nivel_educativo_id = $request->input('apoderado_nivel_educativo_id'); $ficha_matricula->save(); } } public function imprimir(){ $ficha_matricula = \App\Ficha_Matricula::find(Input::get('id')); if($ficha_matricula->pem == Input::get('pem') && $ficha_matricula->alumno_numero_documento == Input::get('alumno_numero_documento')){ $ficha_matricula->imprimir=true; $ficha_matricula->save(); } } public function habilitar_edicion(){ $ficha_matricula = \App\Ficha_Matricula::find(Input::get('id')); if($ficha_matricula->pem == Input::get('pem') && $ficha_matricula->alumno_numero_documento == Input::get('alumno_numero_documento')){ $ficha_matricula->imprimir=false; $ficha_matricula->save(); } } public function destroy($id) { $ficha_matricula = \App\Ficha_Matricula::find($id); $ficha_matricula->delete(); } public function listar() { $ficha_matriculas = \App\Ficha_Matricula::where('seccion_id',Input::get('seccion_id'))->orderBy('id','desc')->get(); foreach ($ficha_matriculas as $ficha_matricula){ $ficha_matricula->seccion; } return $ficha_matriculas; } public function buscar() { $ficha_matriculas = \App\Ficha_Matricula::where('pem',Input::get('pem'))->where('alumno_numero_documento',Input::get('alumno_numero_documento'))->get(); foreach ($ficha_matriculas as $ficha_matricula){ $ficha_matricula->alumno_tipo_documento; $ficha_matricula->padre_tipo_documento; $ficha_matricula->madre_tipo_documento; $ficha_matricula->apoderado_tipo_documento; $ficha_matricula->padre_nivel_educativo; $ficha_matricula->madre_nivel_educativo; $ficha_matricula->apoderado_nivel_educativo; $ficha_matricula->apoderado_parentesco; $ficha_matricula->seccion; } return $ficha_matriculas; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Especialidad extends Model { protected $table = "especialidad"; protected $fillable = ['nombre','abreviatura']; public function trabajadors(){ return $this->hasMany('App\Trabajador'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Periodo extends Model { protected $table = "periodo"; protected $fillable = ['nombre','abreviatura','activo','anio_academico_id']; public function anio_lectivo(){ return $this->belongsTo('App\Anio_Lectivo'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Periodo_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/periodo'); } /** * 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) { $periodo = new \App\Periodo(); $periodo->anio_lectivo_id = $request->input('anio_lectivo_id'); $periodo->nombre = $request->input('nombre'); $periodo->abreviatura = $request->input('abreviatura'); $periodo->activo = $request->input('activo'); $periodo->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Periodo::find($id); } else if($id == "*"){ return \App\Periodo::all(); } } public function listar() { return \App\Periodo::where('anio_lectivo_id',Input::get('anio_lectivo_id'))->get(); } /** * 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) { $periodo = \App\Periodo::find($id); $periodo->anio_lectivo_id = $request->input('anio_lectivo_id'); $periodo->nombre = $request->input('nombre'); $periodo->abreviatura = $request->input('abreviatura'); $periodo->activo = $request->input('activo'); $periodo->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $periodo = \App\Periodo::find($id); $periodo->delete(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Turno extends Model { protected $table = "turno"; protected $fillable = ['nombre','abreviatura','activo']; public function seccions(){ return $this->hasMany('App\Seccion'); } } <file_sep><?php use Illuminate\Database\Seeder; class Nivel_Educativo_Seeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('nivel_educativo')->insert([ [ 'codigo' => '01', 'descripcion' => 'SIN EDUCACIÓN FORMAL', 'abreviatura' => 'SIN EDUCACIÓN FORMAL'], [ 'codigo' => '02', 'descripcion' => 'EDUCACIÓN ESPECIAL INCOMPLETA', 'abreviatura' => 'ESPECIAL INCOMPLETA'], [ 'codigo' => '03', 'descripcion' => 'EDUCACIÓN ESPECIAL COMPLETA', 'abreviatura' => 'ESPECIAL COMPLETA'], [ 'codigo' => '04', 'descripcion' => 'EDUCACIÓN PRIMARIA INCOMPLETA', 'abreviatura' => 'PRIMARIA INCOMPLETA'], [ 'codigo' => '05', 'descripcion' => 'EDUCACIÓN PRIMARIA COMPLETA', 'abreviatura' => 'PRIMARIA COMPLETA'], [ 'codigo' => '06', 'descripcion' => 'EDUCACIÓN SECUNDARIA INCOMPLETA', 'abreviatura' => 'SECUNDARIA INCOMPLETA'], [ 'codigo' => '07', 'descripcion' => 'EDUCACIÓN SECUNDARIA COMPLETA', 'abreviatura' => 'SECUNDARIA COMPLETA'], [ 'codigo' => '08', 'descripcion' => 'EDUCACIÓN TÉCNICA INCOMPLETA', 'abreviatura' => 'TÉCNICA INCOMPLETA'], [ 'codigo' => '09', 'descripcion' => 'EDUCACIÓN TÉCNICA COMPLETA', 'abreviatura' => 'TÉCNICA COMPLETA'], [ 'codigo' => '10', 'descripcion' => 'EDUCACIÓN SUPERIOR (INSTITUTO SUPERIOR, ETC) INCOMPLETA ', 'abreviatura' => 'SUPERIOR INCOMPLETA (INSTIT. SUPER)'], [ 'codigo' => '11', 'descripcion' => 'EDUCACIÓN SUPERIOR (INSTITUTO SUPERIOR, ETC) COMPLETA ', 'abreviatura' => 'SUPERIOR COMPLETA (INSTIT SUPER)'], [ 'codigo' => '12', 'descripcion' => 'EDUCACIÓN UNIVERSITARIA INCOMPLETA', 'abreviatura' => 'UNIVERSITARIA INCOMPLETA'], [ 'codigo' => '13', 'descripcion' => 'EDUCACIÓN UNIVERSITARIA COMPLETA', 'abreviatura' => 'UNIVERSITARIA COMPLETA'], [ 'codigo' => '14', 'descripcion' => 'GRADO DE BACHILLER', 'abreviatura' => 'GRADO DE BACHILLER'], [ 'codigo' => '15', 'descripcion' => 'TITULADO', 'abreviatura' => 'TITULADO'], [ 'codigo' => '16', 'descripcion' => 'ESTUDIOS DE MAESTRÍA INCOMPLETA', 'abreviatura' => 'ESTUD. MAESTRÍA INCOMPLETA'], [ 'codigo' => '17', 'descripcion' => 'ESTUDIOS DE MAESTRÍA COMPLETA', 'abreviatura' => 'ESTUD. MAESTRÍA COMPLETA'], [ 'codigo' => '18', 'descripcion' => 'GRADO DE MAESTRÍA', 'abreviatura' => 'GRADO DE MAESTRÍA'], [ 'codigo' => '19', 'descripcion' => 'ESTUDIOS DE DOCTORADO INCOMPLETO', 'abreviatura' => 'ESTUD. DOCTORADO INCOMPLETO'], [ 'codigo' => '20', 'descripcion' => 'ESTUDIOS DE DOCTORADO COMPLETO', 'abreviatura' => 'ESTUD. DOCTORADO COMPLETO'], [ 'codigo' => '21', 'descripcion' => 'GRADO DE DOCTOR', 'abreviatura' => 'GRADO DE DOCTOR'] ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Enlace_Rapido_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/enlace_rapido'); } /** * 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) { $enlace_rapido = new \App\Enlace_Rapido(); $enlace_rapido->orden= $request->input('orden'); $enlace_rapido->nombre = $request->input('nombre'); $enlace_rapido->categoria = $request->input('categoria'); $enlace_rapido->url = $request->input('url'); $enlace_rapido->color= $request->input('color'); $enlace_rapido->publico= $request->input('publico'); $enlace_rapido->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Enlace_Rapido::find($id); } else if($id == "*"){ return \App\Enlace_Rapido::all(); } } /** * 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) { $enlace_rapido = \App\Enlace_Rapido::find($id); $enlace_rapido->orden= $request->input('orden'); $enlace_rapido->nombre = $request->input('nombre'); $enlace_rapido->categoria = $request->input('categoria'); $enlace_rapido->url = $request->input('url'); $enlace_rapido->color= $request->input('color'); $enlace_rapido->publico= $request->input('publico'); $enlace_rapido->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $enlace_rapido = \App\Enlace_Rapido::find($id); $enlace_rapido->delete(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Tramite_Controller extends Controller { public function index() { return view('tramite'); } public function create() { // } public function store(Request $request) { $tramite = new \App\Tramite(); $tramite->folios = $request->input('folios'); $tramite->prioridad = $request->input('prioridad'); $tramite->numero_documento = $request->input('numero_documento'); $tramite->nombre_completo = $request->input('nombre_completo'); $tramite->celular = $request->input('celular'); $tramite->asunto = $request->input('asunto'); $tramite->referencia = $request->input('referencia'); $tramite->tipo_tramite_id = $request->input('tipo_tramite_id'); $tramite->save(); } public function show($id) { if (is_numeric($id)) { return \App\Tramite::find($id); } else if($id == "*"){ return \App\Tramite::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $tramite = \App\Tramite::find($id); $tramite->folios = $request->input('folios'); $tramite->prioridad = $request->input('prioridad'); $tramite->numero_documento = $request->input('numero_documento'); $tramite->nombre_completo = $request->input('nombre_completo'); $tramite->celular = $request->input('celular'); $tramite->asunto = $request->input('asunto'); $tramite->referencia = $request->input('referencia'); $tramite->tipo_tramite_id = $request->input('tipo_tramite_id'); $tramite->save(); } public function destroy($id) { $tramite = \App\Tramite::find($id); $tramite->delete(); } public function listar() { $tramites = \App\Tramite::all(); foreach ($tramites as $tramite){ } return $tramites; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Categoria_Trabajador extends Model { protected $table = "categoria_trabajador"; protected $fillable = ['nombre','abreviatura']; public function trabajadors(){ return $this->hasMany('App\Trabajador'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Tramite extends Model { protected $table = "tramite"; protected $fillable = ['folios','prioridad','numero_documento','nombre_completo','celular','asunto','referencia','tipo_tramite_id']; public function tipo_tramite(){ return $this->belongsTo('App\Tipo_Tramite'); } public function tramite_transferidos(){ return $this->hasMany('App\Tramite_Transferido'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaSeccion extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('seccion', function (Blueprint $table) { $table->increments('id'); $table->string('letra'); $table->integer('vacantes'); $table->enum('tipo_calificacion',['L','V']); $table->integer('anio_lectivo_id')->unsigned(); $table->foreign('anio_lectivo_id')->references('id')->on('anio_lectivo'); $table->integer('turno_id')->unsigned(); $table->foreign('turno_id')->references('id')->on('turno'); $table->integer('grado_id')->unsigned(); $table->foreign('grado_id')->references('id')->on('grado'); $table->integer('trabajador_id')->unsigned()->nullable(); $table->foreign('trabajador_id')->references('id')->on('trabajador'); $table->boolean('activo'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('seccion'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Emergente extends Model { protected $table = "emergente"; protected $fillable = ['tipo','nombre','fecha','contenido','url','url_foto','publico']; } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaAlumno extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('alumno', function (Blueprint $table) { $table->increments('id'); $table->string('nombres'); $table->string('apellido_paterno'); $table->string('apellido_materno')->nullable(); $table->string('numero_documento',15)->unique(); $table->enum('tipo_documento',['DN','CE','PA']); $table->date('fecha_nacimiento'); $table->enum('sexo',['M','F']); $table->string('direccion')->nullable(); $table->string('telf_fijo')->nullable(); $table->string('codigo_educando')->nullable(); $table->string('codigo_recaudacion')->nullable(); $table->string('url_foto')->nullable(); $table->boolean('padres_juntos')->nullable(); $table->boolean('activo')->default(true); $table->integer('colegio_procedencia_id')->unsigned()->nullable(); $table->foreign('colegio_procedencia_id')->references('id')->on('colegio_procedencia'); $table->integer('user_info_id')->unsigned()->nullable()->unique(); $table->foreign('user_info_id')->references('id')->on('user_info'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('alumno'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaFichaMatricula extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ficha_matricula', function (Blueprint $table) { $table->increments('id'); //Datos del alumno $table->string('pem'); $table->enum('tipo_matricula',['N','P','R']); //Nuevo/Promovido/Reingresante $table->enum('alumno_apoderado',['P','M','O'])->nullable(); //Padre/Madre/Otro $table->integer('seccion_id')->unsigned()->nullable(); $table->foreign('seccion_id')->references('id')->on('seccion')->onDelete('cascade'); $table->boolean('activo')->default(true); $table->boolean('imprimir')->default(false); $table->string('alumno_nombres')->nullable(); $table->string('alumno_apellido_paterno')->nullable(); $table->string('alumno_apellido_materno')->nullable(); $table->string('alumno_numero_documento',15); $table->integer('alumno_tipo_documento_id')->unsigned()->nullable(); $table->foreign('alumno_tipo_documento_id')->references('id')->on('tipo_documento'); $table->date('alumno_fecha_nacimiento')->nullable(); $table->enum('alumno_sexo',['M','F'])->nullable(); $table->string('alumno_direccion')->nullable(); $table->string('alumno_telf_fijo')->nullable(); $table->boolean('alumno_padres_juntos')->nullable(); $table->string('alumno_colegio_procedencia')->nullable(); //Datos del Padre $table->string('padre_apellido_paterno')->nullable(); $table->string('padre_apellido_materno')->nullable(); $table->string('padre_nombres')->nullable(); $table->string('padre_numero_documento',15)->nullable(); $table->integer('padre_tipo_documento_id')->unsigned()->nullable(); $table->foreign('padre_tipo_documento_id')->references('id')->on('tipo_documento'); $table->date('padre_fecha_nacimiento')->nullable(); $table->enum('padre_sexo',['M','F'])->nullable(); $table->string('padre_direccion')->nullable(); $table->string('padre_email')->nullable(); $table->string('padre_telf_movil')->nullable(); $table->boolean('padre_vive_educando')->nullable(); $table->enum('padre_estado_civil',['S','C','V','D'])->nullable(); $table->string('padre_ocupacion')->nullable(); $table->string('padre_lugar_trabajo')->nullable(); $table->string('padre_cargo')->nullable(); $table->integer('padre_nivel_educativo_id')->unsigned()->nullable(); $table->foreign('padre_nivel_educativo_id')->references('id')->on('nivel_educativo'); //Datos del Madre $table->string('madre_apellido_paterno')->nullable(); $table->string('madre_apellido_materno')->nullable(); $table->string('madre_nombres')->nullable(); $table->string('madre_numero_documento',15)->nullable(); $table->integer('madre_tipo_documento_id')->unsigned()->nullable(); $table->foreign('madre_tipo_documento_id')->references('id')->on('tipo_documento'); $table->date('madre_fecha_nacimiento')->nullable(); $table->enum('madre_sexo',['M','F'])->nullable(); $table->string('madre_direccion')->nullable(); $table->string('madre_email')->nullable(); $table->string('madre_telf_movil')->nullable(); $table->boolean('madre_apoderado')->nullable(); $table->boolean('madre_vive_educando')->nullable(); $table->enum('madre_estado_civil',['S','C','V','D'])->nullable(); $table->string('madre_ocupacion')->nullable(); $table->string('madre_lugar_trabajo')->nullable(); $table->string('madre_cargo')->nullable(); $table->integer('madre_nivel_educativo_id')->unsigned()->nullable(); $table->foreign('madre_nivel_educativo_id')->references('id')->on('nivel_educativo'); //Datos del Apoderado $table->string('apoderado_nombres')->nullable(); $table->string('apoderado_apellido_paterno')->nullable(); $table->string('apoderado_apellido_materno')->nullable(); $table->string('apoderado_numero_documento',15)->nullable(); $table->integer('apoderado_tipo_documento_id')->unsigned()->nullable(); $table->foreign('apoderado_tipo_documento_id')->references('id')->on('tipo_documento'); $table->date('apoderado_fecha_nacimiento')->nullable(); $table->enum('apoderado_sexo',['M','F'])->nullable(); $table->string('apoderado_direccion')->nullable(); $table->string('apoderado_email')->nullable(); $table->string('apoderado_telf_movil')->nullable(); $table->boolean('apoderado_vive_educando')->nullable(); $table->enum('apoderado_estado_civil',['S','C','V','D'])->nullable(); $table->string('apoderado_ocupacion')->nullable(); $table->string('apoderado_lugar_trabajo')->nullable(); $table->string('apoderado_cargo')->nullable(); $table->integer('apoderado_parentesco_id')->unsigned()->nullable(); $table->foreign('apoderado_parentesco_id')->references('id')->on('parentesco'); $table->integer('apoderado_nivel_educativo_id')->unsigned()->nullable(); $table->foreign('apoderado_nivel_educativo_id')->references('id')->on('nivel_educativo'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ficha_matricula'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaInformacionMedica extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('informacion_medica', function (Blueprint $table) { $table->increments('id'); $table->boolean('especial'); $table->boolean('diabetico'); $table->boolean('operado'); $table->boolean('perdida_conocimiento'); $table->boolean('convulsiones_epilepsia'); $table->text('impedimientos_fisicos'); $table->text('enfermedades'); $table->text('alergias'); $table->text('alergias_sintomas'); $table->boolean('medicado'); $table->text('medicado_dosis'); $table->text('medicado_forma'); $table->text('medicinas_contraindicadas'); $table->text('otros'); $table->enum('grupo_sanguineo',['O-','O+','A−','A+','B−','B+','AB−','AB+']); $table->integer('alumno_id')->unsigned(); $table->foreign('alumno_id')->references('id')->on('alumno')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('informacion_medica'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Turno_Controller extends Controller { public function index() { return view('intranet/mantenimientos/turno'); } public function create() { // } public function store(Request $request) { $turno = new \App\Turno(); $turno->nombre = $request->input('nombre'); $turno->abreviatura = $request->input('abreviatura'); $turno->activo = $request->input('activo'); $turno->save(); } public function show($id) { if (is_numeric($id)) { return \App\Turno::find($id); } else if($id == "*"){ return \App\Turno::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $turno = \App\Turno::find($id); $turno->nombre = $request->input('nombre'); $turno->abreviatura = $request->input('abreviatura'); $turno->activo = $request->input('activo'); $turno->save(); } public function destroy($id) { $turno = \App\Turno::find($id); $turno->delete(); } public function listar() { $turnos = \App\Turno::all(); foreach ($turnos as $turno){ } return $turnos; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Trabajador extends Model { protected $table = "trabajador"; protected $fillable = ['nombres','apellido_paterno','apellido_materno','numero_documento','tipo_documento','fecha_nacimiento','sexo','direccion','telf_movil','telf_fijo','email','activo','nivel_educativo_id','categoria_trabajador_id','especialidad_id','user_info_id']; public function categoria_trabajador(){ return $this->belongsTo('App\Categoria_Trabajador'); } public function especialidad(){ return $this->belongsTo('App\Especialidad'); } public function nivel_educativo(){ return $this->belongsTo('App\Nivel_Educativo'); } public function user_info(){ return $this->belongsTo('App\User_Info'); } public function seccions(){ return $this->hasMany('App\Seccion'); } public function puesto_trabajos(){ return $this->hasMany('App\Puesto_Trabajo'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Noticia_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/noticia'); } public function ver_noticia($id) { $opciones = \App\Opcion_Menu::where('publico',true)->orderBy('orden','asc')->get(); $noticias = \App\Noticia::take(6)->where('publico',true)->where('id','<>',$id)->orderBy('fecha', 'desc')->get(); $noticia = \App\Noticia::find($id); $opciones_footer = \App\Opcion_Footer::where('publico',true)->orderBy('id', 'desc')->get(); $institucion = \App\Institucion::take(1)->get()[0]; return view('website/noticias',['noticia'=>$noticia,'opciones'=>$opciones,'noticias'=>$noticias,'institucion'=>$institucion,"opciones_footer"=>$opciones_footer]); } /** * 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) { $noticia = new \App\Noticia(); $noticia->nombre = $request->input('nombre'); $noticia->descripcion = $request->input('descripcion'); $noticia->contenido = $request->input('contenido'); $noticia->fecha = $request->input('fecha'); $noticia->url_foto = $request->input('url_foto'); $noticia->publico= $request->input('publico'); $noticia->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Noticia::find($id); } else if($id == "*"){ return \App\Noticia::all(); } } /** * 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) { $noticia = \App\Noticia::find($id); $noticia->nombre = $request->input('nombre'); $noticia->descripcion = $request->input('descripcion'); $noticia->contenido = $request->input('contenido'); $noticia->fecha = $request->input('fecha'); $noticia->url_foto = $request->input('url_foto'); $noticia->publico= $request->input('publico'); $noticia->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $noticia = \App\Noticia::find($id); $noticia->delete(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Video_Controller extends Controller { public function index() { return view('intranet/website/video'); } public function create() { // } public function ver_videos() { $opciones = \App\Opcion_Menu::where('publico',true)->orderBy('orden','asc')->get(); $videos = \App\Video::where('publico',true)->orderBy('fecha', 'desc')->get(); $opciones_footer = \App\Opcion_Footer::where('publico',true)->orderBy('id', 'desc')->get(); $institucion = \App\Institucion::take(1)->get()[0]; return view('website/videos',['opciones'=>$opciones,'institucion'=>$institucion,"videos"=>$videos,"opciones_footer"=>$opciones_footer]); } public function store(Request $request) { $video = new \App\Video(); $video->nombre = $request->input('nombre'); $video->fecha = $request->input('fecha'); $video->frame = $request->input('frame'); $video->publico = $request->input('publico'); $video->save(); } public function show($id) { if (is_numeric($id)) { return \App\Video::find($id); } else if($id == "*"){ return \App\Video::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $video = \App\Video::find($id); $video->nombre = $request->input('nombre'); $video->fecha = $request->input('fecha'); $video->frame = $request->input('frame'); $video->publico = $request->input('publico'); $video->save(); } public function destroy($id) { $video = \App\Video::find($id); $video->delete(); } public function listar() { $videos = \App\Video::all(); foreach ($videos as $video){ } return $videos; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Slider extends Model { protected $table = "slider"; protected $fillable = ['orden','nombre','url_foto','url_vinculo','nombre_vinculo','publico']; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; class Website_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $opciones = \App\Opcion_Menu::where('publico',true)->orderBy('orden','asc')->get(); $sliders = \App\Slider::where('publico',true)->orderBy('orden','asc')->get(); $eventos = \App\Evento::where('publico',true)->orderBy('fecha', 'desc')->get(); $noticias = \App\Noticia::where('publico',true)->orderBy('fecha', 'desc')->get(); $testimonios = \App\Testimonio::where('publico',true)->orderBy('id', 'desc')->get(); $opciones_footer = \App\Opcion_Footer::where('publico',true)->orderBy('id', 'desc')->get(); $comunicados = \App\Enlace_Rapido::where('publico',true)->where('categoria','CO')->orderBy('orden','asc')->get(); $documentos = \App\Enlace_Rapido::where('publico',true)->where('categoria','DO')->orderBy('orden','asc')->get(); $descargas = \App\Enlace_Rapido::where('publico',true)->where('categoria','DE')->orderBy('orden','asc')->get(); $fotos = \App\Foto::take(4)->where('favorito',true)->orderBy('id','desc')->get(); $videos = \App\Video::take(3)->where('publico',true)->orderBy('fecha','desc')->get(); $emergentes = \App\Emergente::where('publico',true)->orderBy('fecha', 'desc')->get(); $institucion = \App\Institucion::take(1)->get()[0]; return view('website/principal',['sliders'=>$sliders,'comunicados'=>$comunicados,'documentos'=>$documentos,'descargas'=>$descargas,'eventos' => $eventos,'noticias'=>$noticias,'testimonios'=>$testimonios,'opciones_footer'=>$opciones_footer,'fotos'=>$fotos,'videos'=>$videos,'emergentes'=>$emergentes,'institucion'=>$institucion,'opciones'=>$opciones]); } /** * 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) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Opcion_Menu_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/opcion_menu'); } /** * 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) { $opcion_menu = new \App\Opcion_Menu(); $opcion_menu->orden = $request->input('orden'); $opcion_menu->opcion_superior_id = $request->input('opcion_superior_id'); $opcion_menu->nombre = $request->input('nombre'); $opcion_menu->tipo = $request->input('tipo'); $opcion_menu->url = $request->input('url'); $opcion_menu->publico = $request->input('publico'); $opcion_menu->save(); if($opcion_menu->opcion_superior_id != null){ $this->actualizar_nro_opciones($request->input('opcion_superior_id'),+1); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Opcion_Menu::find($id); } else if($id == "*"){ return \App\Opcion_Menu::all(); } } public function listar() { $opcion_menus = \App\Opcion_Menu::all(); foreach ($opcion_menus as $opcion_menu){ if($opcion_menu->opcion_superior_id !== null) $opcion_menu->opcion_superior; } return $opcion_menus; } /** * 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 actualizar_nro_opciones($id,$valor) { $opcion_superior = \App\Opcion_Menu::find($id); $opcion_superior->nro_opciones += $valor; $opcion_superior->save(); } public function update(Request $request, $id) { $opcion_menu = \App\Opcion_Menu::find($id); if($opcion_menu->opcion_superior_id !== $request->input('opcion_superior_id')){ //Si se altera la opcion superior if($opcion_menu->opcion_superior_id == null){ //Si no tenia opcion superior se agrega 1 a la opcion superior nueva $this->actualizar_nro_opciones($request->input('opcion_superior_id'),1); }else{ // si ya tenia una opcion superior disminuir $this->actualizar_nro_opciones($opcion_menu->opcion_superior_id,-1); if($request->input('opcion_superior_id') !== null) $this->actualizar_nro_opciones($request->input('opcion_superior_id'),+1); } } $opcion_menu->orden = $request->input('orden'); $opcion_menu->opcion_superior_id = $request->input('opcion_superior_id'); $opcion_menu->nombre = $request->input('nombre'); $opcion_menu->tipo = $request->input('tipo'); $opcion_menu->url = $request->input('url'); $opcion_menu->publico = $request->input('publico'); $opcion_menu->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $opcion_menu = \App\Opcion_Menu::find($id); //Creamos variable guardando el valor porque si no se pudiera eliminar el valor porque dependen de el, no se debería disminuir $opcion_superior_id = $opcion_menu->opcion_superior_id; $opcion_menu->delete(); $this->actualizar_nro_opciones($opcion_superior_id,-1); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Grado extends Model { protected $table = "grado"; protected $fillable = ['nombre','numero','activo','nivel_id','grado_anterior_id']; public function nivel(){ return $this->belongsTo('App\Nivel'); } public function grado_anterior(){ return $this->belongsTo('App\Grado'); } public function grado_anteriors(){ return $this->hasOne('App\Grado'); } public function seccions(){ return $this->hasMany('App\Seccion'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Institucion_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/institucion'); } /** * 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) { } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return \App\Institucion::take(1)->get(); } /** * 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) { $institucion = \App\Institucion::find($id); $institucion->telefonos= $request->input('telefonos'); $institucion->correo= $request->input('correo'); $institucion->ciudad= $request->input('ciudad'); $institucion->direccion= $request->input('direccion'); $institucion->link_mapa= $request->input('link_mapa'); $institucion->bienvenida_url= $request->input('bienvenida_url'); $institucion->bienvenida_texto= $request->input('bienvenida_texto'); $institucion->porque_nosotros_1= $request->input('porque_nosotros_1'); $institucion->porque_nosotros_2= $request->input('porque_nosotros_2'); $institucion->porque_nosotros_3= $request->input('porque_nosotros_3'); $institucion->porque_nosotros_4= $request->input('porque_nosotros_4'); $institucion->anio_ficha = $request->input('anio_ficha'); $institucion->mostrar_ficha = $request->input('mostrar_ficha'); $institucion->mostrar_tramite = $request->input('mostrar_tramite'); $institucion->sms_celular = $request->input('sms_celular'); $institucion->sms_cabecera = $request->input('sms_cabecera'); $institucion->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Evento extends Model { protected $table = "evento"; protected $fillable = ['nombre','decripcion','fecha','lugar','hora','contenido','publico']; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Estado_Tramite_Controller extends Controller { public function index() { return view('intranet/mantenimientos/estado_tramite'); } public function create() { // } public function store(Request $request) { $estado_tramite = new \App\Estado_Tramite(); $estado_tramite->nombre = $request->input('nombre'); $estado_tramite->color = $request->input('color'); $estado_tramite->icono = $request->input('icono'); $estado_tramite->save(); } public function show($id) { if (is_numeric($id)) { return \App\Estado_Tramite::find($id); } else if($id == "*"){ return \App\Estado_Tramite::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $estado_tramite = \App\Estado_Tramite::find($id); $estado_tramite->nombre = $request->input('nombre'); $estado_tramite->color = $request->input('color'); $estado_tramite->icono = $request->input('icono'); $estado_tramite->save(); } public function destroy($id) { $estado_tramite = \App\Estado_Tramite::find($id); $estado_tramite->delete(); } public function listar() { $estado_tramites = \App\Estado_Tramite::all(); foreach ($estado_tramites as $estado_tramite){ } return $estado_tramites; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\DB; class Seccion_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/seccion'); } /** * 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) { $seccion = new \App\Seccion(); $seccion->anio_lectivo_id = $request->input('anio_lectivo_id'); $seccion->grado_id = $request->input('grado_id'); $seccion->trabajador_id = $request->input('trabajador_id'); $seccion->letra= $request->input('letra'); $seccion->turno_id= $request->input('turno_id'); $seccion->tipo_calificacion= $request->input('tipo_calificacion'); $seccion->vacantes= $request->input('vacantes'); $seccion->activo= $request->input('activo'); $seccion->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Seccion::find($id); } else if($id == "*"){ return \App\Seccion::all(); } } public function listar() { $turno_id = Input::get('turno_id'); $anio_lectivo_id = Input::get('anio_lectivo_id'); $secciones = \App\Seccion::where([ ['anio_lectivo_id','=', $anio_lectivo_id], ['turno_id', '=', $turno_id], ])->get(); foreach ($secciones as $seccion){ $seccion->grado; $seccion->grado->nivel; $seccion->trabajador; $seccion->turno; } return $secciones; } /** * 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) { $seccion = \App\Seccion::find($id); $seccion->grado_id = $request->input('grado_id'); $seccion->trabajador_id = $request->input('trabajador_id'); $seccion->letra= $request->input('letra'); $seccion->tipo_calificacion= $request->input('tipo_calificacion'); $seccion->vacantes= $request->input('vacantes'); $seccion->activo= $request->input('activo'); $seccion->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $seccion = \App\Seccion::find($id); $seccion->delete(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Familiar_Controller extends Controller { public function index() { return view('intranet/mantenimientos/familiar'); } public function create() { // } public function store(Request $request) { $familiar = new \App\Familiar(); $familiar->nombre_completo = $request->input('nombre_completo'); $familiar->tipo_documento = $request->input('tipo_documento'); $familiar->numero_documento = $request->input('numero_documento'); $familiar->sexo = $request->input('sexo'); $familiar->fecha_nacimiento = $request->input('fecha_nacimiento'); $familiar->direccion = $request->input('direccion'); $familiar->email = $request->input('email'); $familiar->telf_movil = $request->input('telf_movil'); $familiar->telf_fijo = $request->input('telf_fijo'); $familiar->estado_civil = $request->input('estado_civil'); $familiar->ocupacion = $request->input('ocupacion'); $familiar->lugar_trabajo = $request->input('lugar_trabajo'); $familiar->activo = $request->input('activo'); $familiar->nivel_educativo_id = $request->input('nivel_educativo_id'); $familiar->save(); } public function show($id) { if (is_numeric($id)) { return \App\Familiar::find($id); } else if($id == "*"){ return \App\Familiar::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $familiar = \App\Familiar::find($id); $familiar->nombre_completo = $request->input('nombre_completo'); $familiar->tipo_documento = $request->input('tipo_documento'); $familiar->numero_documento = $request->input('numero_documento'); $familiar->sexo = $request->input('sexo'); $familiar->fecha_nacimiento = $request->input('fecha_nacimiento'); $familiar->direccion = $request->input('direccion'); $familiar->email = $request->input('email'); $familiar->telf_movil = $request->input('telf_movil'); $familiar->telf_fijo = $request->input('telf_fijo'); $familiar->estado_civil = $request->input('estado_civil'); $familiar->ocupacion = $request->input('ocupacion'); $familiar->lugar_trabajo = $request->input('lugar_trabajo'); $familiar->activo = $request->input('activo'); $familiar->nivel_educativo_id = $request->input('nivel_educativo_id'); $familiar->save(); } public function destroy($id) { $familiar = \App\Familiar::find($id); $familiar->delete(); } public function listar() { $familiars = \App\Familiar::all(); foreach ($familiars as $familiar){ } return $familiars; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Parentesco_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/parentesco'); } /** * 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) { $parentesco = new \App\Parentesco(); $parentesco->nombre = $request->input('nombre'); $parentesco->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Parentesco::find($id); } else if($id == "*"){ return \App\Parentesco::all(); } } /** * 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) { $parentesco = \App\Parentesco::find($id); $parentesco->nombre = $request->input('nombre'); $parentesco->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $parentesco = \App\Parentesco::find($id); $parentesco->delete(); } } <file_sep><?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(Categoria_Trabajador_Seeder::class); $this->call(Especialidad_Seeder::class); $this->call(Parentesco_Seeder::class); $this->call(Colegio_Procedencia_Seeder::class); $this->call(Nivel_Educativo_Seeder::class); $this->call(Alumno_Seeder::class); $this->call(Trabajador_Seeder::class); $this->call(Academico_2017_Seeder::class); $this->call(Website_Seeder::class); $this->call(Familiar_Seeder::class); // $this->call(UsersTableSeeder::class); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Enlace_Rapido extends Model { protected $table = "enlace_rapido"; protected $fillable = ['orden','nombre','categoria','url','color','publico']; } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Alumno extends Model { protected $table = "alumno"; protected $fillable = ['nombres','apellido_paterno','apellido_materno','numero_documento','tipo_documento','fecha_nacimiento','sexo','direccion','telf_fijo','codigo_educando','url_foto','codigo_recaudacion','activo','padres_juntos','colegio_procedencia_id','user_info_id']; public function colegio_procedencia(){ return $this->belongsTo('App\Colegio_Procedencia'); } public function user_info(){ return $this->belongsTo('App\User_Info'); } public function apoderados(){ return $this->hasMany('App\Apoderado'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Noticia extends Model { protected $table = "noticia"; protected $fillable = ['nombre','decripcion','contenido','fecha','url_foto','publico']; } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaAlumnoFamiliar extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('alumno_familiar', function (Blueprint $table) { $table->increments('id'); $table->boolean('apoderado'); $table->boolean('vive_educando'); $table->integer('familiar_id')->unsigned(); $table->foreign('familiar_id')->references('id')->on('familiar'); $table->integer('parentesco_id')->unsigned(); $table->foreign('parentesco_id')->references('id')->on('parentesco'); $table->integer('alumno_id')->unsigned(); $table->foreign('alumno_id')->references('id')->on('alumno'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('alumno_familiar'); } } <file_sep><?php namespace App\Http\Controllers; use Tymon\JWTAuth\Facades\JWTAuth; use Illuminate\Http\Request; use Tymon\JWTAuth\Exceptions\JWTException; use Hash; class ApiAuthController extends Controller { // public function authenticate(Request $request) { // grab credentials from the request $email = $request->input('email'); $password = $request->input('password'); $user = \App\User::where('email',$email)->firstOrFail(); if($user != null){ $user_info = \App\User_Info::where('user_id',$user->id)->firstOrFail(); if(Hash::check($password,$user_info->clave)){ if($user_info->activo == true){ try { $credentials = $request->only('email','password'); $token = JWTAuth::attempt($credentials); //$token = JWTAuth::fromUser($user); if(!$token){ return response()->json(['error' => 'invalid_credentials3'], 401); } //$token = JWTAuth::fromUser($user); return response()->json(['token' => $token],200); } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); } }else{ return response()->json(['error' => 'Usuario inactivo'], 401); } }else{ return response()->json(['error' => 'Credenciales Inválidas'], 401); } }else{ return response()->json(['error' => 'Credenciales Inválidas'], 401); } } public function authenticate2(Request $request) { // grab credentials from the request $credentials = $request->only('email', 'password'); try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); } // all good so return the token return response()->json(compact('token')); } public function logout(Request $request){ try { //$token = $request->input("token"); JWTAuth::parseToken()->invalidate(); return response()->json(['message' => "correcto"],200); } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'Could no logout'], 500); } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Puesto_Trabajo extends Model { protected $table = "puesto_trabajo"; protected $fillable = ['nombre','trabajador_id','registro']; public function trabajador(){ return $this->belongsTo('App\Trabajador'); } public function emite_tramite_transferidos(){ return $this->hasMany('App\Tramite_Transferido'); } public function recibe_tramite_transferidos(){ return $this->hasMany('App\Tramite_Transferido'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Tipo_Tramite_Controller extends Controller { public function index() { return view('tipo_tramite'); } public function create() { // } public function store(Request $request) { $tipo_tramite = new \App\Tipo_Tramite(); $tipo_tramite->nombre = $request->input('nombre'); $tipo_tramite->activo = $request->input('activo'); $tipo_tramite->save(); } public function show($id) { if (is_numeric($id)) { return \App\Tipo_Tramite::find($id); } else if($id == "*"){ return \App\Tipo_Tramite::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $tipo_tramite = \App\Tipo_Tramite::find($id); $tipo_tramite->nombre = $request->input('nombre'); $tipo_tramite->activo = $request->input('activo'); $tipo_tramite->save(); } public function destroy($id) { $tipo_tramite = \App\Tipo_Tramite::find($id); $tipo_tramite->delete(); } public function listar() { $tipo_tramites = \App\Tipo_Tramite::all(); foreach ($tipo_tramites as $tipo_tramite){ } return $tipo_tramites; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Alumno_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/alumno'); } /** * 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) { $alumno = new \App\Alumno(); $alumno->nombres = $request->input('nombres'); $alumno->apellido_paterno = $request->input('apellido_paterno'); $alumno->apellido_materno = $request->input('apellido_materno'); $alumno->numero_documento= $request->input('numero_documento'); $alumno->tipo_documento= $request->input('tipo_documento'); $alumno->fecha_nacimiento= $request->input('fecha_nacimiento'); $alumno->sexo= $request->input('sexo'); $alumno->direccion = $request->input('direccion'); $alumno->telf_fijo= $request->input('telf_fijo'); $alumno->colegio_procedencia_id= $request->input('colegio_procedencia_id'); $alumno->codigo_educando= $request->input('codigo_educando'); $alumno->codigo_recaudacion= $request->input('codigo_recaudacion'); $alumno->padres_juntos= $request->input('padres_juntos'); $alumno->activo= $request->input('activo'); $alumno->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { $alumno = \App\Alumno::find($id); $alumno->colegio_procedencia; $alumno->user_info; $alumno->user_info->user; return $alumno; }else if($id == "*"){ return \App\Alumno::where('activo',true)->select('id','apellido_paterno', 'apellido_materno','nombres')->get(); } } public function listar() { $alumnos = \App\Alumno::orderBy('apellido_paterno', 'ASC')->orderBy('apellido_materno', 'ASC')->orderBy('nombres', 'ASC')->get(); foreach ($alumnos as $alumno){ $alumno->colegio_procedencia; } return $alumnos; } public function buscar_numero_documento() { $numero_documento = Input::get('numero_documento'); if (is_numeric($numero_documento)) { return \App\Alumno::where('numero_documento',$numero_documento)->get(); } } /** * 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) { $alumno = \App\Alumno::find($id); $alumno->nombres = $request->input('nombres'); $alumno->apellido_paterno = $request->input('apellido_paterno'); $alumno->apellido_materno = $request->input('apellido_materno'); $alumno->numero_documento= $request->input('numero_documento'); $alumno->tipo_documento= $request->input('tipo_documento'); $alumno->fecha_nacimiento= $request->input('fecha_nacimiento'); $alumno->sexo= $request->input('sexo'); $alumno->direccion = $request->input('direccion'); $alumno->telf_fijo= $request->input('telf_fijo'); $alumno->colegio_procedencia_id= $request->input('colegio_procedencia_id'); $alumno->codigo_educando= $request->input('codigo_educando'); $alumno->codigo_recaudacion= $request->input('codigo_recaudacion'); $alumno->padres_juntos= $request->input('padres_juntos'); $alumno->activo= $request->input('activo'); $alumno->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $alumno = \App\Alumno::find($id); $alumno->delete(); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\Alumno::class, function (Faker\Generator $faker) { return [ 'nombres' => $faker->name, 'apellido_paterno' => $faker->lastName, 'apellido_materno' => $faker->lastName, //'email' => $faker->unique()->safeEmail, 'numero_documento' => $faker->unique()->numberBetween(11111111,99999999), 'tipo_documento' => 'DN', 'fecha_nacimiento' => $faker->date('Y-m-d','now'), 'sexo' => $faker->randomElement(($array = array('M','F'))), 'direccion' => $faker->address, 'telf_fijo' => $faker->tollFreePhoneNumber, 'padres_juntos' => true, 'activo'=>true, 'colegio_procedencia_id'=> \App\Colegio_Procedencia::all()->random()->id ]; }); $factory->define(App\Trabajador::class, function (Faker\Generator $faker) { return [ 'nombres' => $faker->name, 'apellido_paterno' => $faker->lastName, 'apellido_materno' => $faker->lastName, 'email' => $faker->unique()->safeEmail, 'numero_documento' => $faker->unique()->numberBetween(11111111,99999999), 'tipo_documento' => 'DN', 'fecha_nacimiento' => $faker->date('Y-m-d','now'), 'sexo' => $faker->randomElement(($array = array('M','F'))), 'direccion' => $faker->address, 'telf_fijo' => $faker->tollFreePhoneNumber, 'telf_movil' => $faker->e164PhoneNumber, 'activo'=>true, 'categoria_trabajador_id'=> \App\Categoria_Trabajador::all()->random()->id, 'nivel_educativo_id'=> \App\Nivel_Educativo::all()->random()->id, 'especialidad_id'=> \App\Especialidad::all()->random()->id ]; }); <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaOpcionMenu extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('opcion_menu', function (Blueprint $table) { $table->increments('id'); $table->integer('orden'); $table->string('nombre'); $table->string('url'); $table->integer('nro_opciones')->default(0); $table->enum('tipo',['L','B'])->default('L'); //LINK | BUTTON $table->integer('opcion_superior_id')->unsigned()->nullable(); $table->foreign('opcion_superior_id')->references('id')->on('opcion_menu'); $table->boolean('publico'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('opcion_menu'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use File; class Album_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/website/album'); } public function ver_galeria() { $opciones = \App\Opcion_Menu::where('publico',true)->orderBy('orden','asc')->get(); $albums = \App\Album::where('publico',true)->orderBy('fecha', 'desc')->get(); $opciones_footer = \App\Opcion_Footer::where('publico',true)->orderBy('id', 'desc')->get(); $institucion = \App\Institucion::take(1)->get()[0]; return view('website/galeria',['opciones'=>$opciones,'institucion'=>$institucion,"albums"=>$albums,"opciones_footer"=>$opciones_footer]); } /** * 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) { $album = new \App\Album(); $album->nombre = $request->input('nombre'); $album->fecha = $request->input('fecha'); $album->publico = $request->input('publico'); $album->save(); $path = public_path().'/royal/img/galeria/' . $album->id; File::makeDirectory($path, $mode = 0777, true, true); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { return \App\Album::find($id); } else if($id == "*"){ return \App\Album::all(); } } /** * 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) { $album = \App\Album::find($id); $album->nombre = $request->input('nombre'); $album->fecha = $request->input('fecha'); $album->publico = $request->input('publico'); $album->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $album = \App\Album::find($id); $album_id = $album->id; $album->delete(); $path = public_path().'/royal/img/galeria/' . $album->id; File::deleteDirectory($path); } } <file_sep><?php namespace App\Http\Controllers; use App\Usuario; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class Trabajador_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/trabajador'); } /** * 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) { $trabajador = new \App\Trabajador(); $trabajador->nombres = $request->input('nombres'); $trabajador->apellido_paterno = $request->input('apellido_paterno'); $trabajador->apellido_materno = $request->input('apellido_materno'); $trabajador->numero_documento= $request->input('numero_documento'); $trabajador->tipo_documento= $request->input('tipo_documento'); $trabajador->fecha_nacimiento= $request->input('fecha_nacimiento'); $trabajador->sexo= $request->input('sexo'); $trabajador->direccion= $request->input('direccion'); $trabajador->email= $request->input('email'); $trabajador->telf_movil= $request->input('telf_movil'); $trabajador->telf_fijo= $request->input('telf_fijo'); $trabajador->nivel_educativo_id= $request->input('nivel_educativo_id'); $trabajador->especialidad_id= $request->input('especialidad_id'); $trabajador->categoria_trabajador_id= $request->input('categoria_trabajador_id'); $trabajador->activo= $request->input('activo'); $trabajador->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { $trabajador = \App\Trabajador::find($id); $trabajador->nivel_educativo; $trabajador->categoria_trabajador; $trabajador->especialidad; $trabajador->user_info; if($trabajador->user_info != null) $trabajador->user_info->user; return $trabajador; } } public function listar() { $trabajadores = \App\Trabajador::orderBy('apellido_paterno', 'ASC')->orderBy('apellido_materno', 'ASC')->orderBy('nombres', 'ASC')->get(); foreach ($trabajadores as $trabajador){ $trabajador->nivel_educativo; $trabajador->categoria_trabajador; $trabajador->especialidad; } return $trabajadores; } public function listar_usuarios() { $trabajadores = \App\Trabajador::orderBy('apellido_paterno', 'ASC')->orderBy('apellido_materno', 'ASC')->orderBy('nombres', 'ASC')->get(); foreach ($trabajadores as $trabajador){ $trabajador->user_info; if($trabajador->user_info != null) $trabajador->user_info->user; } return $trabajadores; } public function buscar_numero_documento() { $numero_documento = Input::get('numero_documento'); if (is_numeric($numero_documento)) { return \App\Trabajador::where('numero_documento',$numero_documento)->get(); } } /** * 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) { $trabajador = \App\Trabajador::find($id); $trabajador->nombres = $request->input('nombres'); $trabajador->apellido_paterno = $request->input('apellido_paterno'); $trabajador->apellido_materno = $request->input('apellido_materno'); $trabajador->numero_documento= $request->input('numero_documento'); $trabajador->tipo_documento= $request->input('tipo_documento'); $trabajador->fecha_nacimiento= $request->input('fecha_nacimiento'); $trabajador->sexo= $request->input('sexo'); $trabajador->direccion= $request->input('direccion'); $trabajador->email= $request->input('email'); $trabajador->telf_movil= $request->input('telf_movil'); $trabajador->telf_fijo= $request->input('telf_fijo'); $trabajador->nivel_educativo_id= $request->input('nivel_educativo_id'); $trabajador->especialidad_id= $request->input('especialidad_id'); $trabajador->categoria_trabajador_id= $request->input('categoria_trabajador_id'); $trabajador->activo= $request->input('activo'); $trabajador->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $trabajador = \App\Trabajador::find($id); $trabajador->delete(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Alumno_Familiar_Controller extends Controller { public function index() { return view('alumno_familiar'); } public function create() { // } public function store(Request $request) { $alumno_familiar = new \App\Alumno_Familiar(); $alumno_familiar->apoderado = $request->input('apoderado'); $alumno_familiar->vive_educando = $request->input('vive_educando'); $alumno_familiar->familiar_id = $request->input('familiar_id'); $alumno_familiar->parentesco_id = $request->input('parentesco_id'); $alumno_familiar->alumno_id = $request->input('alumno_id'); $alumno_familiar->save(); } public function show($id) { if (is_numeric($id)) { return \App\Alumno_Familiar::find($id); } else if($id == "*"){ return \App\Alumno_Familiar::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $alumno_familiar = \App\Alumno_Familiar::find($id); $alumno_familiar->apoderado = $request->input('apoderado'); $alumno_familiar->vive_educando = $request->input('vive_educando'); $alumno_familiar->familiar_id = $request->input('familiar_id'); $alumno_familiar->parentesco_id = $request->input('parentesco_id'); $alumno_familiar->alumno_id = $request->input('alumno_id'); $alumno_familiar->save(); } public function destroy($id) { $alumno_familiar = \App\Alumno_Familiar::find($id); $alumno_familiar->delete(); } public function listar() { $alumno_familiars = \App\Alumno_Familiar::all(); foreach ($alumno_familiars as $alumno_familiar){ } return $alumno_familiars; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Tipo_Documento extends Model { protected $table = "tipo_documento"; protected $fillable = ['codigo','descripcion','abreviatura','activo']; public function alumno_ficha_matriculas(){ return $this->hasMany('App\Ficha_Matricula'); } public function padre_ficha_matriculas(){ return $this->hasMany('App\Ficha_Matricula'); } public function madre_ficha_matriculas(){ return $this->hasMany('App\Ficha_Matricula'); } public function apoderado_ficha_matriculas(){ return $this->hasMany('App\Ficha_Matricula'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class User_Info_Controller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('intranet/mantenimientos/usuario'); } /** * 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) { $usuario = new \App\User(); $usuario->name =$request->input('alias'); $usuario->email = $request->input('alias'); $usuario->password = <PASSWORD>($request->input('clave1').''); $usuario->save(); if($usuario->id != null){ //Datos de User Info $tipo = $request->input('tipo'); $persona_id = $request->input('persona_id'); $user_info = new \App\User_Info(); $user_info->user_id = $usuario->id; $user_info->clave= bcrypt($request->input('clave1').''); $user_info->tipo = $tipo; $user_info->persona_id= $persona_id; $user_info->cambia_clave= $request->input('cambia_clave'); $user_info->activo = $request->input('activo'); $user_info->save(); switch($tipo){ case "TR": $trabajador = \App\Trabajador::find($persona_id); $trabajador->user_info_id = $user_info->id; $usuario->name = $trabajador->nombres." ".$trabajador->apellido_paterno; $usuario->save(); $trabajador->save(); break; case "AL": $alumno = \App\Alumno::find($persona_id); $alumno->user_info_id = $user_info->id; $alumno->save(); break; } } } public function update(Request $request, $id) { $user_info = \App\User_Info::find($id); $user = \App\User::find($user_info->user_id); $user->email = $request->input('alias'); $user_info->cambia_clave = $request->input('cambia_clave'); $user_info->activo = $request->input('activo'); $user_info->save(); $user->save(); $user_info->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (is_numeric($id)) { $user_info = \App\User_Info::find($id); $user_info->user; return $user_info; } else if($id == "*"){ return \App\User_Info::all(); } } /** * 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 */ /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $user_info = \App\User_Info::find($id); $user = \App\User::find($user_info->user_id); switch($user_info->tipo){ case "TR": $trabajador = \App\Trabajador::find($user_info->persona_id); $trabajador->user_info_id = null; $trabajador->save(); break; case "AL": $alumno = \App\Alumno::find($user_info->persona_id); $alumno->user_info_id = null; $alumno->save(); break; } $user_info->delete(); $user->delete(); } } <file_sep><?php use Illuminate\Database\Seeder; class Parentesco_Seeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('parentesco')->insert([ ['nombre' => "PADRE"], ['nombre' => "MADRE"], ['nombre' => "TIO"], ['nombre' => "TIA"], ['nombre' => "PADRASTRO"], ['nombre' => "MADRASTRA"], ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\Http\Requests; use Image; use File; use App\Library\imageLib; class Foto_Controller extends Controller { public function index() { // } /** * 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) { $album_id = $request->input('album_id'); $transparencia = $request->input('transparencia') == "true" ? true:false; //Decide si lo conviertes en JPG $path = public_path() . '/royal/img/galeria/'.$album_id."/"; $files = $request->file('file'); foreach ($files as $file) { $fileName = str_replace("ñ","n",str_replace(" ","_",mb_strtolower($file->getClientOriginalName(),'UTF-8'))); $fileExtension = strtolower($file->getClientOriginalExtension()); $archivo = time().$fileName; $foto = new \App\Foto(); $foto->nombre = $fileName; $foto->archivo = "/royal/img/galeria/".$album_id."/".$archivo; $foto->extension =$fileExtension; $foto->album_id = $album_id; $foto->save(); $file->move($path,$archivo); if($fileExtension == "png" && $transparencia){ $old_f = public_path().$foto->archivo; $new_f = str_replace(".png", ".jpg",$foto->archivo); $this->png2jpg($old_f,public_path().$new_f,100); if(File::exists($old_f)) File::delete($old_f); $foto->archivo = $new_f; $foto->extension = "jpg"; $foto->nombre = str_replace(".png", ".jpg",$foto->nombre); $foto->save(); } list($ancho, $alto) = getimagesize(public_path().$foto->archivo); //Redimensionar la imagen de ser pesada if($ancho > $alto){ if($ancho > 1024){ $img = new imageLib(public_path().$foto->archivo); $img-> resizeImage(1024, 0,'landscape'); $img->saveImage(public_path().$foto->archivo); } }else{ if($alto > 768){ $img = new imageLib(public_path().$foto->archivo); $img-> resizeImage(0, 768,'portrait'); $img->saveImage(public_path().$foto->archivo); } } $album = \App\Album::find($album_id); $album->nro_fotos += 1; $album->save(); } } function png2jpg($originalFile, $outputFile, $quality) { $image = imagecreatefrompng($originalFile); imagejpeg($image, $outputFile, $quality); imagedestroy($image); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ function show($id) { } public function listar() { return \App\Foto::where('album_id',Input::get('album_id'))->orderBy('id','desc')->get(); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ function update(Request $request, $id) { $foto = \App\Foto::find($id); $foto->nombre = $request->input('nombre'); $foto->favorito = $request->input('favorito'); $foto->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ function destroy($id) { $foto = \App\Foto::find($id); $archivo = public_path().$foto->archivo; $album = \App\Album::find($foto->album_id); if(File::exists($archivo)) File::delete($archivo); $foto->delete(); $album->nro_fotos += -1; $album->save(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Tramite_Transferido_Controller extends Controller { public function index() { return view('tramite_transferido'); } public function create() { // } public function store(Request $request) { $tramite_transferido = new \App\Tramite_Transferido(); $tramite_transferido->tramite_id = $request->input('tramite_id'); $tramite_transferido->emite_trabajador_id = $request->input('emite_trabajador_id'); $tramite_transferido->emite_puesto_trabajo_id = $request->input('emite_puesto_trabajo_id'); $tramite_transferido->emite_observacion = $request->input('emite_observacion'); $tramite_transferido->emite_estado_tramite_id = $request->input('emite_estado_tramite_id'); $tramite_transferido->recibe_trabajador_id = $request->input('recibe_trabajador_id'); $tramite_transferido->recibe_puesto_trabajo_id = $request->input('recibe_puesto_trabajo_id'); $tramite_transferido->recibe_observacion = $request->input('recibe_observacion'); $tramite_transferido->recibe_estado_tramite_id = $request->input('recibe_estado_tramite_id'); $tramite_transferido->vigencia = $request->input('vigencia'); $tramite_transferido->save(); } public function show($id) { if (is_numeric($id)) { return \App\Tramite_Transferido::find($id); } else if($id == "*"){ return \App\Tramite_Transferido::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $tramite_transferido = \App\Tramite_Transferido::find($id); $tramite_transferido->tramite_id = $request->input('tramite_id'); $tramite_transferido->emite_trabajador_id = $request->input('emite_trabajador_id'); $tramite_transferido->emite_puesto_trabajo_id = $request->input('emite_puesto_trabajo_id'); $tramite_transferido->emite_observacion = $request->input('emite_observacion'); $tramite_transferido->emite_estado_tramite_id = $request->input('emite_estado_tramite_id'); $tramite_transferido->recibe_trabajador_id = $request->input('recibe_trabajador_id'); $tramite_transferido->recibe_puesto_trabajo_id = $request->input('recibe_puesto_trabajo_id'); $tramite_transferido->recibe_observacion = $request->input('recibe_observacion'); $tramite_transferido->recibe_estado_tramite_id = $request->input('recibe_estado_tramite_id'); $tramite_transferido->vigencia = $request->input('vigencia'); $tramite_transferido->save(); } public function destroy($id) { $tramite_transferido = \App\Tramite_Transferido::find($id); $tramite_transferido->delete(); } public function listar() { $tramite_transferidos = \App\Tramite_Transferido::all(); foreach ($tramite_transferidos as $tramite_transferido){ } return $tramite_transferidos; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Opcion_Menu extends Model { protected $table = "opcion_menu"; protected $fillable = ['orden','nombre','url','opcion_superior_id','publico']; public function opcion_superior(){ return $this->belongsTo('App\Opcion_Menu'); } public function opcion_superiors(){ return $this->hasOne('App\Opcion_Menu'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Apoderado extends Model { protected $table = "apoderado"; protected $fillable = ['nombres','apellido_paterno','apellido_materno','numero_documento','tipo_documento','fecha_nacimiento','sexo','direccion','email','telf_movil','telf_fijo','apoderado','vive_educando','estado_civil','ocupacion','lugar_trabajo','activo','alumno_id','parentesco_id','nivel_educativo_id']; public function nivel_educativo(){ return $this->belongsTo('App\Nivel_Educativo'); } public function parentesco(){ return $this->belongsTo('App\Parentesco'); } public function alumno(){ return $this->belongsTo('App\Alumno'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Puesto_Trabajo_Controller extends Controller { public function index() { return view('intranet/mantenimientos/puesto_trabajo'); } public function create() { } public function store(Request $request) { $puesto_trabajo = new \App\Puesto_Trabajo(); $puesto_trabajo->nombre = $request->input('nombre'); $puesto_trabajo->trabajador_id = $request->input('trabajador_id'); $puesto_trabajo->registro = $request->input('registro'); $puesto_trabajo->save(); } public function show($id) { if (is_numeric($id)) { return \App\Puesto_Trabajo::find($id); } else if($id == "*"){ return \App\Puesto_Trabajo::all(); } } public function edit($id) { // } public function update(Request $request, $id) { $puesto_trabajo = \App\Puesto_Trabajo::find($id); $puesto_trabajo->nombre = $request->input('nombre'); $puesto_trabajo->trabajador_id = $request->input('trabajador_id'); $puesto_trabajo->registro = $request->input('registro'); $puesto_trabajo->save(); } public function destroy($id) { $puesto_trabajo = \App\Puesto_Trabajo::find($id); $puesto_trabajo->delete(); } public function listar() { $puesto_trabajos = \App\Puesto_Trabajo::all(); foreach ($puesto_trabajos as $puesto_trabajo){ $puesto_trabajo->trabajador; } return $puesto_trabajos; } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreacionTablaControlReunion extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('control_reunion', function (Blueprint $table) { $table->increments('id'); $table->string('ref_alumno'); $table->string('ref_seccion'); $table->enum('sexo',['M','F']); $table->string('nombre_completo'); $table->string('numero_documento',15)->nullable(); ; $table->dateTime('marcacion')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('control_reunion'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Control_Reunion extends Model { protected $table = "control_reunion"; protected $fillable = ['ref_alumno','ref_seccion','sexo','nombre_completo','numero_documento','marcacion']; }
465fdddb17316df375e81f92a624226cc7d04169
[ "PHP" ]
81
PHP
oversanchez/colegio
4a0ad36c683170fba4dfcc2d9a586f58180ce4fb
c5e1e8ff6bfaf51ce53859fb80e4fb383d16cf1d
refs/heads/master
<repo_name>calphiko/dmx512<file_sep>/README.md dmx512 ====== Open Source Dmx 512 System <file_sep>/RaspberryPi/Test_RS232/rs232_test.py import serial import time ser = serial.Serial("/dev/ttyAMA0", 250000) while 1>0: # Sende V, Dezimal: 86 # Binär: 01010110 (Invertiert) ser.write("VV") time.sleep(1) read = ser.read() print read ser.close()
84cb9aee67f693b839f30263691afdf0276a67e3
[ "Markdown", "Python" ]
2
Markdown
calphiko/dmx512
49b970bd5b08ad140ea291e153406411f0ce2427
b19f28f2be2fb472147322ae5a94d75a5c754cf8
refs/heads/master
<file_sep>import { SELECTED_USER } from '../actions/index'; export default function(state =[], action) { console.log('Selected user', action) switch(action.type) { case SELECTED_USER: return action.payload.data; } return state; }<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { selectedUser } from '../actions'; //import { bindActionCreator, bindActionCreators } from 'redux'; class SelectedUserComponent extends Component { render(){ if (!this.props.selectedUser[0]){ return (<div></div>); } return( <div> <img src={this.props.selectedUser[0].picture} className="img-circle imageUser" alt={this.props.selectedUser[0].name}/> {this.props.selectedUser[0].name} </div> ); } } function mapStateToProps(state) { return { selectedUser: state.selectedUser }; } export default connect (mapStateToProps)(SelectedUserComponent); <file_sep>import React, { Component } from 'react'; import UsersList from './users_list'; import Chat from './chat'; export default class App extends Component { render() { return ( <div className="container-fluid"> <div className="row"> <UsersList /> <Chat /> </div> </div> ); } } <file_sep>import { CURRENT_USER } from '../actions/index'; export default function(state = '', action) { console.log('Curent User', action) switch(action.type) { case CURRENT_USER: return action.payload; } return state; }
64cc22f838fcb9f0a716631366a040ec7385edab
[ "JavaScript" ]
4
JavaScript
AlinaGaidamaka/chatty-app
5da6acce3a9e3e342e2698a1e511fe27e7d2fd95
2ae141258994b63a76a0efa4a86bc19fdc244a1f
refs/heads/master
<repo_name>pvikitset/Weather.Notifier<file_sep>/settings.py DARKSKY_ACCESS_TOKEN = '' LOCATIONS = ('Regina',50.432504,-104.524737) BOT_EMAIL = '<EMAIL>' TARGET_EMAIL = '<EMAIL>' SUBJECT = 'Weather Notifier' TIME_TO_SEND = '06:00'<file_sep>/README.md # Weather-Notifier Collect weather data through DarkSky API and email it out as its schedule<br> Reference: <br> weather API from: https://darksky.net/dev <br> schedule lib: https://github.com/dbader/schedule <file_sep>/weather.py # -*- coding: utf-8 -*-1 import csv import datetime import schedule import time import json import sys import traceback import urllib.request from pathlib import Path import smtplib import settings from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def get_url(day_location): day = '{:{dfmt}}'.format(day_location[0], dfmt='%Y-%m-%d') time = '{:{tfmt}}'.format(day_location[0], tfmt='%H:%M:%S') location = str(day_location[1][1]) + ',' + str(day_location[1][2]) return """https://api.darksky.net/forecast/{ACCESS_TOKEN}/{location},{date}T{time}?units=si""".format( location=location, date=day, ACCESS_TOKEN=settings.DARKSKY_ACCESS_TOKEN, time=time) def str_time(unix_time): if unix_time is None: return None else: return datetime.datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d %H:%M:%S') required_fields = [ "time", "timezone", "temperature", "apparentTemperature", "latitude", "longitude", "summary", "sunriseTime", "sunsetTime", "temperatureMin", "temperatureMinTime", "temperatureMax", "temperatureMaxTime", "windGust", "windSpeed" ] def get_today_and_location(location): now = datetime.datetime.today() date_and_location_set = set() date_and_location_set.add((now, location)) return date_and_location_set def get_weather_data(dates_and_locations): weather_data = [] for day_location in dates_and_locations: url = get_url(day_location) print('Getting data from {}'.format(url)) try: raw_data = json.loads(urllib.request.urlopen(url).read()) one_day_data = {key: value for key, value in raw_data["currently"].items( ) if key in required_fields} for required_field in required_fields: if required_field not in one_day_data: one_day_data[required_field] = None one_day_data['timezone'] = raw_data["timezone"] one_day_data['city'] = day_location[1][0] one_day_data['latitude'] = day_location[1][1] one_day_data['longitude'] = day_location[1][2] one_day_data['time'] = str_time(one_day_data['time']) one_day_data['sunriseTime'] = str_time( raw_data['daily']['data'][0]['sunriseTime']) one_day_data['sunsetTime'] = str_time( raw_data['daily']['data'][0]['sunsetTime']) one_day_data['temperatureMinTime'] = str_time( raw_data['daily']['data'][0]['temperatureMinTime']) one_day_data['temperatureMaxTime'] = str_time( raw_data['daily']['data'][0]['temperatureMaxTime']) weather_data.append(one_day_data) except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() print("Missing data in " + str(day_location)) traceback.print_exception( exc_type, exc_value, exc_traceback, file=sys.stdout) return weather_data def get_report(weather_data): data = weather_data[0] report = """The weather in <b>{city}</b> at <b>{time}</b><br> Today <b>{summary}, with {temperature}</b>.<br> The feel like is <b>{apparentTemperature}</b>.<br> Wind gust is <b>{windGust}, and speed is <b>{windSpeed}</b><br> """.format(city=data['city'], time=data['time'], summary=data['summary'], temperature=data['temperature'], apparentTemperature=data['apparentTemperature'], windGust=data['windGust'], windSpeed=data['windSpeed']) return report def get_html(weather_data): msg = MIMEMultipart('alternative') msg['Subject'] = settings.SUBJECT msg['From'] = settings.BOT_EMAIL msg['To'] = settings.TARGET_EMAIL html = """\ <html> <head></head> <body> <p> {body} </p> </body> </html> """.format(body=get_report(weather_data)) text = MIMEText(html, 'html') msg.attach(text) return msg def sendEmail(sender_email, sender_password, email_destination, html): try: smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() print("Successfully connected to gmail.") smtpObj.login(sender_email, sender_password) print("Logged In Successfully") print("Sending email...") smtpObj.sendmail(sender_email, email_destination, html.as_string()) print("Email sent at {time_stamp}".format( time_stamp=datetime.datetime.today().strftime('%H:%M:%S'))) smtpObj.quit() except: print("Fail to send email") def process(): print("Start process: {}".format(datetime.datetime.now())) date_time_and_location = get_today_and_location(settings.LOCATIONS) weather_data = get_weather_data(date_time_and_location) html = get_html(weather_data) sendEmail(settings.BOT_EMAIL, password, settings.TARGET_EMAIL, html) global is_sent is_sent = True password = input('enter password: -> ') is_sent = True if __name__ == '__main__': #schedule.every().day.at(settings.TIME_TO_SEND).do(process) #schedule.every(1).minute.do(process) #schedule.every(10).minutes.do(job) #schedule.every().hour.do(job) #schedule.every().day.at("10:30").do(job) #schedule.every().monday.do(job)f #schedule.every().wednesday.at("13:15").do(job) #schedule.every().minute.at(":17").do(job)ss #schedule.every(1).minute.do(process) schedule.every().day.at(settings.TIME_TO_SEND).do(process) try: while True: schedule.run_pending() time.sleep(1) if is_sent: print('\nNext process is: ' + datetime.datetime.strftime(schedule.next_run(),'%I:%M:%S%p')) is_sent = False except KeyboardInterrupt: print('interrupted!')
82de529b8a9a1faf53b3215723922e6a150460ff
[ "Markdown", "Python" ]
3
Python
pvikitset/Weather.Notifier
aa96314b7ab69218c9a93179de5506f37ad27ad9
c78ca4fae5239ca1887db384f45140d493bd9a41
refs/heads/master
<file_sep>const express = require('express'); const server = express(); server.use(express.json()); const projects = [ { id: 0, title: "Projeto 01", tasks: [] }, { id: 1, title: "Projeto 02", tasks: [] }, { id: 2, title: "Projeto 03", tasks: ["tarefa"] }, ] server.use((req, res, next) => { console.count(); return next(); }) function projectIdExists(req, res, next) { const { id } = req.params; const projectId = projects.find(project => project.id == id); if(!projectId){ return res.status(400).json({Message: 'Project does not exists'}); } return next(); } server.post('/projects', (req, res) => { const {id, title} = req.body; const newProject = { id, title, tasks: [] }; projects.push(newProject); return res.json(projects); }) server.get('/projects', (req, res) => { return res.json(projects); }) server.put('/projects/:id', projectIdExists, (req, res) => { const { id } = req.params; const { title } = req.body; const findIdInProject = projects.find(project => project.id == id); findIdInProject.title = title; return res.json(projects); }) server.delete('/projects/:id', projectIdExists, (req, res) => { const { id } = req.params; const findIdInProject = projects.find(project => project.id == id); projects.splice(findIdInProject, 1); return res.send(); }) server.post('/projects/:id/tasks', projectIdExists, (req, res) =>{ const { id } = req.params; const { title } = req.body; const projectId = projects.find(project => project.id == id); projectId.tasks.push(title); return res.json(projectId); }) server.listen(3000);
038fea4a8130a113b35f5d6703dbd73d39d0df05
[ "JavaScript" ]
1
JavaScript
Dessamgl/gostack_desafio01
f0382d1c2dbb3066a3f5bb43150164b71960b53f
c684a388a52b030c69b7d6510ce45097fa4ac27a
refs/heads/master
<repo_name>raniachouaieb/lumenapp<file_sep>/app/Http/Controllers/WorkersController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use App\Models\Worker; class WorkersController extends Controller { public function createWorker(Request $request){ $work = new Worker; $work->nom= $request->nom; $work->prenom= $request->prenom; $work->specialite= $request->specialite; $work->exp= $request->exp; $work->tel = $request->tel; $work->salaire= $request->salaire; $work->travail = $request->travail; $work->desc = $request->desc; $work->img = $request->img; $work->lieu = $request->lieu; $work->save(); return response()->json($work); } public function viewWorker($id){ $workers = Worker::find($id); return response()->json($workers); } public function getAll(){ $workers = Worker::all(); return response()->json($workers); } public function updateWorker(Request $request, $id){ $work = Worker::find($id); $work->nom = $request->input('nom'); $work->prenom = $request->input('prenom'); $work->specialite = $request->input('specialite'); $work->exp = $request->input('exp'); $work->tel = $request->input('tel'); $work->salaire = $request->input('salaire'); $work->travail = $request->input('travail'); $work->desc = $request->input('desc'); $work->img = $request->input('img'); $work->lieu = $request->input('lieu'); $work->save(); return response()->json($work); } }
258b8cd4abea4398d4ae77c088642da87230d356
[ "PHP" ]
1
PHP
raniachouaieb/lumenapp
dce2d2c16316e8171d8d62a4234d8808c029ec31
4b653b29bf421de268bc4735e0cbae457ee7e5b7
refs/heads/master
<repo_name>mulder3/kirchnerei-maven-plugins<file_sep>/decrypt-plugin/src/main/java/kirchnerei/decrypt/plugin/EncryptMojo.java /* * Copyright (c) 2014. Kirchner * web: http://www.kirchnerei.de * mail: <EMAIL> */ package kirchnerei.decrypt.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.StringUtils; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.cipher.PlexusCipher; import org.sonatype.plexus.components.cipher.PlexusCipherException; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; import java.io.File; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Properties; /** * @describe Lightweight mojo to decrypt project properties */ @Mojo(name = "process", defaultPhase = LifecyclePhase.INITIALIZE) public class EncryptMojo extends AbstractMojo { static final String SETTINGS_SECURITY_FILE = "settings-security.xml"; static final String MAVEN_HOME = "env.M2_HOME"; static final String USER_HOME = "user.home"; static final String M2 = ".m2"; private static final String PASSWORD_PLACEHOLDER = "\\{.*\\}"; private static boolean alreadyProcessed = false; private static Properties decodedProperties = new Properties(); @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; private PlexusCipher plexusCipher; @Override public void execute() throws MojoExecutionException, MojoFailureException { // if is the first time, load security settings file and process the project properties if (!alreadyProcessed) { try { logInfo("Starting to process project properties..."); final SettingsSecurity settingsSecurity = getSettingsSecurity(); final String plainTextMasterPassword = getPlexusCipher().decryptDecorated(settingsSecurity.getMaster(), DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION); final Properties projectProperties = this.getProject().getProperties(); final Enumeration keys = projectProperties.keys(); while (keys.hasMoreElements()) { final String key = (String) keys.nextElement(); final String value = (String) projectProperties.get(key); // if property matches the pattern {.*}, try to decode it if (value.matches(PASSWORD_PLACEHOLDER)) { logInfo(MessageFormat.format("Processing property with key [{0}]", key)); try { decodedProperties.setProperty(key, getPlexusCipher().decryptDecorated(value, plainTextMasterPassword)); } catch (final PlexusCipherException e) { // warn about errors when decrypting passwords, probably the master password is not the key for this one - skip logWarn("Error decoding password. It seams you cannot decrypt this one" + "with your master password, skipping..."); } } } logInfo("Finished processing project properties."); alreadyProcessed = true; } catch (final PlexusCipherException e) { logError("Error decoding master password.", e); throw new RuntimeException(MessageFormat.format("Failed to decode Master Password from {0}", SETTINGS_SECURITY_FILE), e); } catch (final SecDispatcherException e) { logError(MessageFormat.format("Error loading file {0}", SETTINGS_SECURITY_FILE), e); throw new RuntimeException(MessageFormat.format("Failed to load file {0}", SETTINGS_SECURITY_FILE), e); } } logInfo("Merging properties..."); this.getProject().getProperties().putAll(decodedProperties); } /** * Returns the {@link MavenSession} object * * @return mavenSession */ protected MavenSession getSession() { return session; } /** * Returns the {@link MavenProject} object * * @return mavenProject */ protected MavenProject getProject() { return project; } /** * Log info. * * @param message the message to log. */ protected void logInfo(final String message) { if (getLog().isInfoEnabled()) { getLog().info(message); } } /** * Log error. * * @param message the message. * @param e the exception. */ protected void logError(final String message, final Exception e) { if (getLog().isErrorEnabled()) { getLog().error(message, e); } } /** * Log warning. * * @param message the message. */ protected void logWarn(final String message) { if (getLog().isWarnEnabled()) { getLog().warn(message); } } /** * Returns the {@link org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity} object. * * @return settingsSecurity * @throws org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException */ protected SettingsSecurity getSettingsSecurity() throws SecDispatcherException { // load execution properties to lookup for settings-security paths Properties executionProperties = getSession().getExecutionProperties(); // try to load security-settings.xml from the system properties File securitySettings = getSettingsSecurityFile( executionProperties.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION)); if (securitySettings == null) { // try to load security-settings.xml from the user home path / .m2 securitySettings = getSettingsSecurityFile(MessageFormat.format("{0}{1}{2}", System.getProperty(USER_HOME), File.separator, M2)); if (securitySettings == null) { //try to load security-settings.xml from the maven home path / .m2 securitySettings = getSettingsSecurityFile( MessageFormat.format("{0}{1}{2}", executionProperties.getProperty(MAVEN_HOME), File.separator, M2)); } } // if file cannot be found we cannot proceed if (securitySettings == null) { throw new RuntimeException(MessageFormat.format("Failed to load file {0}", SETTINGS_SECURITY_FILE)); } // load SettingsSecurity Object return SecUtil.read(securitySettings.getAbsolutePath(), true); } /** * Returns the {@link File} for the specified path if exists, {@code null} otherwise. * * @param path the path for the file * @return file */ private File getSettingsSecurityFile(final String path) { File file = null; if (StringUtils.isNotBlank(path)) { // if path contains the file name load the file, otherwise try to load the file by it default name if (path.endsWith(".xml")) { logInfo(MessageFormat.format("Loading {0}", path)); file = new File(path); } else { logInfo(MessageFormat.format("Loading {0}{1}{2}", path, File.separator, SETTINGS_SECURITY_FILE)); final File folder = new File(path); file = new File(folder, SETTINGS_SECURITY_FILE); } if (!file.exists()) { file = null; } } return file; } protected PlexusCipher getPlexusCipher() throws PlexusCipherException { if (plexusCipher == null) { synchronized (EncryptMojo.class) { if (plexusCipher == null) { plexusCipher = new DefaultPlexusCipher(); } } } return plexusCipher; } } <file_sep>/buildnumber-plugin/pom.xml <!-- ~ Copyright (c) 2014. Kirchner ~ web: http://www.kirchnerei.de ~ mail: <EMAIL> --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>kirchnerei</groupId> <artifactId>kirchnerei-maven-plugins</artifactId> <version>1.0</version> </parent> <artifactId>kirchnerei-buildnumber-plugin</artifactId> <packaging>maven-plugin</packaging> <version>1.1</version> <name>Kirchnerei BuildNumber Plugin</name> <description> Kirchnerei BuildNumber Plugin (equals to ant buildnumber) </description> <url>https://github.com/mulder3/kirchnerei-maven-plugins.git</url> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-project</artifactId> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> </dependencies> </project> <file_sep>/decrypt-plugin/readme.md Kirchnerei &copy; 2014 # Kirchnerei Decrypt Plugin Decrypt all properties whose values ​​are encrypted with mvn -ep "password" ## Usage Edit the `pom.xml`: ... <build> ... <plugins> ... <plugin> <groupId>kirchnerei</groupId> <artifactId>kirchnerei-encrypt-plugin</artifactId> <version>1.0</version> <executions> <execution> <id>decode-passwords</id> <phase>initialize</phase> <goals> <goal>process</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... ## Repository Edit the `pom.xml`: ... <repositories> <repository> <id>kirchnerei-repository</id> <name>Public Repository on GitHub</name> <url>https://raw.github.com/mulder3/kirchnerei-maven-repository/master</url> <layout>default</layout> </repository> </repositories> ... # Note I was inspired by [<NAME>][mcmartins]. For my projects I have made ​​small adjustments. # License Copyright 2014 Kirchnerei 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. [mcmartins]: https://bitbucket.org/mcmartins/maven-plugins/wiki/DecodePasswordPlugin <file_sep>/readme.md kirchnerei &copy; 2014 # Kirchnerei Maven Plugins This is a collection of [Apache Maven][maven] plugins * Kirchnerei Decrypt Plugin: decrypt all properties whose values ​​are encrypted with mvn -ep "password". * Kirchnerei BuildNumber Plugin: Generates a build number in the same way as ant. # License Copyright 2014 Kirchnerei 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. [maven]: http://maven.apache.org "Apache Maven" <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2014. Kirchner ~ web: http://www.kirchnerei.de ~ mail: <EMAIL> --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>kirchnerei</groupId> <artifactId>kirchnerei-maven-plugins</artifactId> <version>1.0</version> <name>Kirchnerei Maven Plugins</name> <packaging>pom</packaging> <url>https://github.com/mulder3/kirchnerei-maven-plugins</url> <description> Parent artifact for Kirchnerei maven plugins </description> <prerequisites> <maven>3.0.0</maven> </prerequisites> <properties> <project.build.sourceEncoding>utf-8</project.build.sourceEncoding> <mavenVersion>2.2.1</mavenVersion> <mavenPluginPluginVersion>3.2</mavenPluginPluginVersion> <mavenFilteringVersion>1.1</mavenFilteringVersion> <local.maven.repository>github/kirchnerei-maven-repository</local.maven.repository> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-project</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-core</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-artifact</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-settings</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-monitor</artifactId> <version>${mavenVersion}</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <version>${mavenPluginPluginVersion}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.maven.shared</groupId> <artifactId>maven-filtering</artifactId> <version>${mavenFilteringVersion}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>${project.build.sourceEncoding}</encoding> <verbose>true</verbose> <optimize>true</optimize> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>${mavenPluginPluginVersion}</version> <configuration> <!-- see http://jira.codehaus.org/browse/MNG-5346 --> <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound> </configuration> <executions> <execution> <id>mojo-descriptor</id> <goals> <goal>descriptor</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <distributionManagement> <repository> <id>kirchnerei-maven-plugin-public</id> <name>Kirchnerei Repository</name> <url>file://${env.HOME}/${local.maven.repository}</url> </repository> </distributionManagement> <modules> <module>decrypt-plugin</module> <module>buildnumber-plugin</module> </modules> </project><file_sep>/buildnumber-plugin/readme.md # Kirchnerei Buildnumber Plugin Generates a build number in the same way as ant. # Usage **pom.xml** <build> <plugins> <plugin> <groupId>kirchnerei</groupId> <artifactId>buildnumber-plugin</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <phase>generate-resources</phase> <goals> <goal>create</goal> </goals> </execution> </executions> <configuration> <buildFile>build.properties</buildFile> <propertyName>buildnumber</propertyName> <outputDirectory>${basedir}</outputDirectory> <increment>true|false</increment> </configuration> </plugin> </plugins> </build> ## Configuration + buildFile: The name of the property file that store the build number + propertyName: The name of the property + increment (boolean): if the value is true, then it will increment the build number, otherwise it use without incremented. # License Copyright 2014 Kirchnerei 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. <file_sep>/buildnumber-plugin/src/main/java/kirchnerei/buildnumber/plugin/BuildNumberMojo.java /* * Copyright (c) 2014. Kirchner * web: http://www.kirchnerei.de * mail: <EMAIL> */ package kirchnerei.buildnumber.plugin; import org.apache.commons.lang.math.NumberUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; /** * Kirchnerei BuildNumber Plugin (equals to ant buildnumber) */ @Mojo(name = "create", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) public class BuildNumberMojo extends AbstractMojo { public static final String PROPERTY_COMMENT = "This is the build number. Do not change directly"; /** * Location of the file. */ @Parameter(defaultValue = "${basedir}", property = "outputDirectory", required = true) private File outputDirectory; /** * The name of the file. */ @Parameter(defaultValue = "build.properties", property = "buildFile") private String buildFile; /** * The name of the property value in which the buildnumber will be store. */ @Parameter(defaultValue = "buildnumber", property = "propertyName") private String propertyName; @Parameter(defaultValue = "false", property = "increment") private boolean increment; @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; public void execute() throws MojoExecutionException { try { File file = new File(outputDirectory, buildFile); int buildNumber = readBuildNumberFrom(file); if (buildNumber <= 0) { logInfo("create new build number with '1'"); buildNumber = 1; } else { buildNumber++; logInfo("build number '" + buildNumber + "' will be use"); } writeBuildNumberTo(file, buildNumber); Properties prop = project.getProperties(); prop.put(propertyName, String.valueOf(buildNumber)); } catch (IOException e) { logError("could not handle the build number", e); throw new MojoExecutionException("could not handle the build number", e); } } int readBuildNumberFrom(File file) throws IOException { if (!file.exists()) { return -1; } else { Properties prop = new Properties(); InputStream input = new FileInputStream(file); prop.load(input); input.close(); return NumberUtils.toInt(prop.getProperty(propertyName, "1"), 1); } } void writeBuildNumberTo(File file, int buildNumber) throws IOException { if (!increment) { logInfo("no increment the buildnumber."); return; } if (!file.exists()) { File parent = file.getParentFile(); parent.mkdirs(); file.createNewFile(); } logInfo("store the buildnumber"); OutputStream output = new FileOutputStream(file); Properties prop = new Properties(); prop.setProperty(propertyName, String.valueOf(buildNumber)); prop.store(output, PROPERTY_COMMENT); } /** * Log info. * * @param message the message to log. */ void logInfo(final String message) { if (getLog().isInfoEnabled()) { getLog().info(message); } } /** * Log error. * * @param message the message. * @param e the exception. */ protected void logError(final String message, final Exception e) { if (getLog().isErrorEnabled()) { getLog().error(message, e); } } }
f9655c7dcfec96973ea264c288a591fe1844d923
[ "Markdown", "Java", "Maven POM" ]
7
Java
mulder3/kirchnerei-maven-plugins
0edc430c13257d27411049b9ece600d37a3a81c2
2eb64d6e81ab72528c9d39f61499f3109803a258
refs/heads/master
<file_sep># timestamper Timesheet tracker in C++. Keep track of start, stop times for the day. Easy reporting for timesheet needs. I was dissapointed by the lack of timesheet appliations written in C++, so I decided to write my own for my personal use. <file_sep>#include <iostream> #include <fstream> #include <string> #include <cstring> #include <uuid/uuid.h> using namespace std; string DEFAULT_DATA_LOCATION = "data.csv"; /** Show all prints all timefiles @param file, path of csv file to open @return bool of success */ bool show_all(string file) { ifstream ip(file); if(!ip.is_open()) { cout << "ERROR: File Open" << '\n'; return false; } string uuid; string time_stamp; string project; string status; while(ip.good()) { getline(ip,uuid,','); if (uuid.empty()) { return false; } getline(ip,time_stamp,','); getline(ip, project, ','); getline(ip,status,'\n'); cout << "UUID: " << uuid << '\n'; cout << "time_stamp: " << time_stamp << '\n'; cout << "project: " << project << '\n'; cout << "status: " << status << '\n'; cout << "=========================" << '\n'; } ip.close(); return true; } /** Get uuid Gets a unique uuid @return string, uuid */ string get_uuid() { uuid_t id; uuid_generate(id); char *uuid_string = new char[100]; uuid_unparse(id, uuid_string); return uuid_string; } /** Enter Time csv 1) Prints out data that function recieved 2) Saves this data to the default csv file @param int unix_timestamp representing the current unix epoch time @param string project, current project @param int status, current status, 1 if start, 0 if stop @return bool of success */ bool enter_time_csv(int unix_timestamp, string project, int status) { string uuid = get_uuid(); cout << "==== New Entry ====" << endl; cout << "uuid: " << uuid << endl; cout << "timestamp: " << unix_timestamp << endl; cout << "status: " << status << endl; ofstream datafile; datafile.open(DEFAULT_DATA_LOCATION, ios::app); datafile << uuid << "," << unix_timestamp << "," << project << "," << status << endl; datafile.close(); return true; } /** change status Gets current time in unix Epoch time and sends this result with project and status to enter_time_csv. @param string project @param int status, current status, 1 if start, 0 if stop @return bool of success */ bool change_status(string project, int status) { time_t result = time(nullptr); asctime(localtime(&result)); result = enter_time_csv(result,project,status); return result; } /** @TODO */ bool edit_time_csv() { } /** Main Handles arguments sent into timestamper */ int main(int argc, char** argv) { if (argc > 1) { if (!strcmp(argv[1], "show")) { if (argc > 2) { // show all if (!strcmp(argv[2], "all")) { show_all(DEFAULT_DATA_LOCATION); } // show day else if(!strcmp(argv[2], "day")) { cout << "show day" << endl; } // show timestamp timestamp } else { cout << "show timestamp timestamp" << endl; } } else if (!strcmp(argv[1], "start")) { if (argc > 2) { change_status(argv[2], 1); } else { cout << "please enter project" << endl; return -1; } } else if (!strcmp(argv[1], "stop")) { if (argc > 2) { change_status(argv[2], 0); } else { cout << "please enter project" << endl; return -1; } } } else { cout << "show today" << endl; } return 0; }
a358836cf81d2105112d09789c4c919d9e696c84
[ "Markdown", "C++" ]
2
Markdown
userWayneCampbell/timestamper
29fefd881192a8c48c4177a122335c7e32b8372d
8bc4f468a9d99d41416b35646e393969cca13180
refs/heads/master
<file_sep>const { expect, assert } = require("chai"); const { ethers } = require("hardhat"); let lottery; let owner; let players; beforeEach(async () => { let accounts = await ethers.getSigners(); owner = accounts[0]; players = accounts.splice(1, 20); const Lottery = await ethers.getContractFactory("Lottery"); lottery = await Lottery.deploy(); }); describe("Lottery", () => { /** Tests if lottery is deployed by checking if it defined */ it("Deploy", () => { assert.isDefined(lottery); }); /** Tests if we can get the manager and if it is equal to the contract owner */ it("Get manager", async () => { let manager = await lottery.manager(); assert.equal(manager, owner.address); }); /** Tests if we can enter the lottery above the minumum amount */ it("Can enter with > 0.01 ETH", async () => { expect( await lottery .connect(players[0]) .enter({ value: ethers.utils.parseEther("0.011") }) ).to.be.ok; }); /** Tests if we cannot enter with less that the required amount */ it("Can't enter with <= 0.01 ETH", async () => { await expect( lottery .connect(players[0]) .enter({ value: ethers.utils.parseEther("0.01") }) ).to.be.revertedWith("Minimum value is 0.01 ETH"); }); /** Tests if we can enter and the correct player is stored in the contract */ it("Add and retrieve 1 player", async () => { await lottery .connect(players[0]) .enter({ value: ethers.utils.parseEther("0.011") }); let retrievedPlayer = await lottery.players(0); assert.equal(retrievedPlayer, players[0].address); }); /** Tests if we can add and retrieve multiple players */ it("Add and retrieve multiple players", async () => { let playersToEnter = [players[0], players[1]]; for (let player of playersToEnter) { await lottery .connect(player) .enter({ value: ethers.utils.parseEther("0.011") }); } let retrievedPlayers = await lottery.getPlayers(); assert.equal(2, retrievedPlayers.length); for (let i = 0; i < retrievedPlayers.length; i++) { assert.equal(retrievedPlayers[i], playersToEnter[i].address); } }); /** Tests if the random number returns an object */ it("Random number", async () => { assert.isObject(await lottery.random()); // returns object because JavaScript casts a large number to BigNumber }); /** Tests if the manager can pick a winner */ it("Manager picks winner", async () => { await lottery.enter({ value: ethers.utils.parseEther("0.011") }); assert.isDefined(await lottery.pickWinner()); }); /** Tests if the player cannot pick a winner */ it("Player cannot pick winner", async () => { await lottery.enter({ value: ethers.utils.parseEther("0.011") }); await expect(lottery.connect(players[0]).pickWinner()).to.be.revertedWith( "Only the manager can do this" ); }); /** Tests if the player array is empty after picking winner */ it("Players array reset after picking winner", async () => { await lottery.enter({ value: ethers.utils.parseEther("0.011") }); assert.isDefined(await lottery.pickWinner()); assert.equal(0, (await lottery.getPlayers()).length); }); /** Tests if the winner gets all funds */ it("Winner gets all funds", async () => { const initialBalance = await owner.getBalance(); await lottery.enter({ value: ethers.utils.parseEther("1") }); // We spend a bit more than 1 ETH, due to mining fees assert.isTrue( initialBalance - (await owner.getBalance()) > ethers.utils.parseEther("1") ); await lottery.pickWinner(); // We have a bit less ETH in the end due to mining fees assert.isTrue( initialBalance - (await owner.getBalance()) < ethers.utils.parseEther("0.001") ); }); });
69b3bc92085fe916143cb7906ec4869360f76028
[ "JavaScript" ]
1
JavaScript
bufo24/solidity-lottery
0826204ce56350eda7b892d9628ada29b3bd09a1
70b103a780cd78708014c4ea5d9187c9775d382c
refs/heads/main
<file_sep># oct-classification <file_sep>import argparse import os import numpy as np import pandas as pd from PIL import Image from skorch import NeuralNetClassifier from skorch.callbacks import LRScheduler, Checkpoint, EpochScoring, EarlyStopping from skorch.helper import predefined_split import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, WeightedRandomSampler from torchvision import models, transforms class OCTDataset(Dataset): def __init__(self, csv_path, transform): self.df = pd.read_csv(csv_path) self.transform = transform self.class2index = {'NORMAL':0, 'DRUSEN':1, 'CNV':2, 'DME':3} self.labels = np.vectorize(self.class2index.get)(np.array(self.df.loc[:, 'annotation'])) self.samples = np.array(self.df.loc[:, 'filepath']) def __len__(self): return len(self.df) def __getitem__(self, index): filepath = self.df.iloc[index]['filepath'] label = self.class2index[self.df.iloc[index]['annotation']] image = Image.open(filepath).convert('RGB') image = self.transform(image) return image, label class PretrainedModel(nn.Module): def __init__(self, output_features): super().__init__() model = models.resnet18(pretrained=True) num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, output_features) self.model = model def forward(self, x): return self.model(x) def set_device(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device == 'cuda': torch.cuda.empty_cache() print(f'device: {device}') print() return device def prepare_data(args): image_size = (args.image_size,args.image_size) train_transforms = transforms.Compose([transforms.Resize(image_size), transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), transforms.RandomRotation(45), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]) test_transforms = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]) if args.random_flips: train_data = OCTDataset(os.path.join(args.input_dir, 'training.csv'), train_transforms) else: train_data = OCTDataset(os.path.join(args.input_dir, 'training.csv'), test_transforms) val_data = OCTDataset(os.path.join(args.input_dir, 'validation.csv'), test_transforms) test_data = OCTDataset(os.path.join(args.input_dir, 'testing.csv'), test_transforms) return train_data, val_data, test_data def configure_callbacks(stop_early, output_dir): f_params = os.path.join(output_dir, 'model.pt') f_history = os.path.join(output_dir, 'history.json') checkpoint = Checkpoint(monitor='valid_loss_best', f_params=f_params, f_history=f_history, f_optimizer=None, f_criterion=None) train_acc = EpochScoring(scoring='accuracy', on_train=True, name='train_acc', lower_is_better=False) if stop_early: early_stopping = EarlyStopping() callbacks = [checkpoint, train_acc, early_stopping] else: callbacks = [checkpoint, train_acc] return callbacks def configure_sampler(train_data, weight_samples): if weight_samples: labels = train_data.labels normal_weight = 1 / len(labels[labels == 0]) drusen_weight = 1 / len(labels[labels == 1]) cnv_weight = 1 / len(labels[labels == 2]) dme_weight = 1 / len(labels[labels == 3]) sample_weights = np.array([normal_weight, drusen_weight, cnv_weight, dme_weight]) weights = sample_weights[labels] sampler = WeightedRandomSampler(weights, len(train_data), replacement=True) else: sampler = None return sampler def train(train_data, val_data, args): device = set_device() sampler = configure_sampler(train_data, args.weight_samples) callbacks = configure_callbacks(args.stop_early, args.output_dir) print('Training...') net = NeuralNetClassifier(PretrainedModel, criterion=nn.CrossEntropyLoss, lr=args.learning_rate, batch_size=args.batch_size, max_epochs=args.num_epochs, module__output_features=args.num_classes, optimizer=optim.SGD, optimizer__momentum=0.9, iterator_train__num_workers=args.num_workers, iterator_train__sampler=sampler, iterator_train__shuffle=True if sampler == None else False, iterator_valid__shuffle=False, iterator_valid__num_workers=args.num_workers, train_split=predefined_split(val_data), callbacks=callbacks, device=device) net.fit(train_data, y=None) return net def test(net, data, args): print() print('Testing...') probs = net.predict_proba(data) img_locs = test_data.samples csv_data = {'img_loc': img_locs, 'NORMAL': probs[:,0], 'DRUSEN': probs[:,1], 'CNV': probs[:,2], 'DME': probs[:,3]} csv_name = os.path.join(args.output_dir, 'probability.csv') pd.DataFrame(data=csv_data).to_csv(csv_name, index=False) print(f'Done. Outputs written to: {csv_name}') print() def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--batch_size', type=int, default=32) parser.add_argument('--learning_rate', type=float, default=0.001) parser.add_argument('--image_size', type=int, default=224) parser.add_argument('--input_dir', type=str, default='./data') parser.add_argument('--num_classes', type=int, default=4) parser.add_argument('--num_epochs', type=int, default=50) parser.add_argument('--num_workers', type=int, default=0) parser.add_argument('--output_dir', type=str, default='./') parser.add_argument('--pretrained', type=bool, default=True) parser.add_argument('--random_flips', type=bool, default=True) parser.add_argument('--stop_early', type=bool, default=True) parser.add_argument('--weight_samples', type=bool, default=True) return parser.parse_args() if __name__ == '__main__': torch.multiprocessing.set_sharing_strategy('file_system') args = parse_args() print() for arg in vars(args): print(f'{arg}: {getattr(args, arg)}') train_data, val_data, test_data = prepare_data(args) net = train(train_data, val_data, args) test(net, test_data, args) <file_sep>library(groupdata2) library(tidyverse) library(tools) library(utils) relative_path <- file.path('data', 'images') all_data <- list.files(relative_path) %>% as.data.frame() %>% rename(filepath = '.') %>% separate(filepath, c('annotation', 'studyinstanceuid', 'image_number', 'ext'), remove = FALSE) %>% mutate(across(c('studyinstanceuid', 'annotation'), as.factor), filepath = file.path(relative_path, filepath)) %>% select(filepath, studyinstanceuid, annotation) set.seed(1337) partitioned_data <- all_data %>% partition(p = c(0.7, 0.1), id_col = 'studyinstanceuid') train_data <- partitioned_data[[1]] %>% select(filepath, studyinstanceuid, annotation) val_data <- partitioned_data[[2]] %>% select(filepath, studyinstanceuid, annotation) test_data <- partitioned_data[[3]] %>% select(filepath, studyinstanceuid, annotation) write_csv(train_data, './data/training.csv') write_csv(val_data, './data/validation.csv') write_csv(test_data, './data/testing.csv')
c09e5daa1804265b1a458c6d2d3916fd2b7e5f21
[ "Markdown", "Python", "R" ]
3
Markdown
aaroncoyner/oct-classification
5934253d4301b2b9b5a0be87d7893c29c79e05c9
037e27eed2c7d867448d4ea388f3f8add693c289
refs/heads/master
<file_sep>package tk.okou.hls; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.AsyncFile; import io.vertx.core.file.FileSystem; import io.vertx.core.file.OpenOptions; import io.vertx.ext.web.client.HttpRequest; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.ext.web.codec.BodyCodec; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class HLSDownloaderVerticle extends AbstractVerticle { int size = 0; private String name = "小镇车神"; private String output = "H:\\okou\\movie"; private OpenOptions options = new OpenOptions(); @Override public void start() { String outputPath = output + "\\" + name; File f = new File(outputPath); if (!f.exists()) { boolean mkdirs = f.mkdirs(); if (!mkdirs) { throw new RuntimeException("创建目录[" + outputPath + "]失败"); } } String m3u8Url = "https://bilibili.com-h-bilibili.com/20190412/8400_030d1cfc/1000k/hls/index.m3u8"; String baseUrl = m3u8Url.substring(0, m3u8Url.lastIndexOf("/") + 1); System.err.println(baseUrl); WebClientOptions options = new WebClientOptions(); options.setTrustAll(true); options.setMaxPoolSize(100); WebClient client = WebClient.create(vertx, options); HttpRequest<Buffer> request = client.getAbs(m3u8Url); request.as(BodyCodec.string()).send(r -> { if (r.failed()) { r.cause().printStackTrace(); } else { String result = r.result().body(); String[] strs = result.split("\n"); List<String> list = Stream.of(strs).filter(line -> !line.startsWith("#") && line.endsWith(".ts")).collect(Collectors.toList()); this.size = list.size(); System.out.println("需要下载资源数:" + this.size + ""); List<Future> futures = new ArrayList<>(this.size); for (int i = 0; i < list.size(); i++) { String url = baseUrl + list.get(i); try { Future<Void> future = Future.future(); request(client, url, outputPath + "\\" + name + i + ".ts", future); futures.add(future); } catch (IOException e) { e.printStackTrace(); } } CompositeFuture.all(futures).setHandler(cr -> { if (cr.failed()) { cr.cause().printStackTrace(); } else { System.out.println("下载结束,开始合并文件"); String finalName = output + "\\" + name + ".mp4"; vertx.fileSystem().open(finalName, this.options, r3 -> { if (r3.failed()) { System.err.println("打开文件[" + finalName + "]失败!"); } else { AsyncFile af = r3.result(); Future<Void> f1 = Future.future(); compose(af, outputPath, 0, f1); f1.setHandler(r2 -> { if (r2.failed()) { System.err.println("合并失败"); r2.cause().printStackTrace(); } else { System.out.println("合并文件结束"); vertx.close(); } }); } }); } }); } }); } private void compose(AsyncFile asyncFile, String outputPath, int currentIndex, Future<Void> future) { if (currentIndex == this.size) { future.complete(); return; } System.out.println("合并第:" + currentIndex + "个文件"); String fileName = outputPath + "\\" + name + currentIndex + ".ts"; FileSystem fs = vertx.fileSystem(); fs.open(fileName, options, r -> { if (r.failed()) { future.fail(r.cause()); } else { r.result().pipe().endOnSuccess(false).to(asyncFile, ar -> { if (ar.failed()) { future.fail(ar.cause()); } else { compose(asyncFile, outputPath, currentIndex + 1, future); } }); } }); } private void request(WebClient client, String url, String fileName, Future<Void> future) throws IOException { request(client, url, fileName, future, 5); } private void retry(WebClient client, String url, String fileName, Future<Void> future, Throwable e, int retryNum) { if (retryNum == 0) { future.fail(e); } else { request(client, url, fileName, future, retryNum - 1); } } private void request(WebClient client, String url, String fileName, Future<Void> future, int retryNum) { client.getAbs(url).send(r -> { if (r.failed()) { retry(client, url, fileName, future, r.cause(), retryNum); } else { Buffer buffer = r.result().body(); vertx.fileSystem().writeFile(fileName, buffer, r1 -> { if (r1.failed()) { retry(client, url, fileName, future, r1.cause(), retryNum); } else { future.complete(); System.out.println("下载:" + fileName + "成功"); } }); } }); } public static void main(String[] args) { System.setProperty("vertx.disableDnsResolver", "true"); Launcher.main(new String[]{"run", HLSDownloaderVerticle.class.getName()}); } }
925c3378903c9709b5af720134fd385f1fdf9ee9
[ "Java" ]
1
Java
okou19900722/hls-downloader
da963e1b7864f2d9cd48a7c3abb0ce0d4536c827
04c82d761b907dc751c5782a523e7e16eadde16c
refs/heads/master
<repo_name>oggnik/project-euler<file_sep>/Problem 9/euler9.rb sum = 1000 for i in 1..sum for j in i..sum if (i**2 + j**2 > (sum-i-j)**2) break end if (i**2 + j**2 == (sum-i-j)**2) puts "#{i} #{j} #{(sum-i-j)}" puts "product: #{i*j*(sum-i-j)}" exit end end end <file_sep>/cleanup.rb #!/usr/bin/ruby require 'fileutils' #get the files files = Dir["*"] files.map do |name| #this matches names starting with a euler[number]. match = /euler(?<number>\d+)\..+/.match(name) if (match) #the number is stored in MatchData[:number] number = match[:number] path = "Problem " + number + "/" + name FileUtils.mkdir_p(File.dirname(path)) FileUtils.mv(name, path) end end <file_sep>/Problem 5/euler5.rb #result = 10*4*7*9 result = 19*17*13*11*7*5*(3**2)*(2**4) puts result <file_sep>/Problem 7/euler7.rb def isPrime(num) for i in 2..Math.sqrt(num) if (num % i == 0) return false end end return true end numPrimes = 1 lastNum = 2 while numPrimes < 10001 lastNum += 1 if (isPrime(lastNum)) numPrimes += 1 end end puts lastNum <file_sep>/Problem 6/euler6.rb sum = 0 square = 0 for i in 1..100 sum += i**2; square += i end square **= 2 puts square - sum <file_sep>/Problem 4/euler4.rb arr = [] for i in 999.downto(100) for j in 999.downto(100) num = i * j num_string = num.to_s if num_string == num_string.reverse arr.push(num) end end end puts arr.max <file_sep>/Problem 10/euler10.rb max = 2000000 #max = 10 #create array of booleans to show which are true primes = Array.new(max + 1, true) index = 2 while (index < max) if (primes[index]) (2*index..max+1).step(index).map do |i| primes[i] = false end end index += 1 end sum = 0 primes.drop(2).each_with_index do |n, i| if (n) sum += i+2 end end puts primes.inspect puts sum <file_sep>/Problem 3/euler3.py num = 600851475143 #num = 10 for i in range(int(num ** .5), 0, -1): if (num % i == 0): isPrime = True for j in range(2, i): if (i % j == 0): isPrime = False if (isPrime): print(i) <file_sep>/Problem 2/euler2.py sum = 0 prev = 1 current = 2 while current < 4000000: if (current % 2 == 0): sum += current next = current + prev prev = current current = next print(sum)
d9c7b5d7164c05ff55e55a762bdc9802b423373a
[ "Python", "Ruby" ]
9
Ruby
oggnik/project-euler
69234a002ca765d5573e4b1cea02e8b8830d5ae6
2b63b5185b6e62cf2a7e3ba538df63ef44dd851f
refs/heads/master
<repo_name>Zuzzuc/dbmod<file_sep>/dbmod.sh #!/bin/bash # License: The MIT License (MIT) # Author Zuzzuc https://github.com/Zuzzuc/ # # This script is used to modify databases. set -f # Note that noglob is active! Some regex operations might not work as intented. # Exit codes # 1=Unknown operation # 2=No db path supplied # Basic functions sanitizeFilePath(){ # Usage is $1, where $1 is the text to sanitize. echo "$1" | sed 's%\\%%g' | sed -e 's%[[:space:]]*$%%' } stripFromStringBeginning(){ #Usage is $1 and $2, where $1 is the string to modify and $2 is the number of chars to remove echo "$1" | sed -E "s/^.{$2}//" } turnToUpperCase(){ #Usage is $1, where $1 is the string to be converted to uppercase. echo "$1" | tr '[:lower:]' '[:upper:]' } # Pre exec var set if [ "$1" != "" ];then db="$(sanitizeFilePath "$1")" if [ ! -f "$db" ];then touch "$db" fi shift # We dont need to use it anymore else exit 2 fi # Advanced functions unsetAll(){ # Unsets all commonly used variables. This is good to use if running this script inline. unset cols unset vals unset count unset dbexec unset modifier unset table } executeCustomQuery(){ # Usage is $1, where $1 is the custom query to execute. # This assumes the database path is already set in $db sqlite3 "$db" "$1" } createTable(){ #Usage is $@, where $1 is the table name and each following arg is an column name(eg (id INTEGER PRIMARY KEY, f TEXT or l TEXT) # This assumes the database path is already set in $db # NOTE: This will format the input, since it is known to be columns. table="$1" && shift for i in "$@"; do if [ "$1" != "" ]; then dbexec+=",$1" shift fi done dbexec="$(stripFromStringBeginning "$dbexec" "1")" sqlite3 "$db" "CREATE TABLE $table ($dbexec);" } insert(){ # Usage is $@, where $1 is the table name and the remaining variables are the column names and values, in that order. # This assumes the database path is already set in $db # NOTE: This will format the input. It will shift past the table name, and will take the first half of the remaining arguments as column names, and the rest as values. table="$1" && shift count=0 breaktime=$((${#@}/2)) while [ $count -lt $breaktime ];do cols+=",$1" count=$(($count+1)) shift done cols="$(stripFromStringBeginning "$cols" "1")" count=0 while [ $count -lt $breaktime ];do vals+=",'$1'" count=$(($count+1)) shift done vals="$(stripFromStringBeginning "$vals" "1")" sqlite3 "$db" "INSERT INTO $table ($cols) VALUES ($vals);" } get(){ # Usage is $@, where $1 is the table, the following are conditions and its values and the rest is columns.. # This means an example with the usage of where and or could look like this: ## get "table" "WHERE" "id=5" "AND" "FirstName='Adam'" "*" ### This will output all data from the user Adam if he has id 5. table="$1" && shift break=1 while [ $break -ne 0 ];do if [ "$(turnToUpperCase "$1")" == "WHERE" ] || [ "$(turnToUpperCase "$1")" == "AND" ] || [ "$(turnToUpperCase "$1")" == "OR" ] || [ "$(turnToUpperCase "$1")" == "LIKE" ] ||[ "$(turnToUpperCase "$1")" == "WHERE NOT" ] || [ "$(turnToUpperCase "$1")" == "AND NOT" ] || [ "$(turnToUpperCase "$1")" == "OR NOT" ] || [ "$(turnToUpperCase "$1")" == "NOT LIKE" ];then modifier+="$1 $2 " shift && shift # Make it so if it is 'IN', require next one to be fully prefixed, eg "('Kalmar', 'Uppsala')" elif [ "$(turnToUpperCase "$1")" == "IN" ];then modifier+="$1 $2 " shift && shift else break=0 fi done for i in "$@"; do if [ "$1" != "" ]; then cols+=",$1" shift fi done cols="$(stripFromStringBeginning "$cols" "1")" sqlite3 "$db" "SELECT $cols FROM $table $modifier;" } update(){ # Usage is $@, where $1 is the table, the following are conditions and its values and the rest is columns. table="$1" && shift break=1 while [ $break -ne 0 ];do if [ "$(turnToUpperCase "$1")" == "WHERE" ] || [ "$(turnToUpperCase "$1")" == "AND" ] || [ "$(turnToUpperCase "$1")" == "OR" ] || [ "$(turnToUpperCase "$1")" == "LIKE" ] ||[ "$(turnToUpperCase "$1")" == "WHERE NOT" ] || [ "$(turnToUpperCase "$1")" == "AND NOT" ] || [ "$(turnToUpperCase "$1")" == "OR NOT" ] || [ "$(turnToUpperCase "$1")" == "NOT LIKE" ];then modifier+="$1 $2 " shift && shift # Make it so if it is 'IN', require next one to be fully prefixed, eg "('Kalmar', 'Uppsala')" elif [ "$(turnToUpperCase "$1")" == "IN" ];then modifier+="$1 $2 " shift && shift else break=0 fi done for i in "$@"; do if [ "$1" != "" ]; then vals+=",$1" shift fi done vals="$(stripFromStringBeginning "$vals" "1")" sqlite3 "$db" "UPDATE $table SET $vals $modifier;" } prune(){ # Usage is $1, where $1 is the table to drop. sqlite3 "$db" "DROP TABLE $1;" } delete(){ # Usage is $@, where $1 is the table, the following are conditions and its values. table="$1" && shift break=1 while [ $break -ne 0 ];do if [ "$(turnToUpperCase "$1")" == "WHERE" ] || [ "$(turnToUpperCase "$1")" == "AND" ] || [ "$(turnToUpperCase "$1")" == "OR" ] || [ "$(turnToUpperCase "$1")" == "LIKE" ] ||[ "$(turnToUpperCase "$1")" == "WHERE NOT" ] || [ "$(turnToUpperCase "$1")" == "AND NOT" ] || [ "$(turnToUpperCase "$1")" == "OR NOT" ] || [ "$(turnToUpperCase "$1")" == "NOT LIKE" ];then modifier+="$1 $2 " shift && shift elif [ "$(turnToUpperCase "$1")" == "IN" ];then modifier+="$1 $2 " shift && shift else break=0 fi done echo will exec "$db" "DELETE FROM $table $modifier;" sqlite3 "$db" "DELETE FROM $table $modifier;" } getTableInfo(){ # Usage is $1, where $1 is the table to look up sqlite3 "$db" "PRAGMA table_info($1);" } getTables(){ # No input. # Note that the output will be whitespace separerad. sqlite3 "$db" ".tables" } # main if [ "$1" == "get" ] || [ "$1" == "update" ] || [ "$1" == "insert" ] || [ "$1" == "createTable" ] || [ "$1" == "delete" ] || [ "$1" == "prune" ] || [ "$1" == "getTables" ] || [ "$1" == "getTableInfo" ] || [ "$1" == "executeCustomQuery" ];then "$@" unsetAll else echo "'$1' is not a function" exit 1 fi<file_sep>/README.md # dbmod Database modification script <br> <br> A lightweight, fast executing script, used to modify sql (sqlite3) databases. <br><br> Not compatible with any database format other than sqlite3. # Usage ## get ### Will read from selected column Syntax is the following: `get table modifier1 modifier-value1 modifierN modifier-valueN column1 columnN` Where modifier is any of the following: WHERE, AND, OR, IN, LIKE and their corresponding NOT(such as WHERE NOT) Where modifier-value is a declaration of a variable, such as `LastName='Smith'` Note: If using the modifier "IN", make sure to correctly format the values as this script will not do it in this case. #### Examples Return all information about the user with id 5, if his name is Adam.<br> `dbmod.sh "database.db" "get" "myTable" "WHERE" "id=5" "AND" "FirstName='Adam'" "*"`<br><br> Return only id and lastname from any user named Ethan.<br> `dbmod.sh "database.db" "get" "myTable" "WHERE" "FirstName='Ethan'" "id" "LastName"`<br><br> Return all information about an entry where firstname equals George and id is between 1 and 4, or equals 21.(Don't forget to format the input for IN as this is one of few cases when it's not done within the script itself)<br> `dbmod.sh "database.db" "get" "myTable" "WHERE" "FirstName='George'" "AND" "id" "IN" "('1','2','3','4','21')" "*"`<br><br> ## insert ### Will insert value(s) into column. Syntax is the following: `insert Table column1 column2 columnN value1 value2 valueN`<br><br> #### Example Create a new entry containing address, first and lastname.<br> `dbmod.sh "database.db" "insert" "myTable" "FirstName" "LastName" "Address" "John" "Smith" "387 6th Ave"`<br><br> ## update ### Will update information. Syntax is the following: `update table modifier1 modifier-value1 modifier2 modifier-value2 modifierN modifier-valueN column1 column2 columnN value1 value2 valueN` Where modifier is any of the following: WHERE, AND, OR, IN, LIKE and their corresponding NOT(such as WHERE NOT) Where modifier-value is a declaration of a variable, such as `LastName='Smith'` #### Example Change username of a user with id 233 to 'Example'<br> `dbmod.sh "database.db" "update" "myTable" "WHERE" "id=233" "Username='Example'"`<br><br> ## delete ### Deletes specified information Syntax is the following: `delete table modifier1 modifier-value1 modifier2 modifier-value2 modifierN modifier-valueN` Where modifier is any of the following: WHERE, AND, OR, IN, LIKE and their corresponding NOT(such as WHERE NOT) Where modifier-value is a declaration of a variable, such as `LastName='Smith'` #### Examples Remove any entry where id equals 7.<br> `dbmod.sh "database.db" "delete" "myTable" "WHERE" "id=7"`<br><br> Remove any entry where first name equals John and last name equal Smith.<br> `dbmod.sh "database.db" "delete" "myTable" "WHERE" "FirstName='John'" "AND" "LastName='Smith'"`<br><br> ## createTable ### Creates table with given attributes Syntax is the following: `createTable table "column1 datatype" "column2 datatype" "columnN datatype"` #### Example Create a table named 'Customers' with three columns: id(primary key), last and first name. <br> `dbmod.sh "database.db" "createTable" "Customers" "id INTEGER PRIMARY KEY" "FirstName TEXT" "LastName TEXT"`<br><br> ## prune ### drops specified table Syntax is the following: `prune table` #### Example Drop the table Customers<br> `dbmod.sh "database.db" "prune" "Customers"`<br><br> ## executeCustomQuery ### Will execute any query given. Syntax should be formatted for sqlite3 #### Example List everything from Customers<br> `dbmod.sh "database.db" "executeCustomQuery" "SELECT * FROM myTable"`<br><br> ## getTables ### lists tables in database This function uses no input (other than database path)<br> Lists all tables in database whitespace separated. #### Example Get tables from database.db<br> `dbmod.sh "database.db" "getTables"`<br><br> ## getTableInfo ### lists information about specified table Syntax is the following: `getTableInfo table`<br> Lists information about all columns in an table. #### Examples Get info about the table myTable<br> `dbmod.sh "database.db" "getTableInfo" "myTable"`<br><br> # Exit codes <br> 0: Everything went well<br> 1: Unknown function called in $2<br> 2: No database path supplied<br>
016767bf677feb0720e7c49d3ea2ff26942364c5
[ "Markdown", "Shell" ]
2
Shell
Zuzzuc/dbmod
cfbd453cf8d884c2fd887cde5eda26c051f86769
3fcb2cf540130bdf6539484ce0748abb83017dae
refs/heads/master
<file_sep>import React from 'react' ; import "./App.css"; function Hello({name,msg}){ return( <div className="Hello"> <h1>This is the hello component</h1> <h3>{msg}</h3> <h2> {name} </h2> </div> ); } export default Hello;<file_sep>import React, {useState, useEffect} from "react" ; //import usestate hook import "./App.css"; import Hello from './sayhello'; function App(){ const[counter,setCounter]=useState(0); useEffect(()=>{ alert("number of clicks :" +counter); }); function increment(){ setCounter(counter+1); } return( <div> <p> {counter}</p> <button onClick = {increment}> increment</button> </div> ) } // function App(){ // // const [users,setUser] = useState([ // // {name:'Ed', msg:"hello there"}, // // {name:'Ed2', msg:"Hi"}, // // {name:'Ed3', msg:"hello"} // ]); // return( //inside part is actualy javascript(JSX) but this converts into html when exporting. // <div className="app"> // {users.map(user =>( // <Hello name={users.name} msg={users.msg}/> // ))} // </div> // ); // } export default App; //export the file
6ffe494a987893d070f50b33e20e5cde79248edc
[ "JavaScript" ]
2
JavaScript
Tharanidk/increment_numbers
f1e13710f165d3113b68c79b3d067f992cabb30d
72e93948338559965644d863527dad79c9f287a2
refs/heads/master
<file_sep>FROM alpine RUN apk add --no-cache ca-certificates curl RUN curl -Lo /usr/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v1.19.4/bin/linux/amd64/kubectl && \ chmod +x /usr/bin/kubectl ADD ./drone-kubectl /usr/bin/ ENTRYPOINT ["/usr/bin/drone-kubectl"] <file_sep># drone-kubectl Drone plugin for easier use of kubectl in your pipelines. _This work is based on the previous KubeCI/kubectl plugin._ ## Build Build the binary with the following commands: ``` go build -v ./cmd/drone-kubectl ``` ## Docker Build the Docker image with the following commands: ``` docker build --rm -t metalmatze/drone-kubectl . ``` ## Usage Execute from the working directory: ``` docker run --rm \ -e PLUGIN_NAMESPACE=drone \ -e PLUGIN_KUBECTL='get pods' \ -v $(pwd):$(pwd) \ -w $(pwd) \ metalmatze/drone-kubectl ``` <file_sep>package main import ( "bytes" "context" "encoding/base64" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "text/template" "time" "unicode/utf8" "github.com/joho/godotenv" "github.com/pinzolo/casee" "github.com/pkg/errors" "github.com/urfave/cli" ) const ( binary = "kubectl" dryRunFlag = "dry-run" dryRunEnvVar = "PLUGIN_DRY_RUN,DRY_RUN" filesFlag = "files" filesEnvVar = "PLUGIN_FILES,FILES" kubectlFlag = "kubectl" kubectlEnvVar = "PLUGIN_KUBECTL,KUBECTL" kubeconfigFlag = "kubeconfig" kubeconfigEnvVar = "PLUGIN_KUBECONFIG,KUBECONFIG" namespaceFlag = "namespace" namespaceEnvVar = "PLUGIN_NAMESPACE,NAMESPACE" templatesFlag = "templates" templatesEnvVar = "PLUGIN_TEMPLATES,TEMPLATES" debugFlag = "debug" debugEnvVar = "PLUGIN_DEBUG,DEBUG" ) func main() { // Load env-file if it exists first if env := os.Getenv("PLUGIN_ENV_FILE"); env != "" { _ = godotenv.Load(env) } app := cli.NewApp() app.Name = "Drone kubectl" app.Usage = "Run kubectl in your pipeline" app.Action = run app.Version = "0.3.0" app.Flags = []cli.Flag{ cli.BoolFlag{ Name: dryRunFlag, EnvVar: dryRunEnvVar, Usage: "don't actually call kubectl", }, cli.StringSliceFlag{ Name: filesFlag, EnvVar: filesEnvVar, Usage: "the files to use with kubectl", }, cli.StringFlag{ Name: kubeconfigFlag, EnvVar: kubeconfigEnvVar, Usage: "the base64 encoded kubeconfig to use", }, cli.StringFlag{ Name: kubectlFlag, EnvVar: kubectlEnvVar, Usage: "the kubectl command to execute", }, cli.StringFlag{ Name: namespaceFlag, EnvVar: namespaceEnvVar, Usage: "the namespace used by kubectl", }, cli.StringSliceFlag{ Name: templatesFlag, EnvVar: templatesEnvVar, Usage: "the template files to use with kubectl", }, cli.BoolFlag{ Name: debugFlag, EnvVar: debugEnvVar, Usage: "print out some sensitive debug info", }, } if err := app.Run(os.Args); err != nil { log.Fatal(err) } } func run(c *cli.Context) error { kubectl, err := kubectlCommand(c.String(kubectlFlag)) if err != nil { return err } kubeconfigPath := "" kubeconfig64 := c.String(kubeconfigFlag) isInClusterConfig := kubeconfig64 == "" if isInClusterConfig { log.Println("Using in-cluster credentials") } else { log.Println("Decoding kubeconfig from secret") kube, err := base64.StdEncoding.DecodeString(kubeconfig64) if err != nil { return errors.Wrap(err, "failed to base64 decode kubeconfig from envvar") } if c.Bool(debugFlag) { log.Printf("decoded KUBECONFIG:\n%s", kube) } tmpfile, err := ioutil.TempFile("", "kubeconfig") if err != nil { return errors.Wrap(err, "failed to create tmp file for kubeconfig") } defer os.Remove(tmpfile.Name()) if _, err := tmpfile.Write(kube); err != nil { return errors.Wrap(err, "failed to write to tmp kubeconfig file") } if err := tmpfile.Close(); err != nil { return errors.Wrap(err, "failed to close tmp kubeconfig file") } kubeconfigPath = tmpfile.Name() } args := kubectlArgs(kubectl, kubectlFiles(c.StringSlice(filesFlag)), kubectlNamespace(c.String(namespaceFlag)), kubectlTemplates(c.StringSlice(templatesFlag)), ) if !c.Bool(dryRunFlag) { cmd := exec.CommandContext(context.TODO(), binary, args...) if !isInClusterConfig { cmd.Env = []string{"KUBECONFIG=" + kubeconfigPath} } cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " ")) if err := cmd.Run(); err != nil { return err } } return nil } // kubectlCommand makes sure there's not an empty string and executes templating if necessary func kubectlCommand(command string) (string, error) { if command == "" { return "", errors.New("no kubectl command specific") } // If kubectl command contains {{ }} then enable templating on the kubectl command if strings.Contains(command, "{{") && strings.Contains(command, "}}") { tmpl, err := generateTemplate(command) if err != nil { return "", errors.Wrap(err, "failed to generate template from kubectl command") } return tmpl, err } return command, nil } type kubectlOption func([]string) []string func kubectlArgs(kubectl string, options ...kubectlOption) []string { args := strings.Split(kubectl, " ") for _, opt := range options { args = opt(args) } return args } func kubectlFiles(files []string) kubectlOption { return func(args []string) []string { if !stringsContain(args, "--filename") && !stringsContain(args, "-f") { for _, f := range files { args = append(args, "-f", f) } } return args } } func kubectlNamespace(ns string) kubectlOption { return func(args []string) []string { if ns == "" { return args } if !stringsContain(args, "--namespace") && !stringsContain(args, "-n") { args = append(args, "--namespace", ns) } return args } } func kubectlTemplates(templates []string) kubectlOption { return func(args []string) []string { if !stringsContain(args, "--filename") && !stringsContain(args, "-f") { for _, t := range templates { path, err := generateTemplateFile(t) if err != nil { fmt.Println(t, err) continue } args = append(args, "-f", path) } } return args } } func stringsContain(slice []string, s string) bool { for _, item := range slice { if item == s { return true } } return false } func generateTemplateFile(path string) (string, error) { tc, err := ioutil.ReadFile(path) if err != nil { return "", errors.Wrap(err, "failed to read file") } tmpl, err := generateTemplate(string(tc)) if err != nil { return "", errors.Wrap(err, "failed to generate template from file") } tmpfile, err := ioutil.TempFile("", filepath.Base(path)) if err != nil { return "", errors.Wrap(err, "failed to create tmp file for template") } if _, err := tmpfile.WriteString(tmpl); err != nil { return "", errors.Wrap(err, "failed to write template to tmp file") } if err := tmpfile.Close(); err != nil { return "", errors.Wrap(err, "failed to close tmp file for template") } return tmpfile.Name(), nil } func generateTemplate(t string) (string, error) { tmpl := template.New("template").Funcs(map[string]interface{}{ "upper": strings.ToUpper, "lower": strings.ToLower, "replace": strings.Replace, "split": strings.Split, "trim": strings.Trim, "trimPrefix": strings.TrimPrefix, "trimSuffix": strings.TrimSuffix, "toTitle": strings.ToTitle, "datetime": templateDatetime, "trunc": templateTruncate, "b64enc": templateB64enc, "b64dec": templateB64dec, }) tmpl, err := tmpl.Parse(t) if err != nil { return "", errors.Wrap(err, "failed to parse template") } w := bytes.NewBuffer(nil) if err := tmpl.Execute(w, environmentVariables()); err != nil { return "", errors.Wrap(err, "failed to execute template") } return w.String(), err } func environmentVariables() map[string]string { variables := make(map[string]string, len(os.Environ())) for _, env := range os.Environ() { pair := strings.SplitN(env, "=", 2) variables[casee.ToPascalCase(pair[0])] = pair[1] } return variables } func templateDatetime(timestamp float64, layout, zone string) string { if zone == "" { return time.Unix(int64(timestamp), 0).Format(layout) } loc, err := time.LoadLocation(zone) if err != nil { return time.Unix(int64(timestamp), 0).Local().Format(layout) } return time.Unix(int64(timestamp), 0).In(loc).Format(layout) } func templateTruncate(s string, len int) string { if utf8.RuneCountInString(s) <= len { return s } runes := []rune(s) return string(runes[:len]) } func templateB64enc(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } func templateB64dec(s string) string { data, err := base64.StdEncoding.DecodeString(s) if err != nil { return s } return string(data) } <file_sep>## 0.3.0 / 2020-12-16 Bring the entire project from 2017 to 2020 * [ENHANCEMENT] Update kubectl to v1.19.4 * [ENHANCEMENT] Update to Go 1.15 * [FIX] Fix this plugin to work with new Drone config - needed to add prefix `PLUGIN_` to `PLUGIN_KUBECONFIG` ## 0.2.2 / 2018-10-15 * [ENHANCEMENT] Update kubectl to v1.12.1 * [FIX] Using in cluster credentials for kubectl correctly. * [FEATURE] Add debug mode. ## 0.2.1 / 2018-05-29 * [ENHANCEMENT] Update kubectl to v1.10.3 ## 0.2.0 / 2018-02-01 * [FEATURE] Allow kubectl commands to use templating [#5] * [ENHANCEMENT] Update kubectl to v1.9.2 ## 0.1.0 / 2018-01-28 Initial Release * [FEATURE] Add string helpers like b64enc, trunc, trim, upper and lower [#4] * [ENHANCEMENT] Pass the complete environment to templates [#2] <file_sep>module github.com/metalmatze/drone-kubectl go 1.15 require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/fatih/camelcase v1.0.0 // indirect github.com/joho/godotenv v1.3.0 github.com/pinzolo/casee v0.0.0-20160729104318-956b6baf666a github.com/pkg/errors v0.8.0 github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/testify v1.2.2 github.com/urfave/cli v1.20.0 ) <file_sep>--- date: 2018-10-15T00:00:00+00:00 title: drone-kubectl author: metalmatze tags: [ kubernetes, kubectl ] repo: metalmatze/drone-kubectl logo: kubectl.svg image: metalmatze/drone-kubectl --- The kubectl plugin can be used to do everything kubectl can do. It provides some helpers and shortcuts to make your pipeline step more readable. Example configuration running inside a kubernetes cluster: ```yaml pipeline: kubectl: image: metalmatze/drone-kubectl kubectl: get pods ``` Example configuration using a kubeconfig via a secret: This is **required** when running outside a cluster or a different one should be talked to. ```diff pipeline: kubectl: image: metalmatze/drone-kubectl kubectl: get pods + secrets: [ kubeconfig ] ``` _This takes the secret kubeconfig, base64 decodes it and writes it to disk ready for kubectl._ Example configuration using a different kubeconig via a secrets: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl kubectl: get pods + secrets: + - source: kubeconfig_development + target: kubeconfig ``` _This maps the `kubeconfig_develpment` secret to be used by the plugin as `kubeconfig` which is then forwarded to kubectl._ Example configuration running inside a kubernetes cluster using a different namespace: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl - kubectl: get pods + kubectl: --namespace application get pods ``` equivalent: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl kubectl: get pods + namespace: application ``` Example configuration using file paths to apply: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl + kubectl: apply -f /path/to/folder/foo.yaml -f /path/to/folder/bar.yaml -f /path/to/folder/baz.yaml ``` equivalent but easier to read: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl - kubectl: apply -f /path/to/folder/foo.yaml -f /path/to/folder/bar.yaml -f /path/to/folder/baz.yaml + kubectl: apply + files: + - /path/to/folder/foo.yaml + - /path/to/folder/bar.yaml + - /path/to/folder/baz.yaml ``` ### Templating Templating generate commands or files to be used by kubectl when executing. Setting the image to the current commit: ```diff pipeline: kubectl: image: metalmatze/drone-kubectl kubectl: set image deployment/foo container=bar/baz:{{ .DroneCommit }} ``` ### Debug You can turn on the debug mode to see some details like the plain text `kubeconfig`. **Attention** only use this on test systems, **NOT AT PRODUCTIVE SYSTEMS**. ```diff pipeline: kubectl: image: metalmatze/drone-kubectl + debug: true ``` <file_sep>package main import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestKubectlArgs(t *testing.T) { args := kubectlArgs("get pods") assert.Equal(t, []string{"get", "pods"}, args) } func TestKubectlFiles(t *testing.T) { args := kubectlArgs("apply", kubectlFiles([]string{})) assert.Equal(t, []string{"apply"}, args) args = kubectlArgs("apply", kubectlFiles([]string{"foo.yaml"})) assert.Equal(t, []string{"apply", "-f", "foo.yaml"}, args) args = kubectlArgs("apply", kubectlFiles([]string{"foo.yaml", "bar.yaml"})) assert.Equal(t, []string{"apply", "-f", "foo.yaml", "-f", "bar.yaml"}, args) // Don't overwrite files if already set args = kubectlArgs("apply -f app.yaml", kubectlFiles([]string{"foo.yaml"})) assert.Equal(t, []string{"apply", "-f", "app.yaml"}, args) args = kubectlArgs("apply --filename app.yaml", kubectlFiles([]string{"foo.yaml"})) assert.Equal(t, []string{"apply", "--filename", "app.yaml"}, args) } func TestKubectlNamespace(t *testing.T) { args := kubectlArgs("get pods", kubectlNamespace("")) assert.Equal(t, []string{"get", "pods"}, args) args = kubectlArgs("get pods", kubectlNamespace("app")) assert.Equal(t, []string{"get", "pods", "--namespace", "app"}, args) // Don't overwrite namespace if already set args = kubectlArgs("get pods -n drone", kubectlNamespace("app")) assert.Equal(t, []string{"get", "pods", "-n", "drone"}, args) args = kubectlArgs("get pods --namespace drone", kubectlNamespace("app")) assert.Equal(t, []string{"get", "pods", "--namespace", "drone"}, args) } func TestKubectlCommandTemplating(t *testing.T) { kubectl, err := kubectlCommand("get nodes") assert.NoError(t, err) assert.Equal(t, "get nodes", kubectl) os.Setenv("DRONE_COMMIT", "v1.2.3") kubectl, err = kubectlCommand("set image deployment/foo container=bar/baz:{{ .DroneCommit }}") assert.NoError(t, err) assert.Equal(t, "set image deployment/foo container=bar/baz:v1.2.3", kubectl) }
1dbc9dfc6ec3a71b18748311145aaf2112bd2a28
[ "Markdown", "Go Module", "Go", "Dockerfile" ]
7
Dockerfile
metalmatze/drone-kubectl
5ff4177802a2fe65f374eb426d17f6ac7e69eefa
6ea2988a158e485a5b66e604c4dc3e3b1cf1e16b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.ComponentModel; using System.Reflection; namespace DailyProgrammer226_Connect_Four { public enum BoardSquareStatus { [Description(" ")] empty, [Description("X")] X, [Description("O")] O } public class BoardSquare : IComparable<BoardSquare> { public int row; public char column; public BoardSquare(int row, char column) { this.row = row; this.column = column; } public int CompareTo(BoardSquare x) { return this.column.CompareTo(x.column); } } //6 rows, 7 columns /* a b c d e f g 6 . . . . . . . 5 . . . . . . . 4 . . . . . . . 3 . . . . . . . 2 . . . . . . . 1 . . . . . . . */ public class ConnectFourBoard { private static readonly int BOARDCOLUMNS = 7; private static readonly int BOARDROWS = 6; private BoardSquareStatus[,] myBoard = new BoardSquareStatus[BOARDROWS, BOARDCOLUMNS]; public SortedSet<BoardSquare> winningMoves = new SortedSet<BoardSquare>(); public static String GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } public ConnectFourBoard() { for(int i=0;i<myBoard.GetLength(0);i++) { for(int j=0;j<myBoard.GetLength(1);j++) { myBoard[i, j] = BoardSquareStatus.empty; } } } public void printBoard() { Console.WriteLine(" a b c d e f g"); for(int i=BOARDROWS - 1; i>=0; i--) { Console.Write(i + " "); for(int j=0; j<BOARDCOLUMNS;j++) { Console.Write(GetEnumDescription(myBoard[i,j]) + " "); } Console.WriteLine(); } } //Returns the row of the placed piece or -1 if full public int tryPlacePiece(BoardSquareStatus piece, char column) { int col = convertColumntoInt(column); int row = findLowestRowUnoccupied(col); if (row == -1) return -1; myBoard[row,col] = piece; return row; } public int convertColumntoInt(char column) { return (int)column - 97; } public char convertIntToColumn(int column) { return (char)(column + 97); } private int findLowestRowUnoccupied(int column) { for (int i = 0; i < myBoard.GetLength(0); i++) { if (myBoard[i, column] == BoardSquareStatus.empty) return i; } return -1; //Row is full } public BoardSquareStatus getPieceAt(int row, char column) { return myBoard[row, convertColumntoInt(column)]; } public bool isGameOver(int row, char column) { bool[,] squareChecked = new bool[7,6]; BoardSquareStatus curPlayer = this.getPieceAt(row,column); int columnAsInt = convertColumntoInt(column); if (checkRow(row, columnAsInt, curPlayer)) return true; if (checkColumn(row, columnAsInt, curPlayer)) return true; if (checkAscendingDiagonal(row, columnAsInt, curPlayer)) return true; if (checkDescendingDiagonal(row, columnAsInt, curPlayer)) return true; return false; } private bool checkRow(int row, int column, BoardSquareStatus curPlayer) { winningMoves = new SortedSet<BoardSquare>(); for (int i = column + 1; i < BOARDCOLUMNS;i++) { if (!isSamePlayer(row, i,curPlayer)) break; } for (int i = column; i >= 0; i--) { if (!isSamePlayer(row, i, curPlayer)) break; } if (winningMoves.Count == 4) return true; return false; } private bool checkColumn(int row, int column, BoardSquareStatus curPlayer) { winningMoves = new SortedSet<BoardSquare>(); for (int i = row + 1; i < BOARDROWS; i++) { if (!isSamePlayer(i, column, curPlayer)) break; } for (int i = row; i >= 0; i--) { if (!isSamePlayer(i, column, curPlayer)) break; } if (winningMoves.Count == 4) return true; return false; } private bool checkAscendingDiagonal(int row, int column, BoardSquareStatus curPlayer) { winningMoves = new SortedSet<BoardSquare>(); int i = row + 1; for (int j = column + 1; i < BOARDROWS && j < BOARDCOLUMNS; j++) { if(!isSamePlayer(i,j,curPlayer)) break; i++; } i = row; for (int j = column; i >= 0 && j >= 0; j--) { if (!isSamePlayer(i, j, curPlayer)) break; i--; } if (winningMoves.Count == 4) return true; return false; } private bool checkDescendingDiagonal(int row, int column, BoardSquareStatus curPlayer) { winningMoves = new SortedSet<BoardSquare>(); int i = row - 1; for (int j = column + 1; i >= 0 && j < BOARDCOLUMNS; j++) { if (!isSamePlayer(i, j, curPlayer)) break; i--; } i = row; for (int j = column; i < BOARDROWS && j >= 0; j--) { if (!isSamePlayer(i, j, curPlayer)) break; i++; } if (winningMoves.Count == 4) return true; return false; } private bool isSamePlayer(int row, int column, BoardSquareStatus curPlayer) { if (myBoard[row, column] == curPlayer) { winningMoves.Add(new BoardSquare(row+1, convertIntToColumn(column))); return true; }else { return false; } } } class GameEngine { private static char[] getMoves(string filename) { List<char> moves = new List<char>(); foreach(string line in File.ReadLines(filename)) { string[] splitMoves = line.Trim().ToLower().Split((char[])null,StringSplitOptions.RemoveEmptyEntries); foreach(string individualMove in splitMoves) { moves.Add(individualMove.ToCharArray()[0]); } } return moves.ToArray(); } static void Main(string[] args) { ConnectFourBoard board = new ConnectFourBoard(); int currentMove = 0; char[] moves = getMoves(@"C:\Users\829356\Documents\DP226.txt"); bool playerXturn = true; bool gameOver = false; while(!gameOver) { BoardSquareStatus curPlayer; if (playerXturn) curPlayer = BoardSquareStatus.X; else curPlayer = BoardSquareStatus.O; if(currentMove>moves.Length-1) { Console.WriteLine("Ran out of moves!"); break; } int placedRow = board.tryPlacePiece(curPlayer,moves[currentMove]); string curPlayerName = Enum.GetName(typeof(BoardSquareStatus),curPlayer); int turn = (int)(Math.Ceiling((double)(currentMove + 1) / 2)); Console.WriteLine("Turn " + turn + ": Player " + curPlayerName + " placed a piece at " + placedRow + "," + moves[currentMove]); if(placedRow == -1) { Console.WriteLine("Invalid placement, column is full. Move num: " + currentMove + ", column: " + moves[currentMove]); break; } if(board.isGameOver(placedRow,moves[currentMove])) { Console.Write("Player " + curPlayerName + " has won at move " + turn + " (with"); foreach(BoardSquare curSquare in board.winningMoves) { Console.Write(" "); Console.Write(curSquare.column + curSquare.row.ToString()); } Console.WriteLine(")"); gameOver = true; } board.printBoard(); currentMove++; playerXturn = !playerXturn; } Console.Read(); } } } <file_sep>using System; using System.Numerics; namespace DailyProgrammer{ class MainClass{ public static string Reverse( string s ){ char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); } public static bool isPalindrome(string test){ string firstHalf, secondHalf; if (test.Length % 2 == 0) { firstHalf = test.Substring (0, test.Length / 2); secondHalf = test.Substring (test.Length / 2, test.Length / 2); } else { firstHalf = test.Substring (0, test.Length / 2); secondHalf = test.Substring (test.Length / 2 + 1, test.Length / 2); } secondHalf = Reverse (secondHalf); return firstHalf.Equals (secondHalf); } public static void Main (string[] args){ string input = Console.ReadLine (); BigInteger test = BigInteger.Parse(input); for (int i = 1; i <= 10000; i++) { BigInteger first, second; String forward = test.ToString(); String reverse = Reverse(forward); if (BigInteger.TryParse (forward, out first) && BigInteger.TryParse (reverse, out second)) { test = BigInteger.Add(first, second); String testString = test.ToString (); if (isPalindrome (testString)) { Console.WriteLine (input + " gets palindromic after " + i + " steps: " + test); return; } } } Console.WriteLine (input + " never gets palindromic after 10000 iterations"); } } } <file_sep>using System; using System.Text; namespace DailyProgrammer222_Simple_Stream_Cipher { class randomNumberGenerator { private int modulus, multiplier, increment, curValue; public randomNumberGenerator(int modulus, int multiplier, int increment, int startValue) { this.modulus = modulus; this.multiplier = multiplier; this.increment = increment; this.curValue = startValue; } public byte getRandomByte() { curValue = ((multiplier * curValue + increment) % modulus); return (byte)curValue; } } class Program { public static string encrypt(int key, string plaintext) { string result; char[] plaintextChars = plaintext.ToCharArray(); char[] output = new char[plaintextChars.GetLength(0)]; randomNumberGenerator rand = new randomNumberGenerator(10000, 23, 64, key); for(int i=0;i<plaintextChars.GetLength(0);i++) { byte curByte = System.Convert.ToByte(plaintextChars[i]); output[i] = System.Convert.ToChar(curByte ^ rand.getRandomByte()); } result = new string(output); return result; } public static string decrypt(int key, string ciphertext) { return encrypt(key, ciphertext); } static void Main(string[] args) { int key = 31337; string msg = "Attack at dawn"; Console.WriteLine("Message: " + msg); msg = encrypt(key,msg); Console.WriteLine("Encrypted Message: " + msg); msg = decrypt(key, msg); Console.WriteLine("Decrypted Message: " + msg); Console.Read(); } } }
228919be7d0d651d633d3b90dfe6547ffb537dd6
[ "C#" ]
3
C#
andrewtackett/DailyProgrammer
9f71bd4f1d39b7e99cf5d8a0e01f76a6373762fe
da080c112519c7ca2df3f233b331a7a5655cce95
refs/heads/master
<file_sep>import numpy.random as random # Boolean variable on 50% chance def coin_toss(): return random.random() >= 0.5 # Mean value between numbers def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) # Sum of squares def sum2(numbers): return sum(x*x for x in numbers) # Standard deviation def std(numbers): n = len(numbers) sum_sum = sum2(numbers) avg = mean(numbers) return abs((sum_sum - n*avg*avg) / (n - 1.0)) ** 0.5 # Adds arrows between values of a list def arrow_list_str(some_list): return str(some_list).replace(', ', ' -> ').replace('[', '').replace(']', '').replace("'", '')<file_sep># genetics Genetic algorithm implementation for senior thesis, along with dissertation. ## Folder structure for thesis ``` thesis │ README.md │ file001.txt │ └───docs // Made outside of LaTeX │ file011.txt │ file012.txt │ ├───subfolder1 │ │ file111.txt │ │ file112.txt │ │ ... │ ├───folder2 │ file021.txt │ file022.txt ``` <file_sep>import copy from dijkstra17 import dijkstra17_graph # Functions that apply Dijkstra's algorithm def dijkstra_all(graph): full_map = {} for source in graph: dist, prev = dijkstra(graph, source) full_map[source] = {} full_map[source]['dist'] = dist full_map[source]['prev'] = prev return full_map def dijkstra(graph, source): Q = set() dist = {} prev = {} for vertex in graph: dist[vertex] = float("inf") prev[vertex] = None Q.add(vertex) dist[source] = 0 while len(Q) is not 0: u = min_value(Q, dist) Q.remove(u) for v in graph[u]: alt = dist[u] + graph[u][v] if alt < dist[v]: dist[v] = alt prev[v] = u return dist, prev def min_value(Q, dist): u = next(iter(Q)) for v in Q: if dist[v] < dist[u]: u = v return u # Global variables complete_graph = dijkstra_all(dijkstra17_graph) all_cities = [node for node in complete_graph] all_cities.sort() # Functions to calculate distance def dist_between(a, b, dijkstra_graph=complete_graph): return dijkstra_graph[a]['dist'][b] def tsp_dist(sequence): copy_cities = copy.copy(all_cities) init = copy_cities.pop(0) prev = init next = None tsp_sum = 0 for i in sequence: prev = prev if next is None else next next = copy_cities.pop(i) tsp_sum += dist_between(prev, next) tsp_sum += dist_between(next, copy_cities[0]) tsp_sum += dist_between(copy_cities[0], init) return tsp_sum # Functions to find paths def path_between(a, b, dijkstra_graph=complete_graph): path = [b] prev = dijkstra_graph[a]['prev'][b] while prev is not None: path.insert(0, prev) prev = dijkstra_graph[a]['prev'][prev] return path def tsp_path(sequence): copy_sequence = copy.copy(sequence) copy_sequence.append(0) copy_cities = copy.copy(all_cities) init = copy_cities.pop(0) tsp_path = [init] for i in copy_sequence: tsp_path.append(copy_cities.pop(i)) tsp_path.append(init) return tsp_path def tsp_full_path(sequence): path = tsp_path(sequence) full_path = [] for first, second in zip(path, path[1:]): full_path = full_path[:-1] + path_between(first, second) return full_path dijkstra_gsize = len(all_cities) <file_sep>from genes import new_gene from utils import arrow_list_str from dijkstra import tsp_dist, tsp_path, tsp_full_path, dijkstra_gsize import numpy.random as random def new_individual(ind_name, gene_type=None, gsize=None): constructor = globals()[ind_name] if gene_type is None: return constructor() elif gsize is None: return constructor(gene_type) else: return constructor(gene_type, gsize) def from_genes(ind_name, genes, gene_type=None): ind = new_individual(ind_name, gene_type) ind.genes = genes return ind class Individual: def __init__(self, gene_type, gsize): self.gene_type = gene_type self.genes = [new_gene(gene_type) for x in range(gsize)] self.fitness = 0.0 def __len__(self): return len(self.genes) def __repr__(self): return 'Individual {Gene: %s, Count: %d}' % (self.gene_type, len(self)) class OneMaxIndividual(Individual): def __init__(self, gene_type='BooleanGene', gsize=100): Individual.__init__(self, gene_type, gsize) self.gene_type = gene_type self.fitness = 0.0 def __repr__(self): return 'OneMaxIndividual {Gene: %s, Count: %d}' % (self.gene_type, len(self)) def __str__(self): return str([x.value() for x in self.genes]) class TSPIndividual(Individual): def __init__(self, gene_type='IntegerGene', gsize=dijkstra_gsize): Individual.__init__(self, gene_type, gsize) self.gene_type = gene_type self.genes = [new_gene(gene_type, csize) for csize in reversed(range(2, gsize))] self.fitness = 0.0 def __repr__(self): return 'TSPIndividual {Gene: %s, Count: %d}' % (self.gene_type, len(self)) def __str__(self): sequence = [x.value() for x in self.genes] string = '\nDistance : ' + str(tsp_dist(sequence)) string += '\nCities visited : ' + arrow_list_str(tsp_path(sequence)) string += '\nFull path : ' + arrow_list_str(tsp_full_path(sequence)) return string <file_sep>import numpy.random as random from utils import coin_toss def new_gene(gene_name, args=None): constructor = globals()[gene_name] return constructor() if args is None else constructor(args) class Gene: def __init__(self): self.val = None def __repr__(self): return 'Gene {value: %s}' % (self.val) def value(self): return self.val def mutate(self): pass class BooleanGene(Gene): def __init__(self, val=False): Gene.__init__(self) self.val = val def __repr__(self): return 'BooleanGene {value: %s}' % (self.value()) def value(self): return 1 if self.val else 0 def mutate(self): self.val = coin_toss() class RealGene(Gene): def __init__(self, val=0.0): Gene.__init__(self) self.val = val def __repr__(self): return 'RealGene {value: %s}' % (self.val) def mutate(self): self.val = random.random() class IntegerGene(Gene): def __init__(self, k=2): if k <= 1: raise ValueError('IntegerGene should have a range greater than 1.') Gene.__init__(self) self.val = 0 self.k = k def __repr__(self): return 'IntegerGene {value: %s, k: %s}' % (self.val, self.k) def mutate(self): current_val = self.val self.val = random.randint(self.k) while self.val == current_val: self.val = random.randint(self.k) <file_sep> # City map - only contains the paths between the cities dijkstra_map = [ ('A', 'B', 12), ('A', 'C', 20), ('A', 'D', 25), ('A', 'E', 15), ('B', 'C', 40), ('B', 'E', 17), ('C', 'F', 12), ('D', 'E', 30), ('D', 'F', 40), ('E', 'G', 10), ('F', 'G', 10) ] # Functions to find the graph def create_graph(dijk_map): if dijk_map is None or len(dijk_map) is 0: return None graph = {} for edge_tuple in dijk_map: first_city = edge_tuple[0] second_city = edge_tuple[1] distance = edge_tuple[2] if graph.get(first_city) is None: graph[first_city] = {} if graph.get(second_city) is None: graph[second_city] = {} graph[first_city][second_city] = distance graph[second_city][first_city] = distance return graph dijkstra_manual_graph = create_graph(dijkstra_map) <file_sep>import numpy.random as random import fitness import copy import os from utils import * from individuals import new_individual, from_genes from individuals import Individual class GeneFlow: def __init__(self, ind_type, gene_type, ffit=None, pc=0.9, pm=0.01, mu=100, ngen=200, print_stats=True, maximum=True, elitism=True, adaptive=False): self.fitness = ffit self.population = [new_individual(ind_type, gene_type) for x in range(mu)] self.pm = pm self.pm0 = pm self.pc = pc self.mu = mu self.ngen = ngen self.print_stats = print_stats self.maximum = maximum self.elitism = elitism self.adaptive = adaptive self.start_writing(ind_type, gene_type) def start_writing(self, ind_type, gene_type): file_name = '../out/' + ind_type + '_' + gene_type + ('' if not self.adaptive else '_adaptive') new_path = os.path.relpath(file_name + '.csv', os.path.dirname(__file__)) self.file = open(new_path, 'w') self.file.write('Generation,Min,Max,Avg,Std\n') if self.adaptive: new_path = os.path.relpath(file_name + '_pm.csv', os.path.dirname(__file__)) self.adapt_file = open(new_path, 'w') self.adapt_file.write('Generation,pm,pm0,deviation,best_fitness\n') def calculate_all_fitness(self): self.parent_fitness() self.offspring_fitness() def parent_fitness(self): for individual in self.population: individual.fitness = self.fitness(individual) def offspring_fitness(self): for individual in self.offspring: individual.fitness = self.fitness(individual) def min_fitness(self): return min([x.fitness for x in self.population]) def max_fitness(self): return max([x.fitness for x in self.population]) def best_fitness(self): return self.max_fitness() if self.maximum else self.min_fitness() def avg_fitness(self): return mean([x.fitness for x in self.population]) def std_fitness(self): return std([x.fitness for x in self.population]) def stats(self): if self.print_stats is False: return print('Min : %.6f' % self.min_fitness()) print('Max : %.6f' % self.max_fitness()) print('Average: %.6f' % self.avg_fitness()) print('Std : %.6f' % self.std_fitness()) print('Best individual is: ' + str(self.population[0])) def generate(self): if self.print_stats: print('Generation 0:') self.parent_fitness() self.stats() self.write_to_file(0) for i in range(self.ngen): if self.print_stats: print('\nGeneration %s:' % (i+1)) self.update() self.stats() self.write_to_file(i+1) def update(self): self.selection() self.crossover() self.mutation() self.survival() pass # The offspring is selected based on the best fitness values def selection(self): self.population.sort(key=lambda ind:ind.fitness, reverse=self.maximum) self.offspring = [] # Offspring is paired and crossed over with probability pc - two parents generate two children def crossover(self): for parent1, parent2 in zip(self.population[::2], self.population[1::2]): if random.random() < self.pc: child1, child2 = self.cross(parent1, parent2) self.offspring.append(child1) self.offspring.append(child2) # Two-point crossover - two children mix their genes, based in a two-point section switch of their genes def cross(self, ind1, ind2): length = len(ind1) ind_type = ind1.__class__.__name__ gene_type = ind1.gene_type genes1 = copy.deepcopy(ind1.genes) genes2 = copy.deepcopy(ind2.genes) # Two distinct points are chosen rand1 = random.randint(length + 1) rand2 = random.randint(length + 1) while (rand1 == rand2) or (rand1 == 0 and rand2 == length) or (rand2 == 0 and rand1 == length): rand2 = random.randint(length + 1) rand1, rand2 = (rand1, rand2) if rand1 < rand2 else (rand2, rand1) genes1[rand1:rand2], genes2[rand1:rand2] = genes2[rand1:rand2], genes1[rand1:rand2] return from_genes(ind_type, genes1, gene_type), from_genes(ind_type, genes2, gene_type) # Mutation acts over all genes (except the elite), with probability pm def mutation(self): if self.elitism: self.population.sort(key=lambda ind:ind.fitness, reverse=self.maximum) self.elite = copy.deepcopy(self.population[0]) self.population = self.population[1:] for ind in self.population: for gene in ind.genes: if random.random() < self.pm: gene.mutate() for ind in self.offspring: for gene in ind.genes: if random.random() < self.pm: gene.mutate() # Only the best mu individuals survive def survival(self): if self.elitism: self.population.append(self.elite) self.calculate_all_fitness() self.population = self.population + self.offspring self.population.sort(key=lambda ind:ind.fitness, reverse=self.maximum) self.population = self.population[:self.mu] if self.adaptive: self.adapt() # Deviation of the best fitness to the average def deviation(self): if abs(self.avg_fitness()) < 0.0000001: return 0.0 return abs((self.best_fitness() - self.avg_fitness()) / (self.avg_fitness())) # Adaptive Genetic Algorithm (AGA) module def adapt(self): # In order to avoid division by zero if abs(self.avg_fitness()) < 0.0000001: return # Increment pm if the deviation is lower than pm0 if self.deviation() <= self.pm0: self.pm = min(0.5, self.pm + 0.001) # Decrement pm, otherwise else: self.pm = max(0.001, self.pm - 0.001) if self.print_stats: print self.deviation(), self.pm, self.pm0, self.best_fitness() def write_to_file(self, n): self.file.write(str(n)) self.file.write(',') self.file.write(str(self.min_fitness())) self.file.write(',') self.file.write(str(self.max_fitness())) self.file.write(',') self.file.write(str(self.avg_fitness())) self.file.write(',') self.file.write(str(self.std_fitness())) self.file.write('\n') if self.adaptive: self.adapt_file.write(str(n)) self.adapt_file.write(',') self.adapt_file.write(str(self.pm)) self.adapt_file.write(',') self.adapt_file.write(str(self.pm0)) self.adapt_file.write(',') self.adapt_file.write(str(self.deviation())) self.adapt_file.write(',') self.adapt_file.write(str(self.best_fitness())) self.adapt_file.write('\n') # Uncomment one of the next three lines to simulate the algorithm #GeneFlow('OneMaxIndividual', 'BooleanGene', fitness.onemax, adaptive=True, print_stats=True, pm=0.01).generate() #GeneFlow('OneMaxIndividual', 'RealGene', fitness.onemax, adaptive=True, print_stats=True, pm=0.01).generate() GeneFlow('TSPIndividual', 'IntegerGene', fitness.tsp, maximum=False, adaptive=True, print_stats=True, pm=0.2).generate() <file_sep>from dijkstra import tsp_dist, all_cities import copy # Fitness function for OneMax def onemax(individual): return sum(gene.value() for gene in individual.genes) # Fitness function for TSP def tsp(individual): return tsp_dist([gene.value() for gene in individual.genes]) <file_sep>import numpy.random as random def nonzero_rand(limit): return random.randint(limit + 1) # Gets two distinct random positions in a list of def crossover_two_point(ind1, ind2): if len(ind1) < 2 or len(ind1) != len(ind2): return length = len(ind1) if length == 2: return ind1[:1] + ind2[1:], ind2[:1] + ind1[1:] rand1 = nonzero_rand(length) rand2 = nonzero_rand(length) while (rand1 == rand2) or (rand1 == 0 and rand2 == length) or (rand2 == 0 and rand1 == length): rand2 = nonzero_rand(length) rand1, rand2 = (rand1, rand2) if rand1 < rand2 else (rand2, rand1) one_crossed = ind1[:rand1] + ind2[rand1:rand2] + ind1[rand2:] two_crossed = ind2[:rand1] + ind1[rand1:rand2] + ind2[rand2:] if one_crossed == ind1 or two_crossed == ind1: print rand1, rand2 raise ValueError('Error') return one_crossed, two_crossed for i in range(2000): print crossover_two_point([0,1,1,0,0,0], [1,0,0,1,1,1])<file_sep>import fitness import numpy as np from geneflow import * def test_tuning(NGEN=200): best_fitness = 0.0 best_pc = 0.0 i = 0 for tuning_pc in np.linspace(0.9, 1., 51): flow = GeneFlow('OneMaxIndividual', 'RealGene', fitness.onemax, ngen=NGEN, print_stats=False, pc=tuning_pc) flow.generate() print 'Finished', i+1 i = i + 1 if best_fitness < flow.avg_fitness(): best_fitness = flow.avg_fitness() best_pc = tuning_pc print("Best Fitness: %.6f" % best_fitness) print("Best pc : %.6f" % best_pc) best_fitness = 0.0 best_pm = 0.0 for tuning_pm in np.linspace(0, 0.05, 51): flow = GeneFlow('OneMaxIndividual', 'RealGene', fitness.onemax, ngen=NGEN, print_stats=False, pc=best_pc, pm=tuning_pm) flow.generate() print 'Finished', i+1 i = i + 1 if best_fitness < flow.avg_fitness(): best_fitness = flow.avg_fitness() best_pm = tuning_pm print("Best Fitness: %.6f" % best_fitness) print("Best pm : %.6f" % best_pm) test_tuning()
3ab5b20a823ae11b9a5c084dc043074e795f97fe
[ "Markdown", "Python" ]
10
Python
cassioss/genetics
62af87361ec72c5ebf9a47ab549eed8856d964f0
5a844a6a808f1a0cbb07c77e18380d797a9dd687
refs/heads/main
<file_sep> const tutorials = require("../controllers/tutorial.controller.js"); const router = require("express").Router(); router.post("/", tutorials.create); module.exports = router<file_sep>const db = require('../models'); const tutorialService = require('../services/tutorial.service') const Tutorial = db.tutorial; const Op = db.Sequelize.Op; const create = async (req, res) => { if (!req.body.title) { return res.status(400).send({ message: "Title can not be empty!" }); } const createdTut = await tutorialService.createTutorial(req.body); if(createdTut) { return res.status(200).send(createdTut) } return res.send(500).send('Could not create the tutorial'); } module.exports = {create};
510c71c182d7a13ba89c7d9b85e4ad5e4c1582cd
[ "JavaScript" ]
2
JavaScript
sagar-adval/Node-Sql-CRUD
099720b7b95e26370b6c22e091e6998179df23e5
d85ccc276c1e60dc169930b206ea953b6f3f2da5
refs/heads/master
<repo_name>mtharmen/image-search<file_sep>/README.md # API Basejump: Image Search Abstraction Layer Microservice ## User stories: 1. I can get the image URLs, alt text and page urls for a set of images relating to a given search string. 2. I can paginate through the responses by adding a ?offset=2 parameter to the URL. 3. I can get a list of the most recently submitted search strings. ### Example usage: ```text https://mtharmen-image-search.herokuapp.com/imagesearch/lolcats%20funny?offset=10 https://mtharmen-image-search.herokuapp.com/history ``` <file_sep>/server.js var express = require('express'); require('dotenv').config({silent: true}); var mongoose = require('mongoose'); var Bing = require('node-bing-api')({ accKey: process.env.API_KEY }); var routes = require('./app/routes/searchApp.js'); var app = express(); app.use('/', express.static(__dirname + '/app/styles')); // Document format var historySchema = mongoose.Schema({ term: String, when: String }); var History = mongoose.model('History', historySchema); // Establishing connection to database var mongodbUrl = process.env.MONGOD_URL + '/mtharmen-image-search' mongoose.connect(mongodbUrl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('Connected to image-search'); routes(app, Bing, History); }); var port = process.env.PORT || 8080; app.listen(port, function() { console.log('Listening on port', port); }); // Closes database when node server.js stops process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Closing connection to mongoose database'); process.exit(0); }); }); <file_sep>/app/routes/searchApp.js 'use strict'; module.exports = function(app, Bing, History) { app.get('/imagesearch/:terms', function(req, res){ // Search var searchTerm = req.params.terms; var page = req.query.page || 10; // Number of results per page, default to 10 var offset = req.query.offset*page || 0; // Skip number results by page, default to 0 Bing.images(searchTerm, {top: page, skip: offset}, function(err, response, body){ if (err) return console.error(err); var images = body.d.results; // Filtering out excess data var printStuff = images.map(function(obj){ return { url: obj.MediaUrl, snippet: obj.Title, thumbnail : obj.Thumbnail.MediaUrl, context: obj.SourceUrl }; }); // Saving to database var d = new Date(); var newTerm = new History({ term: searchTerm, when: d.toISOString() }); newTerm.save(function (err, newTerm) { if (err) return console.error(err); console.log('Added new search ' + JSON.stringify({term: newTerm.term, when: newTerm.when})); }); res.set('Content-Type', 'text/plain').status(200); res.json(printStuff); }); }); // History app.get('/history', function(req, res){ // Filtering out _id, keeping term, when var query = History.find({}).select('term when -_id'); query.exec(function (err, past) { if (err) return console.error(err); res.set('Content-Type', 'text/plain').status(200); res.json(past); }); }); };
237ad87a2a5788ac5406869b741666dd209a80a1
[ "Markdown", "JavaScript" ]
3
Markdown
mtharmen/image-search
0ab08c43e9d4655a3b155fd5ae32a9719c9c2af4
215b71e27b4b71a1d000310b4b8a2ea11b7f618e
refs/heads/master
<file_sep>package ebay; import main.SignUp; import org.testng.annotations.Test; import reporting.TestLogger; public class SignUpTest extends SignUp { //*****positive testing //REGISTER to ebay @Test(priority = 1) public void ValidRegister() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); validRegister(); } //*****negative testing //register with no email @Test(priority = 5) public void NoEmailRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noEmailRegisterTry(); } //register with no password @Test(priority = 6) public void NoPassRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassRegisterTry(); } //register with no password, no email @Test(priority = 7) public void NoPassEmailRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassEmailRegisterTry(); } //register with no first name @Test public void NoFirstNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noFirstNameRegisterTry(); } //register with no last name @Test public void NoLastNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noLastNameRegisterTry(); } //register with no first name,last name @Test public void NoFirstLastNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noFirstLastNameRegisterTry(); } //register with no email,first name @Test public void NoEmailFirstNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noEmailFirstNameRegisterTry(); } //register with no password, first name @Test public void NoPassFirstNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassFirstNameRegisterTry(); } //register with no password, no email,first name @Test public void NoPassEmailFirstNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassEmailFirstNameRegisterTry(); } //register with no email,last name @Test public void NoEmailLastNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noEmailLastNameRegisterTry(); } //register with no password,last name @Test public void NoPassLastNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassLastNameRegisterTry(); } //register with no password, no email,no last name @Test public void NoPassEmailLastNameRegisterTry() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassEmailLastNameRegisterTry(); } //register with no input @Test public void NoInput() { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noInput(); } } <file_sep>package obamacare; import Base.mainClass; import org.testng.annotations.Test; public class test1 extends mainClass { //plans @Test public void testPlan(){ plans(); } } <file_sep>package ebay; import main.DBsearch; import org.testng.annotations.Test; public class DBsearchTest extends DBsearch { @Test public void testSearchByDB() throws Exception { searchByDB(); } } <file_sep>package main; public class MultipleExcelParameters { } <file_sep>package citybank; import TestBase.CityHomeLinks; import org.testng.annotations.Test; import reporting.TestLogger; public class CityHomeLinksTest extends CityHomeLinks { @Test public void whyCiti(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); WhyCiti(); } @Test public void RelBanking(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); relBanking(); } @Test public void BusinessBanking(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); businessBanking(); } @Test public void Rates(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); rates(); } @Test public void citiEasy() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); CitiEasy(); } @Test public void citiPrivate(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); CitiPrivate(); } @Test public void citiPrivateBank() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); CitiPrivateBank(); } } <file_sep>package Clicks; import base.CommonAPI; import org.openqa.selenium.JavascriptExecutor; import org.testng.annotations.Test; public class ableToChooseSeries extends CommonAPI { @Test public void clickonseries() throws InterruptedException { clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div[1]/div[2]/div/div/ul/li[1]/div/a"); ((JavascriptExecutor) driver).executeScript("scroll(0,2500)"); Thread.sleep(2000); clickByXpath("/html/body/main/div[7]/div/div/div[1]/section/div/div/div/div[2]/a/div[1]/img"); clickByXpath("//div[@class='__player-placeholder-play-button']"); Thread.sleep(3000); navigateBack(); ((JavascriptExecutor) driver).executeScript("scroll(500,0)"); } } <file_sep>package main; import base.CommonAPI; public class EbayHomeLinks extends CommonAPI { //Buy public void Buy(){ clickByLinkedText("Registration"); navigateBack(); clickByLinkedText("eBay Money Back Guarantee"); navigateBack(); clickByLinkedText("Bidding & buying help"); navigateBack(); clickByLinkedText("Stores"); } //Sell public void Sell(){ clickByLinkedText("Start selling"); navigateBack(); clickByLinkedText("Learn to sell"); navigateBack(); clickByLinkedText("Business sellers"); navigateBack(); clickByLinkedText("Affiliates"); navigateBack(); } //Tools & apps public void TnA(){ clickByLinkedText("Mobile apps"); navigateBack(); clickByLinkedText("Developers"); navigateBack(); clickByLinkedText("Security center"); navigateBack(); clickByLinkedText("eBay official time"); navigateBack(); clickByLinkedText("Site map"); navigateBack(); } //eBay companies public void companies(){ clickByLinkedText("eBay Classifieds"); navigateBack(); clickByLinkedText("See all companies"); navigateBack(); } } <file_sep>package TestBase; import base.CommonAPI; public class CityHomeLinks extends CommonAPI { //Why Citi public void WhyCiti(){ clickByLinkedText("Our Story"); navigateBack(); clickByLinkedText("Careers"); navigateBack(); clickByLinkedText("Benefits and Services"); navigateBack(); clickByLinkedText("Rewards"); navigateBack(); clickByLinkedText("Special Offers"); navigateBack(); } //Relationship Banking public void relBanking(){ clickByLinkedText("Citi Priority"); navigateBack(); clickByLinkedText("Citigold®"); navigateBack(); clickByLinkedText("Citi Global Banking"); navigateBack(); } //Business Banking public void businessBanking(){ clickByLinkedText("Small Business Accounts"); navigateBack(); clickByLinkedText("Commercial Accounts"); navigateBack(); } //Rates public void rates(){ clickByLinkedText("Personal Banking"); navigateBack(); clickByLinkedText("Credit Cards"); navigateBack(); clickByLinkedText("Mortgage"); navigateBack(); clickByLinkedText("Home Equity"); navigateBack(); } //Citi Easy public void CitiEasy(){ clickByLinkedText("Citi Easy DealsSMs"); } //Citi® Private Pass® public void CitiPrivate(){ clickByLinkedText("Citi® Private Pass®"); } //Citi® Private Pass® public void CitiPrivateBank(){ clickByLinkedText("Citi Private Bank"); } } <file_sep>package Base; import base.CommonAPI; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Actions; public class MainClass extends CommonAPI { public void login() { typeByXpath("//input[@name='email']","<EMAIL>"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); Actions action =new Actions(driver); action.sendKeys(Keys.ESCAPE).perform(); action.sendKeys(Keys.ESCAPE).perform(); } } <file_sep>package TestBase; import Base.SeeInfo; import org.testng.annotations.Test; import reporting.TestLogger; public class SeeInfoTest extends SeeInfo { @Test public void viewInfo1(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoNews();} @Test public void viewInfo2(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoInvesting();} @Test public void viewInfo3(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoLiveTv();} @Test public void viewInfo4(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoMakeIt();} @Test public void viewInfo5(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoMarket();} @Test public void viewInfo6(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoPro();} @Test public void viewInfo7(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoVideo();} @Test public void viewInfo8(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); seeInfoTest();} } <file_sep>package Base; import base.CommonAPI; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Actions; public class LogIn extends CommonAPI { public void login() { typeByXpath("//input[@name='email']","<EMAIL>"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); Actions action =new Actions(driver); action.sendKeys(Keys.ESCAPE).perform(); } public void loginEnter() { typeByXpath("//input[@name='email']","<EMAIL>"); typeByXpathNEnter("//input[@name='pass']","<PASSWORD>"); } public void loginPartEmail() { typeByXpath("//input[@name='email']", "testuserabcd13"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); } public void loginPartEmailEnter() { typeByXpath("//input[@name='email']","<EMAIL>"); typeByXpathNEnter("//input[@name='pass']","<PASSWORD>"); } public void loginUserId() { typeByXpath("//input[@name='email']","redn.black.315"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); } public void loginUserIdEnter() { typeByXpath("//input[@name='email']","redn.black.315"); typeByXpathNEnter("//input[@name='pass']","<PASSWORD>"); } //Negative Testing public void loginWithOutEmail() { typeByXpath("//input[@name='pass']", "<PASSWORD>"); clickByXpath("//input[@value='Log In']"); } public void loginWithOutpass() { typeByXpath("//input[@name='email']", "<EMAIL>"); clickByXpath("//input[@value='Log In']"); } public void loginWithWrongPass() { typeByXpath("//input[@name='email']", "<EMAIL>"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); } public void loginWithWrongEmail() { typeByXpath("//input[@name='email']", "wrong@gmail"); typeByXpath("//input[@name='pass']","<PASSWORD>"); clickByXpath("//input[@value='Log In']"); } } <file_sep>package facebook; import Base.SignUp; import org.testng.annotations.Test; public class TestSignUp extends SignUp { @Test public void logInAttempt() throws InterruptedException {register();} } <file_sep>package TestBase; import Base.ReadDataFromTable; import org.testng.annotations.Test; public class TestReadData extends ReadDataFromTable { @Test public void readDataTest(){ readData(); } @Test public void readDataTest1(){ readData1();} @Test public void readDataTest2(){ readData2();} } <file_sep>package ebay; import main.Messages; import org.testng.annotations.Test; import reporting.TestLogger; public class MessagesTest extends Messages { //go to my messages @Test(priority = 1) public void MyMessage() { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); myMessages(); } //create folder in messages @Test(priority = 2) public void FolderInMessages() { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); folderInMessages(); } } <file_sep>package Base; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import base.CommonAPI; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Search extends CommonAPI { //Search single iteam public void itemSearch(){ typeByXpathNEnter("//*[@placeholder='Search Quotes, News & Video']","gaming"); } @FindBy(xpath = "[@placeholder='Search Quotes, News & Video']") public static WebElement webElement1 ; public void lookForALaptop() { webElement1.sendKeys("laptop", Keys.ENTER); } //SearchMultipleItems @FindBy(xpath = "//*[@placeholder='Search Quotes, News & Video']") public WebElement webElement2; public void searchItems() { List<String> itemsList = new ArrayList<String>(); itemsList.add("gaming"); itemsList.add("social media"); itemsList.add("mobile"); for (String st : itemsList) { webElement2.sendKeys(st, Keys.ENTER); webElement2.clear(); } } public ArrayList<String> dataFromExcel(int colNo) throws IOException { FileInputStream filein = new FileInputStream("/Users/sreejon/IdeaProjects/WebAutomationTeam9/Cnbc/cnbcData/CnbcBook-1.xls"); HSSFWorkbook hss = new HSSFWorkbook(filein); HSSFSheet siter = hss.getSheet("CnbcBook"); Iterator<Row> rowIT =siter.iterator(); ArrayList<String> list = new ArrayList<>(); while(rowIT.hasNext()){ list.add(rowIT.next().getCell(colNo).getStringCellValue()); } return list; } public void excelTest() throws IOException { ArrayList<String> searchItemsEx = dataFromExcel(0); for (int i = 0; i < searchItemsEx.size(); i++) { typeByXpathNEnter("//*[@placeholder='Search Quotes, News & Video']", searchItemsEx.get(i)); clearInputByXpath("//*[@placeholder='Search Quotes, News & Video']"); } } public void work(){ Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("//i[@class='fa fa-user fa-2']"))).build().perform(); driver.findElement(By.xpath("//*[@id='unreg-user']/li/ul/li[1]")).click(); } }<file_sep>package TestBase; import Base.SignUp; import org.testng.annotations.Test; public class SignUpTest extends SignUp { @Test public void registerTest() throws InterruptedException { try { register(); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>package main; import base.CommonAPI; public class Login extends CommonAPI { //******positive testing //login to ebay public void login(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin div:nth-of-type(3) [size]","<EMAIL>"); typeByCss("#pri_signin .m12 [size]","testMySelenium123#@"); clickByXpath("/html//input[@id='sgnBt']"); } //*****negative testing //login with fake email public void fakeEmailLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin div:nth-of-type(3) [size]","<EMAIL>"); typeByCss("#pri_signin .m12 [size]","testMySelenium123#@"); clickByXpath("/html//input[@id='sgnBt']"); } //login with fake password public void fakePassLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin div:nth-of-type(3) [size]","<EMAIL>"); typeByCss("#pri_signin .m12 [size]","fake_pass"); clickByXpath("/html//input[@id='sgnBt']"); } //login with fake email,fake pass public void fakePassEmailLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin div:nth-of-type(3) [size]","<EMAIL>"); typeByCss("#pri_signin .m12 [size]","fake_pass"); clickByXpath("/html//input[@id='sgnBt']"); } //log in with no email public void noEmailLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin .m12 [size]","fake_pass"); clickByXpath("/html//input[@id='sgnBt']"); } //log in with no password public void noPassLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); typeByCss("#pri_signin div:nth-of-type(3) [size]","<EMAIL>"); clickByXpath("/html//input[@id='sgnBt']"); } //log in with no password, no email public void noPassEmailLoginTry(){ clickByXpath("//*[@id='gh-ug']/a"); clickByXpath("/html//input[@id='sgnBt']"); } } <file_sep>package Base; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Actions; import base.CommonAPI; public class SignUp extends CommonAPI { public void register() throws InterruptedException { Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("//i[@class='fa fa-user fa-2']"))).build().perform(); driver.findElement(By.xpath("//*[@id='unreg-user']/li/ul/li[1]")).click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } /*WebElement myFrame1=driver.findElement(By.xpath("//div[@id='surf-xdm']/iframe[@name='easyXDM_default7303_provider']")); driver.switchTo().frame(myFrame1); WebElement myFrame2=driver.findElement(By.xpath("//iframe[@id='display-frame']")); driver.switchTo().frame(myFrame2);*/ driver.switchTo().frame(1); //driver.switchTo().frame("display-frame"); driver.findElement(By.xpath("//input[@name='<EMAIL>']")).sendKeys("<EMAIL>",Keys.ENTER); driver.findElement(By.xpath("//input[@name='user_<EMAIL>']")).sendKeys("<PASSWORD>",Keys.ENTER); driver.findElement(By.xpath("//input[@name='user_<EMAIL>']")).sendKeys("testuser"); //driver.findElement(By.xpath("//span[text()='Sign up']")).click(); } } <file_sep>package ebay; import base.CommonAPI; import main.Search; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import reporting.TestLogger; public class SearchTest extends CommonAPI { //search for a laptop @Test public void searchLaptop(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); Search search = PageFactory.initElements(driver, Search.class); search.lookForALaptop(); } //search for a laptop and define group apple @Test public void group(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); Search search = PageFactory.initElements(driver, Search.class); search.group(); } //SearchMultipleItems @Test public void SearchMultipleItems() { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); Search search = PageFactory.initElements(driver, Search.class); search.searchItems(); } } <file_sep>package Base; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.testng.annotations.Test; import base.CommonAPI; public class CountryDropDown extends CommonAPI { @Test public void dropDownCountry(){ clickByXpath("/html//main/div[11]/div/div//ul[@class='modules/FooterLinks--links modules/FooterLinks--topLinks']//a[@href='https://hbocareers.com/']"); switchTabs(0,1); driver.findElement(By.xpath("/html/body/main/section[1]/div/div[2]/div/form/table/tbody/tr/td[1]/input")).sendKeys("SOFTWARE ENGINEER",Keys.ENTER); driver.manage().window().fullscreen(); clickByXpath("//*[@id=\"location-selects\"]/button[1]"); driver.manage().window().fullscreen(); clickByXpath("/html/body/div[12]/ul/li[2]/label/span"); clickByXpath("//*[@id=\"location-selects\"]/button[2]"); //clickByXpath("/html/body/div[7]/div/ul/li[3]/a/span"); clickByXpath("/html/body/div[11]/div/ul/li[2]/a"); clickByXpath("/html/body/div[11]/ul/li[3]/label/span"); clickByXpath("//*[@id=\"inputs-wrap\"]/div[3]/div[3]/button"); } } <file_sep>package Base; import base.CommonAPI; public class SignUp extends CommonAPI { public void register() throws InterruptedException { typeByXpath("//input[@class='inputtext _58mg _5dba _2ph-' and @name='firstname']","test"); typeByXpath("//input[@class='inputtext _58mg _5dba _2ph-' and @name='lastname']","user"); typeByXpath("//input[@class='inputtext _58mg _5dba _2ph-' and @name='reg_email__']","<EMAIL>"); wait(2); typeByXpath("//*[@id='u_0_l']","<EMAIL>"); typeByXpath("//input[@class='inputtext _58mg _5dba _2ph-' and @name='reg_passwd__']","<PASSWORD>"); clickByXpath("//select[@name='birthday_month']"); clickByXpath("//*[@id='month']/option[10]"); clickByXpath("//select[@name='birthday_day']"); clickByXpath("//*[@id='day']/option[17]"); clickByXpath("//select[@name='birthday_year']"); clickByXpath("//*[@id='year']/option[40]"); clickByXpath("//*[@id='u_0_b']"); clickByXpath("websubmit"); } } <file_sep>package main; import base.CommonAPI; import org.openqa.selenium.By; public class Messages extends CommonAPI { //go to my messages// public void myMessages(){ Login login = new Login(); login.login(); mouseHoverNClickbyXC("//*[@id='gh-eb-My']/div/a[1]","Messages"); } //add a folder inside messages public void folderInMessages(){ myMessages(); clickByXpath("//*[@id='adf']"); driver.findElement(By.xpath("//*[@id='-1_inp_inp']")).clear(); typeByXpath("//*[@id='-1_inp_inp']","folder1"); } } <file_sep>package facebook; import DataDrivenBase.DataWork; import org.testng.annotations.Test; import java.io.IOException; public class TestDataWork extends DataWork { @Test public void excelWork() throws IOException { excelData(); } } <file_sep>package ebay; import main.Login; import org.testng.annotations.Test; import reporting.TestLogger; public class LoginTest extends Login { //******positive testing //login to ebay @Test(priority = 1) public void Login(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); login(); } //*****negative testing //login with fake email @Test(priority = 2) public void FakeEmailLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); fakeEmailLoginTry(); } //login with fake password @Test(priority = 3) public void FakePassLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); fakePassLoginTry(); } //login with fake email,fake pass @Test(priority = 4) public void FakePassEmailLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); fakePassEmailLoginTry(); } //log in with no email @Test(priority = 5) public void NoEmailLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noEmailLoginTry(); } //log in with no password @Test(priority = 6) public void NoPassLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassLoginTry(); } //log in with no password, no email @Test(priority = 7) public void NoPassEmailLoginTry(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); noPassEmailLoginTry(); } } <file_sep>package TestBase; import base.CommonAPI; public class walmartMainClass extends CommonAPI { //search public void search(){ typeByXpathNEnter("//input[@class='GlobalHeaderSearchbar-input header-GlobalSearch-input']","fishing rod"); } //signIn public void signIn(){ //Actions action=new Actions(driver); //action.moveToElement(driver.findElement(By.xpath("//html//button[1]/div[1]/span[1]"))).build().perform(); clickByXpath("//span[@class='elc-icon elc-icon-user-nav BubbleButton-icon']"); clickByXpath(" //div[text()='Sign In']"); } } <file_sep>package Clicks; import base.CommonAPI; import org.testng.annotations.Test; public class ableToChooseMovie extends CommonAPI { @Test public void AbleToclickonmovies(){ clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div[1]/div[2]/div/div/ul/li[2]/div/a"); clickByXpath("/html/body/main/div[2]/div/div/div[1]/section/div/div/div/div[1]/a/div[1]/img"); clickByXpath("//div[@class='__player-placeholder-play-button'][1]"); } } <file_sep>package google.api; import base.CommonAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class GoogleSheetPageCnbc extends CommonAPI { // get actual result public void searchGaming(){ typeByXpathNEnter("//*[@placeholder='Search Quotes, News & Video']","gaming"); } //get the item info public List<String> getLinkName(){ List<WebElement> linkLists= driver.findElements(By.xpath("//a[@class='dy<EMAIL>Monitor']")); List<String> linkname=new ArrayList<>(); for(int i=0;i<5;i++){ System.out.println(linkname.add(linkLists.get(i).getText())); } return linkname; } } <file_sep>package Base; import base.CommonAPI; public class mainClass extends CommonAPI { public void CheckCreditCard(){ clickByLinkedText("Credit Cards"); clickByXpath("//*[@id='cA-DD-taskbarMenu']/div[1]/div[1]/div/a"); } public void compareCreditCards() throws InterruptedException { CheckCreditCard(); clickByCss(".citi-prestige-card .cA-DD-result-chkbox"); clickByXpath("//*[@id='compareWidget']/div[2]/div[1]/a[1]"); } } <file_sep>package Base; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import base.CommonAPI; import java.util.ArrayList; import java.util.List; public class mainClass extends CommonAPI { public void searchItems() { clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div"); List<String> itemsList = new ArrayList<String>(); itemsList.add("West world"); itemsList.add("Kong"); itemsList.add("Fantastic Beast and Where TO Find Them"); for (String loopstring : itemsList) { driver.findElement(By.xpath("/html//main[@class='wrapperMain']/div[1]/div/div//div[@class='components/Search--searchInputContainer']/input[@type='text']")).sendKeys(loopstring, Keys.ENTER); clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div"); } } } <file_sep>package citybank; import org.testng.annotations.Test; public class testDebitCards { @Test public void clickdebitcardTag() { //clickButtonByXpath("#creditCards>a"); } @Test public void searchByCSS() { //searchByCSS("#cA-cardsUseridMasked","UserID"); } @Test public void searchByXpath(){ //searchByXpath(".//*[@id='PASSWORD']","password"); } @Test public void clickButtonByCSS(){ //searchByCSS(".cA-cardsLoginSubmit.cA-DD-singon-buttom"); } @Test public void clickButtonByXpath(){ //clickButtonByXpath(".cA-DD-browseCards"); } } <file_sep>package main; import base.CommonAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class GoogleSheet extends CommonAPI { public void searchItems(){ typeByXpathNEnter("//input[@id='gh-ac']","Java Books"); } public List<String> getBooksName(){ List<WebElement> bookList = driver.findElements(By.className("s-item__title")); List<String> bookname = new ArrayList<>(); for(int i = 0;i<=3;i++){ System.out.println(bookname.add(bookList.get(i).getText())); } return bookname; } } <file_sep>package Clicks; import base.CommonAPI; import org.testng.annotations.Test; public class clickSearch extends CommonAPI { @Test public void clicksearch(){ //mainClass obj = new mainClass(); //ss("/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div"); clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div/div[2]/div/div/div"); } } <file_sep>package Base; import org.openqa.selenium.By; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.Test; import base.CommonAPI; import java.util.concurrent.TimeUnit; public class mouseMovement extends CommonAPI { @Test public void movemouse() throws InterruptedException { clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div/div[3]/ul/li[2]/div/a"); clickByXpath("/html/body/main/div[2]/div/div/div[1]/div/div[1]/ul/li[10]/span[1]"); driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS); Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("/html/body/main/div[2]/div/div/div[1]/div/div[2]/div/div[2]/div/ul/span/li[1]/ul/li[15]"))).build().perform(); Thread.sleep(2000); action.moveToElement(driver.findElement(By.xpath("/html/body/main/div[2]/div/div/div[1]/div/div[2]/div/div[2]/div/ul/span/li[2]/ul/li[14]/div[2]"))).build().perform(); Thread.sleep(2000); action.moveToElement(driver.findElement(By.xpath("/html/body/main/div[2]/div/div/div[1]/div/div[2]/div/div[2]/div/ul/span/li[2]/ul/li[13]"))).build().perform(); Thread.sleep(2000); action.moveToElement(driver.findElement(By.xpath("/html/body/main/div[2]/div/div/div[1]/div/div[2]/div/div[2]/div/ul/span/li[1]/ul/li[12]"))).build().perform(); Thread.sleep(2000); action.moveToElement(driver.findElement(By.xpath("/html/body/main/div[2]/div/div/div[1]/div/div[2]/div/div[2]/div/ul/span/li[1]/ul/li[11]"))).build().perform(); } } <file_sep>package Base; import base.CommonAPI; public class MainClass extends CommonAPI { public void homeUs(){ mouseHoverNClickbyXC("//span[contains(text(),'HOME U.S.')]","U.S EDITION"); navigateBack(); mouseHoverNClickbyXC("//span[contains(text(),'HOME U.S.')]","INTL EDITION"); } public void newss(){ mouseHoverNClickbyXC("//a[text()='News'][1]","ECONOMY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","FINANCE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","HEALTH CARE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","REAL ESTATE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","WEALTH"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","AUTOS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","EARNINGS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","ENERGY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","LIFE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","MEDIA"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","POLITICS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","RETAIL"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","COMMENTARY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","SPECIAL REPORTS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","ASIA"); navigateBack(); mouseHoverNClickbyXC("//a[text()='News'][1]","EUROPE"); navigateBack(); //mouseHoverNClickbyXC("//a[text()='News'][1]","CFO COUNCIL"); } public void markets(){ mouseHoverNClickbyXC("//a[text()='Markets'][1]","PRE-MARKETS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","U.S"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","ASIA"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","EUROPE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","STOCKS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","COMMODITIES"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","CURRENCIES"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","CRYPTOCURRENCY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","BONDS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","FOUNDS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Markets'][1]","ETFs"); } public void investing(){ mouseHoverNClickbyXC("//a[text()='Investing'][1]","TRADING NATION"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","TRADER TALK"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","FINANCIAL ADVISORS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","PERSONAL FINANCE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","ETS STREET"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","FUTURES NOW"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","OPTIONS ACTION"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","PORTFOLIO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","WATCHLIST"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","STOCK SCREENER"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Investing'][1]","FUND SCREENER"); } public void tech(){ mouseHoverNClickbyXC("//a[text()='Tech'][1]","MOBILE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Tech'][1]","SOCIAL MEADIA"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Tech'][1]","ENTERPRISE"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Tech'][1]","GAMING"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Tech'][1]","CYBERSECURITY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Tech'][1]","TECH GUIDE"); } public void makeIt(){ mouseHoverNClickbyXC("//a[text()='Make It'][1]","ENTERPRENEURS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Make It'][1]","LEADERSHIP"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Make It'][1]","CAREERS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Make It'][1]","MONEY"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Make It'][1]","SPECIALS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Make It'][1]","PRIMETIME"); } public void video(){ mouseHoverNClickbyXC("//a[text()='Video'][1]","TOP VIDEO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","LATEST VIDEO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","U.S VIDEO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","ASIA VIDEO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","EUROPE VIDEO"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","CEO INTERVIEWS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","ANALYST INTERVIEWS"); navigateBack(); mouseHoverNClickbyXC("//a[text()='Video'][1]","FULL EPISODES"); } public void shows(){ mouseHoverNClickbyXC("//a[text()='Shows'][1]","WATCH LIVE"); } public void subscribe(){ mouseHoverByXpath("//li[@id='bx-subscribe-anchor-342017']"); } public void pro(){ mouseHoverNClickbyXC("//a[text()='Pro'][1]","TAKE A TOUR"); } public void liveTv(){ mouseHoverNClickbyXC("//a[text()='LIVE TV']","WATCH CNBC TV"); } public void watchList(){ mouseHoverByXpath("//a[text()='WATCHLIST']"); } public void breakingNews(){ clickByXpath("//div[contains(text(),'Breaking News')]"); } public void itemSearch(){ typeByXpathNEnter("//*[@placeholder='Search Quotes, News & Video']","VERIZON"); clickByXpath("//*[@class='fa fa-Search fa-2']"); } public void work(){ mouseHoverByXpath("//i[@class='fa fa-user fa-2']"); clickByXpath("//*[@id='unreg-user']/li/ul/li[1]"); } public void work2() throws InterruptedException { mouseHoverByXpath("//i[@class='fa fa-user fa-2']"); clickByXpath("//*[@id='signin']"); Thread.sleep(10000); typeByXpath("//input[@id='input_username']","tester1"); } public void career(){ mouseHoverByXpath("//a[text()='Make It'][1]"); clickByXpath("//a[text()='Careers']"); } } <file_sep>package TimelinesScenario; import Base.MainClass; public class ScenarioMainClass extends MainClass { public void SearchFunction(){ login(); clickByXpath("//input[@class='_1frb']"); typeByXpathNEnter("//input[@class='_1frb']","<NAME>"); } public void friendRequest(){ login(); typeByXpathNEnter("//input[@class='_1frb']","<NAME>"); clickByXpath("//div[@class='_4xjz'][contains(text(),'People')]"); clickByXpath("//*[@class='_42ft _4jy0 FriendRequestAdd addButton _4jy3 _517h _51sy'][1]"); } public void postAstatus(){ login(); clickByXpath("//a[@class='_2s25'][contains(text(),'Home')]"); typeByXpath("//textarea[@class='_3en1 _480e navigationFocus']","this is a test"); clickByXpath("//button[@class='_1mf7 _4jy0 _4jy3 _4jy1 _51sy selected _42ft']"); } public void deleteAstatus(){ login(); clickByXpath(""); } } <file_sep>package Base; import base.CommonAPI; public class ReadDataFromTable extends CommonAPI { public void readData(){ String cellData=getTextByCss(".data.quoteTable"); System.out.println(cellData); } public void readData1(){ String cellData1=getTextByCss(".data.quoteTable tr:nth-child(1)"); System.out.println(cellData1); } public void readData2(){ String cellData2=getTextByCss(".data.quoteTable tr:nth-child(1) td:nth-child(2)"); System.out.println(cellData2); } } <file_sep>package TestBase; import Base.Search; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import reporting.TestLogger; import java.io.IOException; public class SearchTest extends Search { @Test public void searchMultipleIteams() { Search sc = PageFactory.initElements(driver, Search.class); sc.searchItems(); } @Test public void searchOneItem(){ searchItems();} @Test public void exTest() throws IOException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); excelTest(); } } <file_sep>package ebay; import main.MainEbay; import org.openqa.selenium.JavascriptExecutor; import org.testng.annotations.Test; import reporting.TestLogger; public class TestEbay extends MainEbay { @Test public void mouse(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); mouseHoverByXpath(); } //view multiple items @Test public void view(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); viewMultipleByCSS(); } //extended search @Test public void ExtendedSearch() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); xtendedSearches(); } //search problems @Test public void Problems() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); searchProblems(); } //search different parameters @Test public void searcfDifferent(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); searchWithDifferentRequirements(); } //edit categories @Test public void editcategoriess(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); editCategories(); } //test tab @Test public void testNewTab(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); newTab(); } //use TAB @Test public void testTabButton() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); tabUse(); } //using scrolling @Test public void scroolupanddown() throws InterruptedException { TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); ((JavascriptExecutor) driver).executeScript("scroll(0,2000)"); Thread.sleep(2000); ((JavascriptExecutor) driver).executeScript("scroll(50,0)"); } //Check Ebay Motors Mousehover and click by linkText @Test public void testMotors(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); motors(); } //Check Ebay Fashion Mousehover and click by linkText @Test public void testFashion(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); fashion(); } //Check Ebay Electronics Mousehover and click by linkText @Test public void testElectronics(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); electronics(); } //Check Ebay Collectiables & art Mousehover and click by linkText @Test public void testCollectiablesNart(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); collectiablesNart(); } //Check Ebay Home & Garden Mousehover and click by linkText @Test public void testHomeNgarden(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); homeNgarden(); } //Check Ebay Sporting Goods Mousehover and click by linkText @Test public void testSportingGoods(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); sportingGoods(); } //Check Ebay Toys Mousehover and click by linkText @Test public void testToys(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); toys(); } //Check Ebay Business & Industrial Mousehover and click by linkText @Test public void testBusinessNindustrial(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); businessNindustrial(); } //Check Ebay Music Mousehover and click by linkText @Test public void testMusic(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); music(); } //Check Ebay Deals Mousehover and click by linkText @Test public void testDeals(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); deals(); } //Check Ebay Under $10 Mousehover and click by linkText @Test public void testUnder$10(){ TestLogger.log(getClass().getSimpleName() + ": " + convertToString(new Object(){}.getClass().getEnclosingMethod().getName())); under$10(); } } <file_sep>package Clicks; import Base.mainClass; import org.testng.annotations.Test; public class TopOptions extends mainClass { @Test public void series() throws InterruptedException {} @Test public void Movies(){;} @Test public void Kids(){} @Test public void clickcareers(){ clickByLinkedText("CAREERS"); } }<file_sep>package Clicks; import base.CommonAPI; import org.testng.annotations.Test; public class ableToChooseBoxing extends CommonAPI { @Test public void AbleToclickonboxing(){ clickByXpath("//a[@href='/boxing'][1]"); clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div[3]/div/div/div/ul/li[2]/div/a"); clickByXpath("/html/body/main/div[1]/div/div/header/div[1]/div[3]/div/div/div/ul/li[2]/div[2]/ul/li[1]/a"); } } <file_sep>package TestScenarioTimelines; import Base.LogIn; import TimelinesScenario.ScenarioMainClass; import org.testng.annotations.Test; public class TestSearch extends ScenarioMainClass { //@Test public void test1(){SearchFunction();} //@Test public void test2(){friendRequest();} @Test public void test3(){postAstatus();} }
6ed8a6c7702b795a23888b488a117c63847c0c3f
[ "Java" ]
41
Java
Syedhussain102/WebAutomationTeam9
cccbd6149bdd0164278996fbead082f2b2ad8559
6c33c98c6912387cde54c07348a0659d8683ba34
refs/heads/master
<file_sep>カード決済手数料込み計算機 ========================== Square などで支払いを受けるとき、 手数料を引いてちょうど目的の金額になるように請求額を計算します。 http://komi.msng.info/ <file_sep>$('#methods a').click(function() { $('#methods').hide(); $('#calc').show(); var method = $(this).find('dt').text(); var fee = $(this).find('dd').text().replace('%', ''); $('#method-name span').text(method); $('#fee').val(fee); var amount = $('#amount'); if (amount.val()) { $('#do-calc').click(); } else { amount.focus(); } return false; }); $('#change').click(function() { $('#result').hide(); $('#calc').hide(); $('#methods').show(); return false; }); $('#do-calc').click(function() { var method = $('#method-name span').text(); var fee = $('#fee').val(); var amount = $('#amount').val(); var tax = Math.ceil(amount * (1 / (1 - fee / 100))); $('#result-charge').text(tax + '円'); $('#result-method span').text(method); $('#result-fee').text((tax - amount) + '円'); $('#result').show(); return false; });
4e6fdd1b6ddce239a9c135b1eb98e2ecb3f5528c
[ "Markdown", "JavaScript" ]
2
Markdown
msng/komi
b5ddcdd4c6c14cc2dd77d07e6e36899353097f7f
1ecfff79415d43d0263dd08f74a41fc8d43c92f6
refs/heads/master
<repo_name>JonahJana/lesson1<file_sep>/apps.js //const stuff that can be copy pasta //------------------------------------------ const express = require('express'); const app = express(); const https = require("http"); const server = http.createServer(app); const LISTEN_PORT = 8080; //------------------------------------------ //these functions run befor the page is "served" app.use(express.static(__dirname + "/public")); //route for accesing page app.get("/", function(req, res){ res.sendfile(__dirname + 'public.index.html'); // send the index.html }); //start server server.listen(LISTEN_PORT); console.log('listening to port' + LISTEN_PORT);
21a48a1347689d1ecf91850ce7c4ace15562090f
[ "JavaScript" ]
1
JavaScript
JonahJana/lesson1
6af3083637ac4a0938b18105ff5de0c175549db7
a1f5ca21f75f02ff76c39a14e522b0cd9ca4a62f
refs/heads/master
<file_sep>import frappe #send_emails to attendees for conference invitation @frappe.whitelist() def send_invitation_emails(Name,Attendee,Agenda,Venue): print "_________________mailing____________" url="http://localhost:8000/desk#Calendar/Event" msg = frappe.render_template("templates/email/conference_booking.html", {"Name":Name,"Attendee":Attendee,"Agenda": Agenda,"Venue": Venue,"base_url":url}) frappe.sendmail( recipients=Attendee, sender=frappe.session.user, subject="Conference Invitation", message=msg ) print "_________________mail_ sent____________" #send_emails to creater for conference confirmation @frappe.whitelist() def send_confirmation_emails(Name,Agenda,Venue,email): print "_________________mailing____________" msg = frappe.render_template("templates/email/conference_confirmation.html", {"Name":Name,"Agenda": Agenda,"Venue": Venue,"email": email}) frappe.sendmail( recipients=email, sender=frappe.session.user, subject="Conference Confirmation", message=msg ) print "_________________mail_ sent__to creator__________" # For displaying conferences on calendar @frappe.whitelist() def get_conference(start,end,filters=None): if not frappe.has_permission("Conference booking","read"): raise frappe.PermissionError print "\n\nstart=",start print "\n\nend=",end cal=frappe.db.sql("""select timestamp(date, from_time) as start_date, timestamp(date, to_time) as end_date, name, workflow_state from `tabConference booking` where workflow_state='Booked' and timestamp(date,from_time) between %(start)s and %(end)s or timestamp(date,to_time) between %(start)s and %(end)s """,{ "start":start, "end":end },as_dict=True,debug=1,update={"allDay": 0}) print "\ndetails=",cal return cal
f088eaefd34d6fcb714d780707914b1291d77785
[ "Python" ]
1
Python
yashodhank/conference_management
caa34a947881dfe8ccb68a2b8e449008bd9ced47
3c5e39e37fcf3ed927536d448ac4e3de1d8f4905
refs/heads/master
<file_sep>import decimal import json from django.forms.models import model_to_dict from django.http import HttpResponse from django.shortcuts import get_object_or_404 import datetime_to_decimal as dt import models def rsp(data): return HttpResponse(json.dumps(data), content_type="application/json") def _get_model_by_id(klass, model_id): model = get_object_or_404(klass, id=model_id) model_dict = _convert_model(model) return model_dict def list_usage_launches(request): filter_args = {} if 'instance' in request.GET: filter_args['instance'] = request.GET['instance'] if len(filter_args) > 0: objects = models.InstanceUsage.objects.filter(**filter_args) else: objects = models.InstanceUsage.objects.all() dicts = _convert_model_list(objects.order_by("launched_at")) return rsp({'launches': dicts}) def get_usage_launch(request, launch_id): return rsp({'launch': _get_model_by_id(models.InstanceUsage, launch_id)}) def list_usage_deletes(request): filter_args = {} if 'instance' in request.GET: filter_args['instance'] = request.GET['instance'] if len(filter_args) > 0: objects = models.InstanceDeletes.objects.filter(**filter_args) else: objects = models.InstanceDeletes.objects.all() dicts = _convert_model_list(objects.order_by("launched_at")) return rsp({'deletes': dicts}) def get_usage_delete(request, delete_id): return rsp({'delete': _get_model_by_id(models.InstanceDeletes, delete_id)}) def list_usage_exists(request): filter_args = {} if 'instance' in request.GET: filter_args['instance'] = request.GET['instance'] if len(filter_args) > 0: objects = models.InstanceExists.objects.filter(**filter_args) else: objects = models.InstanceExists.objects.all() dicts = _convert_model_list(objects.order_by("id")) return rsp({'exists': dicts}) def get_usage_exist(request, exist_id): return rsp({'exist': _get_model_by_id(models.InstanceExists, exist_id)}) def _convert_model(model): model_dict = model_to_dict(model) for key in model_dict: if isinstance(model_dict[key], decimal.Decimal): model_dict[key] = str(dt.dt_from_decimal(model_dict[key])) return model_dict def _convert_model_list(model_list): converted = [] for item in model_list: converted.append(_convert_model(item)) return converted
36f6c74e2cf5a65c75a68d565cf2f7ef3d2180dd
[ "Python" ]
1
Python
hungld/stacktach
29ec82e186fdc32bc67c94eeb07197ee58f88871
fbaf58295cd54be0a5e9a038455734c880ad6d2f
refs/heads/master
<file_sep>#include<stdio.h> #include<string.h> #define num 1<<20 #define DUMBCOPY for (i = 0; i < num; i++) \ destination[i] = source[i] #define SMARTCOPY memcpy(destination, source, num) int main() { char source[num], destination[num]; int i, j; for (j = 0; j < 500; j++) SMARTCOPY; // DUMBCOPY; return 0; }
9dd8e30da1392cdf785a647e8eee256749634b22
[ "C" ]
1
C
tomxuetoy/cache_effect
81c906a027745208d336da29d83eafa7e5e1a1ee
085e25b1a4a7aec38a8faf1049276942fd722bdf
refs/heads/master
<repo_name>SrivatsavG/calculator-nodejs<file_sep>/README.md # calculator-nodejs **BACKEND**: NodeJS <br/> **FRONTEND**: EJS <br/> **DATABASE**: MongoDB <br/> **HOSTED ON**: Heroku <br/> ### Details Basic calculator that stores the last 10 calculations performed by its users. ### Website https://srivatsav-calculator.herokuapp.com/calculate <file_sep>/models/calculation.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const calculationSchema = new Schema({ equation : {type:String,required:true} }) module.exports = mongoose.model("Calculation",calculationSchema);<file_sep>/public/js/calc.js //function that display value function dis(val) { document.getElementById("equation").value += val; } //function that evaluates the digit and return result // function solve() { // let equation = document.getElementById("equation").value; // try { // let result = eval(x); // if (result === undefined) { // return; // } else { // //WRITE TO DB // document.getElementById("equation").value = result; // var xhttp = new XMLHttpRequest(); // xhttp.open("POST", "/calculate", true); // xhttp.send(equation+"="+result); // } // } catch (err) { // } // } //function that clear the display function clr() { document.getElementById("equation").value = ""; } <file_sep>/controllers/home.js const Calculation = require("../models/calculation"); exports.showCalculator = async (req, res, next) => { var calculations = []; try { calculations = await (await Calculation.find()).reverse(); res.render("home.ejs", { calculations: calculations, result: "", }); } catch (err) { const error = new Error(err); error.httpStatusCode = 500; return next(error); } }; exports.postCalculator = async (req, res, next) => { let equation = req.body.equation; let result = ""; let calculations = []; console.log("EQUATION IS ", equation); try { let result = eval(equation); console.log("RESULT IS", result); if (result === undefined) { calculations = await (await Calculation.find()).reverse(); res.render("home.ejs", { calculations: calculations, result: equation, error: "Invalid equation", }); } else { const calc = new Calculation({ equation: equation + "=" + result, }); const calcResult = await calc.save(); calculations = await (await Calculation.find()).reverse(); res.render("home.ejs", { calculations: calculations, result: result }); } } catch (err) { const error = new Error(err); console.log(err); error.httpStatusCode = 500; return next(error); } };
7f4042f3fae46866f1e90b44e1363c51ce33d1dd
[ "Markdown", "JavaScript" ]
4
Markdown
SrivatsavG/calculator-nodejs
8cb7a71705de1ac8371fb1a46d8670aa94717969
69891def2ca8bad4bf0ee75073c4fd50f57658c6
refs/heads/master
<repo_name>arasouli91/omniChess<file_sep>/README.md ### OmniChess <file_sep>/Board.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Advertisements; public class Board : MonoBehaviour { private readonly int ROWS = Settings.ROWS | 8, COLS = Settings.COLS | 8; Square[][] Grid; private int selectionX = -1, selectionY = -1, selectionX1 = -1, selectionY1 = -1, revivalPosX = -1, revivalPosY = -1; private GameObject selection = null, selectedPiece = null; private int teamTurn = 1; // -1 for white, 1 for black // Used to determine whether or not a move can be made private Dictionary<int, HashSet<int>> validLocations; // Count of dead units for each player private int[] deadCount; private GameObject blackSquare, whiteSquare; // Base pieces initially off screen, duplicated for board setup GameObject[] basePieces; // The actual pieces on the board private List<GameObject>[] thePieces; private GameObject cam; private Vector3 camDefaultPos, camDefaultRot; private bool checkedFlag = false, reviveFlag = false, wokeFlag = false, revivedFlag = false, highLit = false; [SerializeField] // Square materials private Material a1,a2,a3,a4; [SerializeField] private GameObject blackWins, whiteWins, gameOver; private King[] kings; // Always need to know where each player's king is private bool[] kingPlaced; private readonly int BLACK = 0, WHITE = 1, BLACK_KING = 5, WHITE_KING = 10; void PlacePiece(GameObject piece, int row, int col) => Grid[row][col].PieceHeld = Object.Instantiate(piece, new Vector3(col, 1, row), Quaternion.identity); void Start () { #region Init #if UNITY_ANDROID QualitySettings.vSyncCount = 0; Application.targetFrameRate = 60; QualitySettings.antiAliasing = 0; Screen.sleepTimeout = SleepTimeout.NeverSleep; #endif Settings.HoverFlag = true; Grid = new Square[ROWS][]; basePieces = new GameObject[12]; thePieces = new List<GameObject>[2]; thePieces[BLACK] = new List<GameObject>(); thePieces[WHITE] = new List<GameObject>(); kings = new King[2]; kingPlaced = new bool[2]; deadCount = new int[2]; EventCallbacks.ReviveEvent.RegisterListener(HandleRevival); // Find initial squares and units blackSquare = GameObject.Find("bBlackSquare1"); whiteSquare = GameObject.Find("bWhiteSquare1"); { basePieces[0] = GameObject.Find("Black Pawn"); // All these will be deleted, because their positions are variable they were initial off screen basePieces[6] = GameObject.Find("White Pawn"); basePieces[7] = GameObject.Find("White Rook"); basePieces[8] = GameObject.Find("White Knight"); basePieces[9] = GameObject.Find("White Bishop"); basePieces[10] = GameObject.Find("White King"); basePieces[11] = GameObject.Find("White Queen"); basePieces[1] = GameObject.Find("Black Rook"); basePieces[2] = GameObject.Find("Black Knight"); basePieces[3] = GameObject.Find("Black Bishop"); basePieces[4] = GameObject.Find("Black Queen"); basePieces[5] = GameObject.Find("Black King"); } // Auto generate back row sequence, MUST have even cols // The values placed in BackRow[] correspond to the black pieces held in pieces[] // the white pieces are determined by shifting 6 indices var BackRow = new int[COLS]; for(int i = 0; i < (COLS-2)/2; ++i) { // Pieces placed symmetrically BackRow[i] = BackRow[COLS - i - 1] = (i)%3 + 1; // loop through possible pieces } BackRow[(COLS / 2) - 1] = 4; BackRow[(COLS / 2)] = 5; #endregion Init #region Board Setup // Place all squares and pieces on board for (int row = 0; row < ROWS; row++) { Grid[row] = new Square[COLS]; for (int col = 0; col < COLS; col++) { PlaceSquare(row, col); // Place pieces if (Settings.IsRandomMode) RandomPlacement(row, col); else StandardPlacement(BackRow, row, col); // Handle setting team and adding to list FinalizePiece(row, col); } } #endregion Board Setup #region Setup Other Pieces //// Position/resize all other objects in scene //// // Camera and lights need to be positioned accordingly. // Directional light and camera need to be positioned in middle of platform // Find camera and lights cam = GameObject.Find("Main Camera"); camDefaultPos = cam.transform.localPosition; camDefaultRot = cam.transform.eulerAngles; var l = GameObject.Find("Directional Light"); var l1 = GameObject.Find("Point Light"); var l2 = GameObject.Find("Point Light Top"); // Give them initial positions. // Orderded by 3 on bottom left 2 top left. 3 right bottom 2 right top. 1 white bottom/top. 1 black bottom/top GameObject[] lights = new GameObject[14]; lights[0] = l1; lights[3] = l2; { lights[1] = Object.Instantiate(l1, new Vector3(-5, 1, 4), Quaternion.identity); lights[2] = Object.Instantiate(l1, new Vector3(-5, 1, 13), Quaternion.identity); lights[4] = Object.Instantiate(l1, new Vector3(-1, 5, 10), Quaternion.identity); lights[5] = Object.Instantiate(l1, new Vector3(15, 1, 4), Quaternion.identity); lights[6] = Object.Instantiate(l1, new Vector3(15, 1, 13), Quaternion.identity); lights[7] = Object.Instantiate(l1, new Vector3(15, 1, -5), Quaternion.identity); lights[8] = Object.Instantiate(l1, new Vector3(10, 5, 0), Quaternion.identity); lights[9] = Object.Instantiate(l1, new Vector3(10, 5, 10), Quaternion.identity); lights[10] = Object.Instantiate(l1, new Vector3(5, 1, 15), Quaternion.identity); lights[11] = Object.Instantiate(l1, new Vector3(5, 5, 10), Quaternion.identity); lights[12] = Object.Instantiate(l1, new Vector3(5, 1, -5), Quaternion.identity); lights[13] = Object.Instantiate(l1, new Vector3(5, 5, 0), Quaternion.identity); } // Adjust all side and corner pieces // Position camera and lights int cDiff = 0 , rDiff = 0; if (COLS > 8) { cDiff = COLS - 8; } if (ROWS > 8) { rDiff = ROWS - 8; GameObject bin = GameObject.Find("CartWhite"); bin.transform.localPosition = new Vector3(-6.66f, -1, ROWS); } if (COLS>8 || ROWS > 8) { // Collision plane GameObject plane = GameObject.Find("Plane"); plane.transform.localPosition = new Vector3(COLS / 2f - .5f, 0.5f, ROWS / 2f - .5f); plane.transform.localScale = new Vector3(COLS / 10f, 0.01f, ROWS / 10f); // Lights Orderded by 3 on bottom left 2 top left. 3 right bottom 2 right top. 1 white bottom/top. 1 black bottom/top // need to move: [1,2]U[4] pos Z --- [6,7]U[9] pos Z & pos X // 5,8 pos X --- 10,11 pos X,Z ---- 12,13 pos X // Adjust all affected side pieces, and platform // bSideVertical needs to scale by diff and translate by 0.5*(diff) into pos. Z GameObject cur = GameObject.Find("bSideVertical"); cur.transform.localPosition += new Vector3(0, 0, 0.5f*(rDiff)); cur.transform.localScale += new Vector3(rDiff,0,0); for(int i = 1; i <5; ++i) { if (i != 3) lights[i].transform.localPosition += new Vector3(0, 0, 0.5f * (rDiff)); } // bCornerLeftFar needs to translate cur = GameObject.Find("bCornerLeftFar"); cur.transform.localPosition += new Vector3(0, 0, rDiff); // bSideVerticalRight needs to scale and translate cur = GameObject.Find("bSideVerticalRight"); cur.transform.localPosition += new Vector3(cDiff, 0, 0.5f * (rDiff)); cur.transform.localScale += new Vector3(rDiff, 0, 0); for (int i = 6; i < 10; ++i) { if (i != 8) lights[i].transform.localPosition += new Vector3(cDiff, 0, 0.5f * (rDiff)); } // bCornerRightFar needs to translate cur = GameObject.Find("bCornerRightFar"); cur.transform.localPosition += new Vector3(cDiff, 0, rDiff); // bSideHorizontalFar needs to translate and scale cur = GameObject.Find("bSideHorizontalFar"); cur.transform.localPosition += new Vector3(0.5f * (cDiff), 0, rDiff); cur.transform.localScale += new Vector3(cDiff, 0, 0); lights[10].transform.localPosition += new Vector3(0.5f * (cDiff), 0, rDiff); lights[11].transform.localPosition += new Vector3(0.5f * (cDiff), 0, rDiff); cur = GameObject.Find("bPlatform"); cur.transform.localPosition += new Vector3(0.5f * (cDiff), 0, 0.5f * (rDiff)); cur.transform.localScale += new Vector3(rDiff, 0, cDiff); cur = GameObject.Find("bSideHorizontal"); cur.transform.localPosition += new Vector3(0.5f * (cDiff),0,0); cur.transform.localScale += new Vector3(cDiff,0,0); lights[12].transform.localPosition += new Vector3(0.5f * (cDiff), 0, 0); lights[13].transform.localPosition += new Vector3(0.5f * (cDiff), 0, 0); cur = GameObject.Find("bCornerRight"); cur.transform.localPosition += new Vector3(cDiff,0,0); lights[5].transform.localPosition += new Vector3(cDiff, 0, rDiff); lights[8].transform.localPosition += new Vector3(cDiff, 0, rDiff); cam.transform.localPosition = new Vector3(cDiff/2+ 3.5f, 9.8f, -6); camDefaultPos = cam.transform.localPosition; l.transform.localPosition += new Vector3(cDiff / 2+ 3.5f, 0, 0); cam.GetComponent<CameraController>().panLimitLeftTop += new Vector2(0,rDiff); cam.GetComponent<CameraController>().panLimitRightBot += new Vector2(cDiff, 0); } #endregion Setup Other Pieces // Delete offboard base pieces, delete black/white offboard squares GameObject.Destroy(blackSquare); GameObject.Destroy(whiteSquare); for (int i = 0; i < 12; ++i) GameObject.Destroy(basePieces[i]); } // Place a square object in the board during setup void PlaceSquare(int row, int col) { Grid[row][col] = new Square(); GameObject square; if ((row + col) % 2 == 0) // alternate square colors square = blackSquare; else square = whiteSquare; Grid[row][col].Cube = Object.Instantiate(square, new Vector3(col, 0, row), Quaternion.identity); } void RandomPlacement(int row, int col) { int pieceNumber; // Place randomly chosen pieces if (row == 1) // Black front row { // Randomly generate a piece number avoiding kings PlacePiece(basePieces[Random.Range(0, 5)], row, col); } else if (row == ROWS - 2) // White front row { // Randomly generate a piece number avoiding kings do pieceNumber = Random.Range(6, 12); //[6,12) while (pieceNumber == 10); PlacePiece(basePieces[pieceNumber], row, col); } else if (row == ROWS - 1) // White back row { RandomBackRowPlacement(WHITE, WHITE_KING, row, col, 6); } else if (row == 0) // Black back row { RandomBackRowPlacement(BLACK, BLACK_KING, row, col); } } void StandardPlacement(int[] BackRow, int row, int col) { // Place pieces if (row == 1) // Black front row { PlacePiece(basePieces[0], row, col); } else if (row == ROWS - 2) // White front row { PlacePiece(basePieces[6], row, col); } else if (row == ROWS - 1) // White back row { // Sequentially place back row units PlacePiece(basePieces[BackRow[col] + 6], row, col); // Only if king was placed, it will be marked IfKingAdd(WHITE, row, col); } else if (row == 0) // Black back row { PlacePiece(basePieces[BackRow[col]], row, col); IfKingAdd(BLACK, row, col); } } // If king is on square, add to kings list void IfKingAdd(int color, int row, int col) { if (Grid[row][col].PieceHeld.GetComponent<King>()) { kings[color] = Grid[row][col].PieceHeld.GetComponent<King>(); kings[color].x = col; kings[color].y = row; kingPlaced[color] = true; } } void RandomBackRowPlacement(int color, int kingNumber, int row, int col, int shift = 0) { int pieceNumber = Random.Range(0 + shift, 6 + shift); // [start, end) // If number corresponding to this color king chosen or at last column and king hasn't been placed if (pieceNumber == kingNumber || (col == COLS - 1 && !kingPlaced[color])) { // If king hasn't been placed, place it if (!kingPlaced[color]) { PlacePiece(basePieces[kingNumber], row, col); // Store the king in kings array IfKingAdd(color, row, col); } else // else place knight PlacePiece(basePieces[2 + shift], row, col); } else // else place piece PlacePiece(basePieces[pieceNumber], row, col); } // Handle setting team and adding to piece list void FinalizePiece(int row, int col) { // Set team to white. Default is already black. White is -1. These numbers will also be used for movement direction. if (row >= ROWS - 2 && Grid[row][col].PieceHeld != null) { Grid[row][col].PieceHeld.GetComponent<Piece>().Team = -1; } if (Grid[row][col].PieceHeld) { var piece = Grid[row][col].PieceHeld; // Add pieces to list, except for kings. if (!piece.GetComponent<King>()) { // add to the appropriate team's piece list thePieces[row >= ROWS - 2 ? WHITE : BLACK].Add(piece); piece.GetComponent<Piece>().x = col; piece.GetComponent<Piece>().y = row; } } } public void HandleRevival(EventCallbacks.ReviveEvent e) { // Discard the pawn Grid[revivalPosY][revivalPosX].PieceHeld.transform.localPosition += new Vector3(0, -12, 0); // Move dead piece back onto the board Grid[revivalPosY][revivalPosX].PieceHeld = e.Piece; e.Piece.transform.localPosition = new Vector3(revivalPosX, 4, revivalPosY); e.Piece.transform.localEulerAngles = new Vector3(0, 0, 0); e.Piece.GetComponent<Piece>().x = revivalPosX; e.Piece.GetComponent<Piece>().y = revivalPosY; // Put zombies back to sleep new EventCallbacks.SleepEvent().FireEvent(); Debug.Log("Handling revival, and just fired sleep event"); // False this flag so Update can finish up the turn wokeFlag = false; revivedFlag = true; } private void Update () { // if (Advertisement.IsReady()) // Advertisement.Show("video"); if (reviveFlag || wokeFlag || revivedFlag) { // You need to revive a piece from your team. // A dead piece must exist, check the count // Only do this once block once, and then wait for a selection. if(reviveFlag && deadCount[teamTurn == 1 ? 0 : 1] != 0) { // Wake up your dead pieces var e = new EventCallbacks.WakeUpEvent(); e.Team = teamTurn; e.FireEvent(); wokeFlag = true; deadCount[teamTurn == 1 ? 0 : 1]--; } reviveFlag = false; // After revive, the event handler will flip this // or if revive was skipped because it couldn't occur (no dead pieces), this flag would never have been true // Finish up. if (!wokeFlag) { // Check if enemy's team is now check mated. CheckMate(); // If you check the other player's king, then they will have to move it next round Check(); teamTurn *= -1; // Next turn will be other player. reviveFlag = false; wokeFlag = false; revivedFlag = false; // Wait for piece to drop before switching camera StartCoroutine("SwitchCam"); } } else { UpdateSelection(); // If left click if (Input.GetMouseButtonDown(0)) { // If click on board if (selectionX >= 0 && selectionY >= 0 && selectionY < ROWS && selectionX < COLS) { // Initial selection if (selection == null) { // Select square if (selectSquare()) { // Lift chess piece selectedPiece.GetComponent<Rigidbody>().isKinematic = true; selectedPiece.transform.localPosition = new Vector3(selection.transform.localPosition.x, 4, selection.transform.localPosition.z); selectedPiece.transform.eulerAngles = new Vector3(0, 0, 0); // We will need to know the initial position after a valid move is made. selectionX1 = selectionX; selectionY1 = selectionY; // Calculate all possible positions that the piece can move to validLocations = selectedPiece.GetComponent<Piece>().CalculateLocations(ref Grid, selectionX, selectionY); Dictionary<int, HashSet<int>> newValidLocations = new Dictionary<int, HashSet<int>>(); var isKing = selectedPiece.GetComponent<King>(); // Highlight all validLocations if (Settings.HoverFlag) { teamTurn *=-1; highLit = true; foreach (var pair in validLocations) { newValidLocations.Add(pair.Key, new HashSet<int>()); var newSet = new HashSet<int>(); newValidLocations.TryGetValue(pair.Key, out newSet); foreach (var Y in pair.Value) { // If checked, must decide if any of these moves are actually valid. // However, kings already check if their moves are truly valid if (checkedFlag && !isKing) { // Temporarily make the move var tempEnemy = Grid[Y][pair.Key].PieceHeld; Grid[Y][pair.Key].PieceHeld = selectedPiece; Grid[selectionY][selectionX].PieceHeld = null; // If still checked, this move is invalid bool stillChecked = Check(); // Reverse move Grid[selectionY][selectionX].PieceHeld = selectedPiece; Grid[Y][pair.Key].PieceHeld = tempEnemy; // Skip this location if it is invalid if (stillChecked) { Debug.Log("Invalid move, can't highlight"); continue; } } var rend = Grid[Y][pair.Key].Cube.GetComponent<Renderer>(); var s = Shader.Find("Legacy Shaders/Self-Illumin/Diffuse"); rend.material.shader = s; if (rend.material.name.Contains("Black")) { rend.material = a2; } else { rend.material = a4; } newSet.Add(Y); } } validLocations = newValidLocations; teamTurn *= -1; } } else // Couldn't select square. Wrong team? { selection = null; // will have to try again, so, we will end up calling selectSquare until we pick a valid square } } // A valid initial selection has been made. Now select where to move. // We won't get here unless selection!=null and selectedPiece!=null else { // Turn off halo var halo = selection.GetComponent("Halo"); halo.GetType().GetProperty("enabled").SetValue(halo, false, null); selectedPiece.GetComponent<Rigidbody>().isKinematic = false; // Un-Highlight all validLocations if (highLit) { highLit = false; foreach (var pair in validLocations) { foreach (var Y in pair.Value) { var rend = Grid[Y][pair.Key].Cube.GetComponent<Renderer>(); var s = Shader.Find("Standard"); if (rend.material.name.Contains("Black")) { rend.material = a1; } else { rend.material = a3; } } } } selection = null; // Let another selection after this // Is this a valid destination? HashSet<int> ySet; if (validLocations.TryGetValue(selectionX, out ySet)) { // The X coord was valid. Check the Y if (ySet.Contains(selectionY) == false) { selectedPiece.GetComponent<Rigidbody>().useGravity = true; // Did not find Y coord, invalid destination. Break here so another initial selection must be made, before switching teams return; } } else { selectedPiece.GetComponent<Rigidbody>().useGravity = true; // Did not find X coord, invalid destination. Break here so another initial selection must be made, before switching teams return; } /// At this point: A valid destination was selected. Time to move. // Move chess piece selectedPiece.transform.localPosition = new Vector3(selectionX, 3, selectionY); selectedPiece.transform.eulerAngles = new Vector3(0, 0, 0); selectedPiece.GetComponent<Piece>().x = selectionX; selectedPiece.GetComponent<Piece>().y = selectionY; if (selectedPiece.GetComponent<King>()) { selectedPiece.GetComponent<King>().hasMoved = true; } checkedFlag = false; // If this flag was on, and we got here, we know it is not checked anymore // Find enemy piece. var enemy = Grid[selectionY][selectionX].PieceHeld; // If there actually is an enemy there if (enemy != null) { // Check castling case // If this "enemy" is actually an allied Rook, we know this has to be a castling case if (enemy.GetComponent<Rook>() && enemy.GetComponent<Piece>().Team == teamTurn) { Debug.Log("Rook special case"); int rightWard = -1; // Although we highlighted the rook's position, we don't actually swap with the Rook // King goes before Rook, then Rook moves before King // Since we have a chance that the Rook is already initially adjacent to the King // Rook will end up swapping with another piece if need be. if (selectionX > selectionX1) rightWard = 1; // Move king Grid[selectionY][selectionX-rightWard].PieceHeld = selectedPiece; selectedPiece.transform.localPosition = new Vector3(selectionX-rightWard, 3, selectionY); selectedPiece.GetComponent<Piece>().x = selectionX-rightWard; selectedPiece.GetComponent<Piece>().y = selectionY; Grid[selectionY1][selectionX1].PieceHeld = null; // Move rook Grid[selectionY][selectionX-rightWard*2].PieceHeld = enemy; enemy.transform.localPosition = new Vector3(selectionX-rightWard*2, 3, selectionY); enemy.transform.eulerAngles = new Vector3(0, 0, 0); enemy.GetComponent<Piece>().x = selectionX-rightWard*2; enemy.GetComponent<Piece>().y = selectionY; Grid[selectionY][selectionX].PieceHeld = null; enemy.GetComponent<Rook>().hasMoved = true; kings[teamTurn == 1 ? 0 : 1].x = selectionX-rightWard; } else { HandleKill(enemy); // Kill enemy Grid[selectionY][selectionX].PieceHeld = selectedPiece; // selectedPiece moves to the new position Grid[selectionY1][selectionX1].PieceHeld = null; } } else { Grid[selectionY][selectionX].PieceHeld = selectedPiece; // selectedPiece moves to the new position Grid[selectionY1][selectionX1].PieceHeld = null; } // Rook can't castle with king anymore if (selectedPiece.GetComponent<Rook>()) selectedPiece.GetComponent<Rook>().hasMoved = true; // Special cases for Pawn moves if (Grid[selectionY][selectionX].PieceHeld) { var thePawn = Grid[selectionY][selectionX].PieceHeld.GetComponent<Pawn>(); if (thePawn != null) { thePawn.isInitial++; // Count the pawn's moves // A kill wasn't made, so maybe it was an En Passant capture if (enemy == null) { // Check En Passant condition. We may have made an En Passant capture. // To check En Passant, all we need to know is if there is an enemy pawn behind us and if we didn't make a kill on our move. // Because if we didn't make a kill, then the only way there can be a pawn behind us is if it was an En Passant diagonal move. // Use the teamTurn value to get to the cell behind. There is always a cell behind, bcuz we moved forward. var behind = Grid[selectionY - teamTurn][selectionX].PieceHeld; if (behind != null) { var pawnBehind = behind.GetComponent<Pawn>(); // If it is an enemy pawn if (pawnBehind != null && pawnBehind.Team != teamTurn) { /// It was an En Passant capture. We need to kill the enemy. HandleKill(behind); } } } // Check revive case -- Pawn has reached opposing end. if ((teamTurn == 1 && selectionY == ROWS - 1) || (teamTurn == -1 && selectionY == 0)) { // Flip revive flag, now we have to poll for revival before we can do anything else with the board. reviveFlag = true; revivalPosX = selectionX; revivalPosY = selectionY; // So we break here, then once revival occurs we will finish up and switch turn return; } } } // Check pawn swapping dead case. //How could we possibly allow the user to swap dead here? //They need to make a selection, but we are here. // Maybe we neeed to move all this business to an async method, and we await something? // Or maybe we have to leave this method, set some flag. // And, while the flag is set, we don't come back in here anymore. // We wait until a dead piece is clicked on (if there are no dead pieces, well pawn loses his chance) // Once dead piece is clicked on, we need to flip the flag. So, how does pawn notify the board? // Pawn would need to be observing the board. Or the board needs to be subscribed to pawn events. // At this point: selectedPiece has been moved to a valid location // We should stop the game if checkmate or stalemate. Also should notify if mate. // Stale mate occurs if current player has no valid moves, but isn't in check. // There doesn't seem to be a sensible performant way to check for stalemate. Think of a big board // If player has no moves, he will have to give up. Or maybe he can ask to check stalemate condition. // Only check if enemy's team is now check mated, because you can't move your own king into check mate on your turn. CheckMate(); // If you check the other player's king, then they will have to move it next round Check(); teamTurn *= -1; // Next turn will be other player. // Wait for piece to drop before switching camera StartCoroutine("SwitchCam"); } } } } } private void HandleKill(GameObject enemy) { // For white's turn, we are killing a black, and putting him in the black bin if (teamTurn == -1) enemy.transform.localPosition = new Vector3(-6.7f - (deadCount[teamTurn == -1 ? 1 : 0]*.01f), 2.8f + (deadCount[teamTurn == -1 ? 1 : 0] * .08f), 0); else enemy.transform.localPosition = new Vector3(-6.7f - (deadCount[teamTurn == -1 ? 1 : 0] * .01f), 2.8f+ (deadCount[teamTurn == -1 ? 1 : 0] * .08f), ROWS); // Increment opposing team's deadCount deadCount[teamTurn == -1 ? 0 : 1]++; // Notify piece it is dead so it can start accepting clicks. It also subscribes to the WakeUpEvent enemy.GetComponent<Piece>().Die(); // Nope // Enemy needs to go in a dead collection for his team //deadPieces[teamTurn==1 ? 0 : 1].Add } IEnumerator AnimateWinText(GameObject text) { var rot = text.GetComponent<RectTransform>(); int i = 1, j = 1, k = 1; for (; i < 40; ++i) { rot.Rotate(new Vector3(i,i,i*-1)); yield return new WaitForSecondsRealtime(0.0001f); } for (; i >=0; --i) { rot.Rotate(new Vector3(i*-1, i*-1, i)); yield return new WaitForSecondsRealtime(0.01f); } rot.eulerAngles = new Vector3(0, 0, 0); yield return new WaitForSecondsRealtime(1.7f); gameOver.SetActive(true); yield return null; } private void CheckMate() { if (teamTurn == 1) // Black's turn { // Call white King's CheckMate(), passing in white King's coords if (kings[1].CheckMate(ref Grid, kings[1].x, kings[1].y)) { // We only know that the King can't move. // Now, we need to know if any white piece can get them out of check. // So, iterate each alive piece and calculate valid locations // Iterate valid locations and try to see if the move removes the check. foreach(var p in thePieces[1]) { var piece = p.GetComponent<Piece>(); // If piece is alive if (!piece.IsDead) { var moves = piece.CalculateLocations(ref Grid, piece.x, piece.y); foreach (var pair in moves) { foreach (var Y in pair.Value) { // Temporarily make the move var tempEnemy = Grid[Y][pair.Key].PieceHeld; Grid[Y][pair.Key].PieceHeld = p; Grid[piece.y][piece.x].PieceHeld = null; // If still checked, this move is invalid. bool stillChecked = Check(); // Reverse move Grid[piece.y][piece.x].PieceHeld = p; Grid[Y][pair.Key].PieceHeld = tempEnemy; // We've found a piece with a valid move (unchecking move), so we aren't check mated. if (!stillChecked) { return; } } } } } // Black wins! blackWins.SetActive(true); StartCoroutine(AnimateWinText(blackWins)); } } else { if (kings[0].CheckMate(ref Grid, kings[0].x, kings[0].y)) { foreach (var p in thePieces[0]) { var piece = p.GetComponent<Piece>(); // If piece is alive if (!piece.IsDead) { var moves = piece.CalculateLocations(ref Grid, piece.x, piece.y); foreach (var pair in moves) { foreach (var Y in pair.Value) { // Temporarily make the move var tempEnemy = Grid[Y][pair.Key].PieceHeld; Grid[Y][pair.Key].PieceHeld = p; Grid[piece.y][piece.x].PieceHeld = null; // If still checked, this move is invalid. bool stillChecked = Check(); // Reverse move Grid[piece.y][piece.x].PieceHeld = p; Grid[Y][pair.Key].PieceHeld = tempEnemy; // We've found a piece with a valid move (unchecking move), so we aren't check mated. if (!stillChecked) { return; } } } } } // White wins! whiteWins.SetActive(true); StartCoroutine(AnimateWinText(whiteWins)); } } } private bool Check() { if (teamTurn == 1) // Black's turn { // Call white King's Check(), passing in white King's coords if (kings[1].Check(ref Grid, kings[1].x, kings[1].y)) { // White king is checked checkedFlag = true; Debug.Log("White king is checked"); return true; } } else { if (kings[0].Check(ref Grid, kings[0].x, kings[0].y)) { checkedFlag = true; Debug.Log("Black king is checked"); return true; } } return false; } // Switches camera after delay IEnumerator SwitchCam() { yield return new WaitForSeconds(1.2f); // Switch camera orientation cam.transform.localPosition = camDefaultPos; cam.transform.eulerAngles = camDefaultRot; if (teamTurn == -1) { cam.transform.eulerAngles += new Vector3(0, 180, 0); cam.transform.localPosition += new Vector3(0, 0, ROWS + 11); } } // Track mouse, and update which square is selected // Note: the center of the first square is at 0,0. it extends .5 in four XZ directions. So we truncate it // So now first square is from 0-1 on X and Z. So, let's say 1,1 actually starts the diagonal square private void UpdateSelection() { if (!Camera.main) return; RaycastHit hit; if (Physics.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 50.0f, LayerMask.GetMask("Plane"))) { //Debug.Log(hit.point); selectionX = (int)(hit.point.x+0.5f); selectionY = (int)(hit.point.z+0.5f); } else { selectionX = selectionY = -1; } } // Ensure validity of the initial square selection private bool selectSquare() { selectedPiece = Grid[selectionY][selectionX].PieceHeld; // If empty square, return false if (selectedPiece == null) return false; // If square of wrong team selected, return false if (selectedPiece.GetComponent<Piece>().Team != teamTurn) return false; // Determine whether if this piece leaves his square will cause the king to be checked if (!checkedFlag && selectedPiece.GetComponent<King>()==null) { // Temporarily remove the piece Grid[selectionY][selectionX].PieceHeld = null; // Check if the king is checked now if ((teamTurn == 1 && kings[0].Check(ref Grid, kings[0].x, kings[0].y)) || (teamTurn == -1 && kings[1].Check(ref Grid, kings[1].x, kings[1].y))) { // Reject this selection, can't move this piece if it will check the king Grid[selectionY][selectionX].PieceHeld = selectedPiece; return false; } Grid[selectionY][selectionX].PieceHeld = selectedPiece; } // Select cube selection = Grid[selectionY][selectionX].Cube; // Turn on halo var halo = selection.GetComponent("Halo"); halo.GetType().GetProperty("enabled").SetValue(halo, true, null); return true; } } // find first game object in scene of given type //FindObjectOfType<Square>()
5c0a4203b07606928d65a7d57addfd748682141b
[ "Markdown", "C#" ]
2
Markdown
arasouli91/omniChess
b6f746d548a413e57f61674ac256f516ca983f3e
2aeb5a5123fd7add993f56d078de372467b14f37
refs/heads/master
<repo_name>kirin123kirin/GitTest<file_sep>/hoge/src/hoge.py # To change this template, choose Tools | Templates # and open the template in the editor. __author__="yellow" __date__ ="$2013/01/31 21:31:43$" if __name__ == "__main__": print "Hello World" <file_sep>/hoge/nbproject/project.properties java.lib.path= main.file=hoge.py platform.active=Python_2.7.2 python.lib.path= src.dir=src
3e7e3ebf3ef491fef201eb3ce5b54743b3e32097
[ "Python", "INI" ]
2
Python
kirin123kirin/GitTest
081eb5505729b2a403dcc19da7ea1409b21565d7
53a8051361511daa5a56ea3efbec7f89a6be180c
refs/heads/master
<repo_name>chenmiaohui/Login<file_sep>/app/src/main/java/com/god/mvp/mvp/model/LoginModelImpl.java package com.god.mvp.mvp.model; import android.util.Log; import com.god.mvp.mvp.bean.User; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; /** * @author David create on 2016/7/29 15:47. * @email <EMAIL> * Learn from yesterday, live for today, hope for tomorrow. */ public class LoginModelImpl implements LoginModel { private OkHttpClient client = new OkHttpClient(); @Override public void login(final String username, final String password, final OnLoginListener onLoginListener) { if (username.isEmpty()){ onLoginListener.loginFailed("用户名不能为空"); return; } if (password.isEmpty()){ onLoginListener.loginFailed("密码不能为空"); return; } FormEncodingBuilder builder = new FormEncodingBuilder(); builder.add("accountName",username);//"zzsDev" builder.add("password",password);//"<PASSWORD>" Request request = new Request.Builder() .url("www.baidu.com")//换成自己的URI .post(builder.build()) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { onLoginListener.loginFailed(e+"--"+request); Log.e("--------------","=============="+request+"========="+e); } @Override public void onResponse(Response response) throws IOException { try { String result = response.body().string(); JSONObject jo = new JSONObject(result); Log.e("--------------","=============="+jo); String code = jo.getString("code"); if (code.equals("1111")){ onLoginListener.loginSuccess(new User(username, password)); }else { onLoginListener.loginFailed("账户名或者密码错误..."); } } catch (JSONException e) { e.printStackTrace(); } // Gson gson = new Gson(); // LoginBean loginBean = gson.fromJson(result, LoginBean.class); // if (loginBean.getCode().equals("1111")){ // onLoginListener.loginSuccess(new User(username, password)); // }else{ // onLoginListener.loginFailed("登陆失败..."); // } // Log.e("--------------","=============="+response.body().string()+"----"+new User(username, password)); } }); } }
0fd9e232a305f0a6caddb816bf65019c10c2d655
[ "Java" ]
1
Java
chenmiaohui/Login
1794937f1f0b85049b3b102ec185066cb4efb13d
9aa44d0d608752e09962e8da23af3f210c7c8d48
refs/heads/master
<file_sep>#include<stdio.h> #include<sys/types.h> main() { char cmd [10]; int ch; pid_t pid; pid=fork(); if(pid==0) { do { printf("enter the command to be executed :\n"); scanf("%s",cmd); system(cmd); printf("enter 1 to enter more commands,0 to exit\n"); scanf("%d",&ch); } while ( ch!=0 ); } wait(); } <file_sep>#include<stdio.h> int main() { int a,b,c,ch; printf("welcome to program 2 lex demo of SS and OS!lab\n"); printf("1. to add\n 2. to sub\n 3 . to MUL \n"); //switch cae for make the above listed decession before that get input scanf("%d",&ch); /*get the ch as choice input*/ switch(ch) case 1: printf("Enter the 2 nos\n"); scanf("%d",&a); scanf("%d",&b); c=a+b; printf("sum of 2 nos %d",c); //case 2: // printf("Get the hell out\n"); } <file_sep>echo "the number of arguments provided are:$#" length=$# echo "reverse order of the aruments:" while [ $length -ne 0 ] do eval echo \$$length length=`expr $length - 1` done <file_sep>ls -l $1|cut -d "" -f1 > file1per ls -l $2|cut -d "" -f1 > file2per if cmp file1per file2per then echo "$1 and $2 have same permissions" cat file1per else echo "$1 and $2 have different permissions" echo "$1 permissions are" cat file1per echo "$2 permissions are" cat file2per fi <file_sep># include<stdio.h> # include<omp.h> # include<stdlib.h> int MAX; int Fibonacci(int n) { int x, y; if (n < 2) return n; else { x = Fibonacci(n - 1); y = Fibonacci(n - 2); return (x + y); } } int FibonacciTask(int n) { int x, y; if (n < 2) return n; else { x = Fibonacci(n - 1); y = Fibonacci(n - 2); return (x + y); } } /* random number generation upto 24 */ int random_num() { int temp; temp = rand(); temp = temp%24; MAX = temp; return(MAX); } int main(int argc, char * argv[]) { int FibNumber[25] = {0}; int j, temp,tmp,id,i = 0; int n, tid, nthreads; printf("Please Enter the number Range :"); scanf("%d",&n); printf("\n"); omp_set_num_threads(2); //Parallel region # pragma omp parallel { printf("The number of threads are %d\n",omp_get_num_threads()); # pragma omp for private (tid, tmp, FibNumber) for(j = 1; j<=n; j++) { tmp = random_num(); /* Get thread number */ /* tid = omp_get_thread_num(); printf("The number of threads are %d\n",omp_get_num_threads()); printf("The thread id is = %d\n", tid); */ /* The critical section here will enable, not more then one thread to execute in this section (synchronization) */ # pragma omp critical { /* Get thread number */ /* tid = omp_get_thread_num(); printf("********************* inside critical section*****\n"); printf("The thread id is = %d\n", tid); */ for(i = 1; i <= tmp; i++) FibNumber[i] = FibonacciTask(i); printf("The number value is %d:",tmp); for(i = 1; i <= tmp; i++) printf("%d \t", FibNumber[i]); printf("\n\n"); } } } } /* gcc -o fiber11.c -fopenmp fiber11.c */ <file_sep>#include <iostream> using namespace std; int main () { cout<< "hell"; } <file_sep>#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<stdlib.h> main() { int fd; char buf1[]="department of is"; char buf2[]="department of cs"; fd=creat("ise",0622); if(fd<0) { printf("file is not created\n"); exit(0); } write(fd,buf1,16); lseek(fd,48,SEEK_SET); write(fd,buf2,16); } <file_sep>#include<iostream> using namespace std; int n,sum,q; struct time { float at,bt,tat; int p; }a[20]; void SJF(); void RRB(); int main() { int i,j,ch; cout<<"Enter the no of processes\n"; cin>>n; sum=0; for(i=1;i<=n;i++) { cout<<"Enter the arrival time"<<i<<":"; cin>>a[i].at; cout<<"Enter the burst time"<<i<<":"; cin>>a[i].bt; a[i].p=i; sum=sum+a[i].bt; } cout<<"1.SJF 2.RRB"<<endl; cin>>ch; switch(ch) { case 1:SJF(); cout<<"Shortest remaining time job\n"; break; case 2:cout<<"Enter the Quantam"; cin>>q; RRB(); cout<<"\n\n"; } cout<<"\n\n\n"<<"pno"<<"\t"<<"tat"<<endl; for(i=1;i<=n;i++) cout<<a[i].p<<"\t"<<a[i].tat<<"\n"; float avg=0; for(i=1;i<=n;i++) { avg+=a[i].tat; } float tat=avg/n; cout<<"average tat is"<<tat<<endl; return 0; } void SJF() { float ts=0,diff; int i,j=1,k=1; while(ts<sum) { if(j<=n-1) { j++; diff=a[j].at-a[j-1].at; a[k].bt-=diff; ts+=diff; if(a[k].bt==0) a[k].tat=ts-a[k].at; } else { j=n; ts+=a[k].bt; a[k].bt=0; a[k].tat=ts-a[k].at; } int small=999; for(i=1;i<=j;i++) { if(a[i].bt<small && a[i].bt!=0) { small=a[i].bt; k=i; } } } for(i=1;i<=j;i++) { cout<<i<<"\t"<<a[i].tat<<endl; } } void RRB() { float ts=0; int i; while (ts<sum) { for(i=1;i<=n;i++) { if(a[i].bt!=0) { if(a[i].bt<=q) { ts+=a[i].bt; a[i].bt=0; } else { a[i].bt-=q; ts+=q; } if(a[i].bt==0) a[i].tat=ts-a[i].at; } } } } <file_sep>echo nf1 echo dsce >nf1 echo nf2 echo dsce >nf2 <file_sep>#include<stdio.h> int main() { int pid=fork(); if(pid==0) { printf("\n child process\n"); printf("process id=%d\n",getpid()); printf("parent process id=%id\n",getppid()); } else { wait(0); printf("\n parents process\n"); printf("process id=%d\n",getpid()); printf("child's process id=%d\n",pid); } return 0; } <file_sep>for i in $* do echo "echo $i" echo "echo `cat $1` >$i" done
943e2b215380c31fe652ccb1ecf0eddf482d01be
[ "C", "C++", "Shell" ]
11
C
1we/SSOS
4718df5bf7d2eec624f88b32fa7e5c763d3cd544
1e4a2e0d73076467fa2c7556ec09682d0d5e864c
refs/heads/main
<file_sep>from pydub import AudioSegment files_path = '' file_name = '2_cut' print (file_name+'.mp3' ) startMin = 0 startSec = 5 endMin = 1 endSec = 45 # Time to miliseconds startTime = startMin*60*1000+startSec*1000 endTime = endMin*60*1000+endSec*1000 # Opening file and extracting segment song = AudioSegment.from_mp3( file_name+'.mp3' ) extract = song[startTime:endTime] # Saving extract.export( file_name+'-extract.mp3', format="mp3")<file_sep>import io import os import speech_recognition as sr import os from pydub import AudioSegment from pydub.silence import split_on_silence from google.cloud import speech # from google.cloud.speech import enums # from google.cloud.speech import types import wave from google.cloud import storage import requests from flask import Flask, request, redirect, session, url_for, Response, json, render_template, send_from_directory from werkzeug.utils import secure_filename from flask.json import jsonify from flask_cors import CORS ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.config.from_object(__name__) CORS(app) def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def getfile(url): r = requests.get(url, allow_redirects=True) open('download.mp3', 'wb').write(r.content) return ('download.mp3') def trimfile(filein): startMin = 0 startSec = 0 endMin = 1 endSec = 45 # Time to miliseconds startTime = startMin*60*1000+startSec*1000 endTime = endMin*60*1000+endSec*1000 # Opening file and extracting segment song = AudioSegment.from_mp3( filein ) extract = song[startTime:endTime] # Saving extract.export( 'extract.mp3', format="mp3") return 'extract.mp3' def mp3_to_wav(audio_file_name): if audio_file_name.split('.')[1] == 'mp3': sound = AudioSegment.from_mp3(audio_file_name) audio_file_name = audio_file_name.split('.')[0] + '.wav' sound.export(audio_file_name, format="wav") def stereo_to_mono(audio_file_name): sound = AudioSegment.from_wav(audio_file_name) sound = sound.set_channels(1) sound.export(audio_file_name, format="wav") def frame_rate_channel(audio_file_name): with wave.open(audio_file_name, "rb") as wave_file: frame_rate = wave_file.getframerate() channels = wave_file.getnchannels() return frame_rate,channels # create a speech recognition object r = sr.Recognizer() # a function that splits the audio file into chunks # and applies speech recognition def get_large_audio_transcription(path): """ Splitting the large audio file into chunks and apply speech recognition on each of these chunks """ # open the audio file using pydub sound = AudioSegment.from_wav(path) # split audio sound where silence is 700 miliseconds or more and get chunks chunks = split_on_silence(sound, # experiment with this value for your target audio file min_silence_len = 500, # adjust this per requirement silence_thresh = sound.dBFS-14, # keep the silence for 1 second, adjustable as well keep_silence=500, ) folder_name = "audio-chunks" # create a directory to store the audio chunks if not os.path.isdir(folder_name): os.mkdir(folder_name) whole_text = "" # process each chunk for i, audio_chunk in enumerate(chunks, start=1): # export audio chunk and save it in # the `folder_name` directory. chunk_filename = os.path.join(folder_name, f"chunk{i}.wav") audio_chunk.export(chunk_filename, format="wav") # recognize the chunk with sr.AudioFile(chunk_filename) as source: audio_listened = r.record(source) # try converting it to text try: text = r.recognize_google(audio_listened) except sr.UnknownValueError as e: print("Error:", str(e)) else: text = f"{text.capitalize()}. " print(chunk_filename, ":", text) whole_text += text # return the text for all chunks detected return whole_text def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) def delete_blob(bucket_name, blob_name): """Deletes a blob from the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(blob_name) blob.delete() def google_transcribe(audio_file_name): file_name = audio_file_name mp3_to_wav(file_name) audio_file_name = 'extract.wav' # The name of the audio file to transcribe print(file_name) frame_rate, channels = frame_rate_channel('extract.wav') if channels > 1: stereo_to_mono('extract.wav') bucket_name = 'callsaudiofilesx' source_file_name = audio_file_name destination_blob_name = audio_file_name upload_blob(bucket_name, source_file_name, destination_blob_name) gcs_uri = 'gs://callsaudiofilesx/' + audio_file_name transcript = '' client = speech.SpeechClient() audio = speech.RecognitionAudio(uri=gcs_uri) config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=frame_rate, language_code='en-US') # Detects speech in the audio file operation = client.long_running_recognize(config=config, audio=audio) response = operation.result(timeout=10000) for result in response.results: transcript += result.alternatives[0].transcript delete_blob(bucket_name, destination_blob_name) return transcript ##testing # filename = 'test.mp3' # filename = getfile('https://dcs.megaphone.fm/WSMM8548505894.mp3?key=<KEY>') # efile = trimfile(filename) # mp3_to_wav(efile) # whole_text = '' # stereo_to_mono('extract.wav') # # recognize the chunk # with sr.AudioFile('extract.wav') as source: # audio_listened = r.record(source) # # try converting it to text # try: # text = r.recognize_google(audio_listened) # except sr.UnknownValueError as e: # print("Error:", str(e)) # else: # text = f"{text.capitalize()}. " # # print(chunk_filename, ":", text) # whole_text += text # whole_text = google_transcribe('extract.mp3') # print (whole_text) # print ('done') ##done testing @app.route("/transcribe", methods=[ 'POST']) def transcribereq(): print(request) res = request.get_json() print (res) resraw = request.get_data() print (resraw) fileurl = res['url'] filename = getfile(fileurl) efile = trimfile(filename) mp3_to_wav(efile) whole_text = '' whole_text = google_transcribe('extract.mp3') status = {} status["server"] = "up" status["transcript"] = whole_text status["request"] = res statusjson = json.dumps(status) print(statusjson) js = "<html> <body>OK THIS WoRKS</body></html>" resp = Response(statusjson, status=200, mimetype='application/json') ##resp.headers['Link'] = 'http://google.com' return resp @app.route("/file_upload", methods=["POST"]) def fileupload(): if 'file' not in request.files: return "No file part" file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': return "No selected file" if file and allowed_file(file.filename): # UPLOAD_FOLDER = "./uploads" UPLOAD_FOLDER = "uploads" filename = secure_filename(file.filename) # file.save(os.path.join(UPLOAD_FOLDER, filename)) file.save(filename) # uploadtogcp(os.path.join(UPLOAD_FOLDER, filename)) uploadtogcp(os.path.join(filename)) return 'https://storage.googleapis.com/hackybucket/current.jpg' return 'file not uploaded successfully', 400 @app.route("/dummyJson", methods=['GET', 'POST']) def dummyJson(): print(request) res = request.get_json() print (res) resraw = request.get_data() print (resraw) ## args = request.args ## form = request.form ## values = request.values ## print (args) ## print (form) ## print (values) ## sres = request.form.to_dict() status = {} status["server"] = "up" status["message"] = "some random message here" status["request"] = res statusjson = json.dumps(status) print(statusjson) js = "<html> <body>OK THIS WoRKS</body></html>" resp = Response(statusjson, status=200, mimetype='application/json') ##resp.headers['Link'] = 'http://google.com' return resp @app.route("/dummy", methods=['GET', 'POST']) def dummy(): ##res = request.json js = "<html> <body>OK THIS WoRKS</body></html>" resp = Response(js, status=200, mimetype='text/html') ##resp.headers['Link'] = 'http://google.com' return resp @app.route("/api", methods=["GET"]) def index(): if request.method == "GET": return {"hello": "world"} else: return {"error": 400} if __name__ == "__main__": app.run(debug=True, host = 'localhost', port = 8003) # app.run(debug=True, host = '172.16.58.3', port = 8003) <file_sep>import os import pymongo import json import random # import psycopg2 import hashlib import time from hashlib import sha256 def translate_text(target, text): """Translates text into the target language. Target must be an ISO 639-1 language code. See https://g.co/cloud/translate/v2/translate-reference#supported_languages """ # import six from google.cloud import translate_v2 as translate translate_client = translate.Client() # if isinstance(text, six.binary_type): # text = text.decode("utf-8") # Text can also be a sequence of strings, in which case this method # will return a sequence of results for each text. result = translate_client.translate(text, target_language=target) # print(u"Text: {}".format(result["input"])) # print(u"Translation: {}".format(result["translatedText"])) # print(u"Detected source language: {}".format(result["detectedSourceLanguage"])) return result["translatedText"] def hashthis(st): hash_object = hashlib.md5(st.encode()) h = str(hash_object.hexdigest()) return h def dummy(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ if request.method == 'OPTIONS': # Allows GET requests from origin https://mydomain.com with # Authorization header headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*', 'Access-Control-Max-Age': '3600', 'Access-Control-Allow-Credentials': 'true' } return ('', 204, headers) # Set CORS headers for main requests headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } request_json = request.get_json() mongostr = os.environ.get('MONGOSTR') fromLan = request_json['from'] toLan = request_json['to'] text = request_json['text'] result = translate_text(toLan, text) retjson = {} retjson['result'] = result return json.dumps(retjson) retstr = "action not done" if request.args and 'message' in request.args: return request.args.get('message') elif request_json and 'message' in request_json: return request_json['message'] else: return retstr
313152ecebee97c5e14308cf5002cac92d7e09e8
[ "Python" ]
3
Python
flozender/PodCare
012b4f1c8158524c80e2846be33dd7fc5bf13792
f2e01c50f845583ada2195f7cc2187c9361b09fe
refs/heads/master
<file_sep>#pragma once #include <QtWidgets/QMainWindow> #include "ui_MutiCam.h" #include "ApiController.h" #include "OpenCVVideoRecorder.h" using AVT::VmbAPI::Examples::ApiController; class MutiCam : public QMainWindow { Q_OBJECT public: MutiCam( QWidget *parent = 0, Qt::WindowFlags flags = 0 ); ~MutiCam(); private: typedef QSharedPointer<OpenCVRecorder> OpenCVRecorderPtr; //OpenCVRecorderPtr m_pVideoRecorder; std::vector<OpenCVRecorderPtr> m_pVideoRecorders; // The Qt GUI Ui::MutiCamClass ui; // Our controller that wraps API access ApiController m_ApiController; // A list of known camera IDs std::vector<std::string> m_cameras; // A list of selected camera IDs std::vector<std::string> m_selected_cameras; // Are we streaming? bool m_bIsStreaming; // Our Qt image to display //QImage m_Image; std::vector<QImage> m_Images; // // Queries and lists all known camera // void UpdateCameraListBox(); // // Prints out a given logging string, error code and the descriptive representation of that error code // // Parameters: // [in] strMsg A given message to be printed out // [in] eErr The API status code // void Log( std::string strMsg, VmbErrorType eErr ); // // Prints out a given logging string // // Parameters: // [in] strMsg A given message to be printed out // void Log( std::string strMsg); // // Copies the content of a byte buffer to a Qt image with respect to the image's alignment // // Parameters: // [in] pInbuffer The byte buffer as received from the cam // [in] ePixelFormat The pixel format of the frame // [out] OutImage The filled Qt image // VmbErrorType CopyToImage( VmbUchar_t *pInBuffer, VmbPixelFormat_t ePixelFormat, QImage &pOutImage, const float *Matrix = NULL ); private slots: // The event handler for starting / stopping acquisition void OnBnClickedButtonStartstop(); // // This event handler (Qt slot) is triggered through a Qt signal posted by the frame observer // // Parameters: // [in] status The frame receive status (complete, incomplete, ...) // void OnFrameReady( int msg ); // // This event handler (Qt slot) is triggered through a Qt signal posted by the camera observer // // Parameters: // [in] reason The reason why the callback of the observer was triggered (plug-in, plug-out, ...) // void OnCameraListChanged( int reason ); }; <file_sep>#include <FrameObserver.h> #include <OpenCVVideoRecorder.h> #include <iostream> namespace AVT { namespace VmbAPI { namespace Examples { // // This is our callback routine that will be executed on every received frame. // Triggered by the API. // // Parameters: // [in] pFrame The frame returned from the API // void FrameObserver::FrameReceived( const FramePtr pFrame ) { bool bQueueDirectly = true; VmbFrameStatusType eReceiveStatus; if( 0 != receivers(SIGNAL(FrameReceivedSignal(int)) ) && VmbErrorSuccess == pFrame->GetReceiveStatus( eReceiveStatus ) ) { // Lock the frame queue m_FramesMutex.lock(); // Add frame to queue m_Frames.push( pFrame ); push((double)clock(), observer_id); //std::cout << "FrameObserver timeq address : " << &timequeue << std::endl; // Unlock frame queue m_FramesMutex.unlock(); // Emit the frame received signal emit FrameReceivedSignal(eReceiveStatus * 10 + observer_id ); bQueueDirectly = false; } // If any error occurred we queue the frame without notification if( true == bQueueDirectly ) { m_pCamera->QueueFrame( pFrame ); } } // // After the view has been notified about a new frame it can pick it up. // It is then removed from the internal queue // // Returns: // A shared pointer to the latest frame // FramePtr FrameObserver::GetFrame() { // Lock the frame queue m_FramesMutex.lock(); // Pop frame from queue FramePtr res; if( !m_Frames.empty() ) { res = m_Frames.front(); m_Frames.pop(); } // Unlock frame queue m_FramesMutex.unlock(); return res; } // // Clears the internal (double buffering) frame queue // void FrameObserver::ClearFrameQueue() { // Lock the frame queue m_FramesMutex.lock(); // Clear the frame queue and release the memory std::queue<FramePtr> empty; std::swap( m_Frames, empty ); // Unlock the frame queue m_FramesMutex.unlock(); } }}} // namespace AVT::VmbAPI::Examples <file_sep>#pragma once #include <iostream> #include <opencv2/opencv.hpp> #include <string> using namespace std; using namespace cv; Mat PerfectReflectionAlgorithm(Mat src); void calibration(string path);<file_sep> #include "timercpp.h" ActionTimer::ActionTimer() {}; ActionTimer::~ActionTimer() {}; void ActionTimer::stopInterval() { this->clear = true; }<file_sep>#ifndef OPEN_CV_VIDEO_RECORDER_H_ #define OPEN_CV_VIDEO_RECORDER_H_ // open cv include #include "opencv2/opencv.hpp" //qt include #include "QtCore/QSharedPointer" #include "QtCore/QList" #include "QtCore/QMutex" #include "QtCore/QWaitCondition" #include "QtCore/QThread" // std include #include <vector> #include <algorithm> #include <exception> // allied vision image transform include #include "VimbaImageTransform/Include/VmbTransform.h" #include <VimbaCPP/Include/VimbaCPP.h> #include <ctime> #include <stdio.h> #include <iostream> #include <queue> #define num_camera 2 extern std::queue<std::pair<double, int>> timequeue; extern FILE* pfile[num_camera]; extern std::string file[num_camera]; void push(double a, int id); // // Base exception // class BaseException: public std::exception { QString m_Function; QString m_Message; public: BaseException(const char*fun, const char* msg); ~BaseException() throw(); const QString& Function() const; const QString& Message() const; }; // // Exception for video recorder class VideoRecorderException: public BaseException { public: VideoRecorderException(const char* fun, const char*msg); ~VideoRecorderException() throw(); }; // // Video recorder using open cv VideoWriter // class OpenCVRecorder: public QThread { Q_OBJECT; // // Example FOURCC codes that can be used with the OpenCVRecorder // VmbUint32_t maxQueueElements() const; enum { FOURCC_USER_SELECT = CV_FOURCC_PROMPT, FOURCC_DEFAULT = CV_FOURCC_MACRO('I','Y','U','V'), FOURCC_MPEG1 = CV_FOURCC_MACRO('P','I','M','1'), FOURCC_MJPEG = CV_FOURCC_MACRO('M','J','P','G'), FOURCC_MPEG42 = CV_FOURCC_MACRO('M','P','4','2'), FOURCC_MPEG43 = CV_FOURCC_MACRO('M','P','4','3'), FOURCC_DIVX = CV_FOURCC_MACRO('D','I','V','X'), FOURCC_X264 = CV_FOURCC_MACRO('X','2','6','4'), }; // // frame data temporary storage // struct frame_store { private: typedef std::vector<VmbUchar_t> data_vector; data_vector m_Data; // Frame data VmbUint32_t m_Width; // frame width VmbUint32_t m_Height; // frame height VmbPixelFormat_t m_PixelFormat; // frame pixel format public: // // Method: frame_store() // // Purpose: default constructing frame store from data pointer and dimensions // frame_store(const VmbUchar_t *pBuffer, VmbUint32_t BufferByteSize, VmbUint32_t Width, VmbUint32_t Height, VmbPixelFormatType PixelFormat) : m_Data(pBuffer, pBuffer + BufferByteSize) , m_Width(Width) , m_Height(Height) , m_PixelFormat(PixelFormat) { } // // Method: equal // // Purpose: compare frame store to frame dimensions // bool equal(VmbUint32_t Width, VmbUint32_t Height, VmbPixelFormat_t PixelFormat) const { return m_Width == Width && m_Height == Height && m_PixelFormat == PixelFormat; } // // Method: setData // // Purpose: copy data into frame store from matching source // // Returns: false if data size not equal to internal buffer size // bool setData(const VmbUchar_t *Buffer, VmbUint32_t BufferSize) { if (BufferSize == dataSize()) { std::copy(Buffer, Buffer + BufferSize, m_Data.begin()); return true; } return false; } // // Methode: PixelFormat() // // Purpose: get pixel format of internal buffer. // VmbPixelFormat_t pixelFormat() const { return m_PixelFormat; } // // Methode: Width() // // Purpose: get image width. // VmbUint32_t width() const { return m_Width; } // // Methode: Height() // // Purpose: get image height // VmbUint32_t height() const { return m_Height; } // // Methode: dataSize() // // Purpose: get buffer size of internal data. // VmbUint32_t dataSize() const { return static_cast<VmbUint32_t>(m_Data.size()); } // // Methode: data() // // Purpose: get constant internal data pointer. // const VmbUchar_t* data() const { return &*m_Data.begin(); } // // Methode: data() // // Purpose: get internal data pointer. // VmbUchar_t* data() { return &*m_Data.begin(); } }; typedef QSharedPointer<frame_store> FrameStorePtr; // shared pointer to frame store data typedef QList<FrameStorePtr> FrameQueue; // queue of frames tore pointers cv::VideoWriter m_VideoWriter; // OpenCV VideoWriter cv::Mat m_ConvertImage; // storage for converted image, data should only be accessed inside run // size and format are const while thread runs FrameQueue m_FrameQueue; // frame data queue for frames that are to be saved into video stream bool m_StopThread; // flag to signal that the thread has to finish QMutex m_ClassLock; // shared data lock QWaitCondition m_FramesAvailable; // queue frame available condition void run(); bool convertImage(frame_store &frame); public: int cam_id = -1; OpenCVRecorder(const QString &fileName, VmbFloat_t fps, VmbUint32_t Width, VmbUint32_t Height); virtual ~OpenCVRecorder(); void stopThread(); bool enqueueFrame(const AVT::VmbAPI::Frame &frame); int m_framequeue_size(); }; #endif<file_sep>//#pragma once // //#include <QtWidgets/QMainWindow> //#include "ui_MultiCam.h" // //class MultiCam : public QMainWindow //{ // Q_OBJECT // //public: // MultiCam(QWidget *parent = Q_NULLPTR); // //private: // Ui::MultiCamClass ui; //}; #ifndef MULTICAM_H #define MULTICAM_H #include <QtWidgets/QMainWindow> #include "ui_MultiCam.h" #include <VimbaCPP/Include/VimbaCPP.h> #include "ApiController.h" #include "OpenCVVideoRecorder.h" #include "timercpp.h" using AVT::VmbAPI::Examples::ApiController; class MultiCam : public QMainWindow { Q_OBJECT public: MultiCam(QWidget *parent = 0, Qt::WindowFlags flags = 0); ~MultiCam(); private: typedef QSharedPointer<OpenCVRecorder> OpenCVRecorderPtr; //OpenCVRecorderPtr m_pVideoRecorder; std::vector<OpenCVRecorderPtr> m_pVideoRecorders; // The Qt GUI Ui::MultiCamClass ui; // Our controller that wraps API access ApiController m_ApiController; // A list of known camera IDs std::vector<std::string> m_cameras; // A list of selected camera IDs std::vector<std::string> m_selected_cameras; // Are we streaming? bool m_bIsStreaming; // Our Qt image to display //QImage m_Image; std::vector<QImage> m_Images; ActionTimer actt; // // Queries and lists all known camera // void UpdateCameraListBox(); // // Prints out a given logging string, error code and the descriptive representation of that error code // // Parameters: // [in] strMsg A given message to be printed out // [in] eErr The API status code // void Log(std::string strMsg, VmbErrorType eErr); // // Prints out a given logging string // // Parameters: // [in] strMsg A given message to be printed out // void Log(std::string strMsg); // // Copies the content of a byte buffer to a Qt image with respect to the image's alignment // // Parameters: // [in] pInbuffer The byte buffer as received from the cam // [in] ePixelFormat The pixel format of the frame // [out] OutImage The filled Qt image // VmbErrorType CopyToImage(VmbUchar_t *pInBuffer, VmbPixelFormat_t ePixelFormat, QImage &pOutImage, const float *Matrix = NULL); private slots: // The event handler for starting / stopping acquisition void OnBnClickedButtonStartstop(); // // This event handler (Qt slot) is triggered through a Qt signal posted by the frame observer // // Parameters: // [in] status The frame receive status (complete, incomplete, ...) // void OnFrameReady(int msg); // // This event handler (Qt slot) is triggered through a Qt signal posted by the camera observer // // Parameters: // [in] reason The reason why the callback of the observer was triggered (plug-in, plug-out, ...) // void OnCameraListChanged(int reason); void AcquisitionLoop(); // useless signals: void StartActionCommandSignal(); // useless }; #endif<file_sep>#include "OpenCVVideoRecorder.h" #include <windows.h> std::string file[num_camera]; FILE* pfile[num_camera]; std::queue<std::pair<double, int>> timequeue; errno_t err; void push(double a, int id){ timequeue.push({ a, id }); } BaseException::BaseException(const char*fun, const char* msg) { try { if (NULL != fun) { m_Function = QString(fun); } } catch (...) {} try { if (NULL != msg) { m_Message = QString(msg); } } catch (...) {} } BaseException::~BaseException() throw() {} const QString& BaseException::Function() const { return m_Function; } const QString& BaseException::Message() const { return m_Message; } VideoRecorderException::VideoRecorderException(const char* fun, const char*msg) : BaseException(fun, msg) {} VideoRecorderException::~VideoRecorderException() throw() {} VmbUint32_t OpenCVRecorder::maxQueueElements() const { return 3000; } int OpenCVRecorder::m_framequeue_size() { return m_FrameQueue.size(); } void OpenCVRecorder::run() { // clock_t time[3000]; // int count = 0; QMutex mu; while (!m_StopThread) { static int framecnt = 0; mu.lock(); framecnt++; std::cout << framecnt << std::endl; mu.unlock(); double timetmp; int id; FrameStorePtr tmp; { // two class events unlock the queue // first if a frame arrives enqueueFrame wakes the condition // second if the thread is stopped we are woken up // the while loop is necessary because a condition can be woken up by the system QMutexLocker local_lock(&m_ClassLock); while (!m_StopThread && m_FrameQueue.empty()) { m_FramesAvailable.wait(local_lock.mutex()); } if (!m_StopThread) { tmp = m_FrameQueue.front(); m_FrameQueue.pop_front(); } }// scope for the lock, from now one we don't need the class lock if (!m_StopThread) { static QMutex timestp; timestp.lock(); convertImage(*tmp); std::cout << "before write time is : " << clock() << "\n"; m_VideoWriter << m_ConvertImage; std::cout << "after write time is : " << clock() << "\n"; timestp.unlock(); /* if (count < 3000) { time[count] = clock(); count++; } */ } } /* double avg = 0, maxtime = 0; for (int i = 0; i < 2999; i++) { std::cout << i << " frame diff is : " << difftime(time[i+1] , time[i])<< "\n"; avg += difftime(time[i + 1] , time[i]); if (maxtime < difftime(time[i + 1], time[i])) { maxtime = difftime(time[i + 1], time[i]); } } std::cout << "avg is :" << avg / 3000 << "\n"; std::cout << "maxtime is :" << maxtime << "\n"; */ } bool OpenCVRecorder::convertImage(frame_store &frame) { VmbImage srcImage; VmbImage dstImage; srcImage.Size = sizeof(srcImage); dstImage.Size = sizeof(dstImage); VmbSetImageInfoFromPixelFormat(frame.pixelFormat(), frame.width(), frame.height(), &srcImage); VmbSetImageInfoFromPixelFormat(VmbPixelFormatBgr8, m_ConvertImage.cols, m_ConvertImage.rows, &dstImage); srcImage.Data = frame.data(); dstImage.Data = m_ConvertImage.data; return VmbErrorSuccess == VmbImageTransform(&srcImage, &dstImage, NULL, 0); } OpenCVRecorder::OpenCVRecorder(const QString &fileName, VmbFloat_t fps, VmbUint32_t Width, VmbUint32_t Height) : m_StopThread(false) #ifdef _MSC_VER // codec selection only supported by Windows //, m_VideoWriter(fileName.toStdString(), FOURCC_USER_SELECT, fps, cv::Size(Width, Height), true) , m_VideoWriter(fileName.toStdString(), FOURCC_MJPEG, fps, cv::Size(Width, Height), true) #else , m_VideoWriter(fileName.toStdString(), FOURCC_X264, fps, cv::Size(Width, Height), true) #endif , m_ConvertImage(Height, Width, CV_8UC3) { int id = fileName.toStdString().at(22)-'0'; cam_id = id; file[id] = fileName.toStdString(); err = fopen_s(&pfile[id], (file[id] + ".txt").c_str(), "w"); std::cout << "id is " << id << std::endl; std::cout << fileName.toStdString() << std::endl; /* if (err == 0) { fputs(fileName.toStdString().c_str(), pfile); std::cout << "bb"; } */ if (!m_VideoWriter.isOpened()) { throw VideoRecorderException(__FUNCTION__, "could not open recorder"); } } OpenCVRecorder::~OpenCVRecorder() { } void OpenCVRecorder::stopThread() { QMutexLocker local_lock(&m_ClassLock); m_StopThread = true; m_FrameQueue.clear(); m_FramesAvailable.wakeOne(); } bool OpenCVRecorder::enqueueFrame(const AVT::VmbAPI::Frame &frame) { VmbUint32_t Width; VmbUint32_t Height; VmbUint32_t BufferSize; VmbPixelFormatType PixelFormat; const VmbUchar_t* pBuffer(NULL); if (VmbErrorSuccess == frame.GetPixelFormat(PixelFormat) && VmbErrorSuccess == frame.GetWidth(Width) && VmbErrorSuccess == frame.GetHeight(Height) && VmbErrorSuccess == frame.GetBufferSize(BufferSize) && VmbErrorSuccess == frame.GetBuffer(pBuffer)) { if (m_ConvertImage.cols == Width && m_ConvertImage.rows == Height) { QMutexLocker local_lock(&m_ClassLock); FrameStorePtr pFrame; // in case we reached the maximum number of queued frames // take of the oldest and reuse it to store the newly arriving frame if (m_FrameQueue.size() >= static_cast<FrameQueue::size_type>(maxQueueElements())) { std::cout << "m_frame_queue is full\n"; pFrame = m_FrameQueue.front(); m_FrameQueue.pop_front(); if (!pFrame->equal(Width, Height, PixelFormat)) { pFrame.clear(); } } if (pFrame.isNull()) { pFrame = FrameStorePtr(new frame_store(pBuffer, BufferSize, Width, Height, PixelFormat)); } else { pFrame->setData(pBuffer, BufferSize); } m_FrameQueue.push_back(pFrame); m_FramesAvailable.wakeOne(); return true; } } return false; } <file_sep>#ifndef ACTION_TIMER #define ACTION_TIMER #include <iostream> #include <thread> #include <chrono> class ActionTimer { public: ActionTimer(); ~ActionTimer(); template<typename T> void setTimeout(T function, int delay); template<typename T> void setInterval(T function, int interval); void stopInterval(); private: bool clear = false; }; template<typename T> void ActionTimer::setTimeout(T function, int delay) { this->clear = false; std::thread tr_out([=]() { if (this->clear) return; std::this_thread::sleep_for(std::chrono::milliseconds(delay)); if (this->clear) return; function(); }); tr_out.detach(); } template<typename T> void ActionTimer::setInterval(T function, int interval) { this->clear = false; std::thread t_in([=]() { while (true) { if (this->clear) return; std::this_thread::sleep_for(std::chrono::milliseconds(interval)); if (this->clear) return; function(); } }); t_in.detach(); } #endif
c7a32d01f550a0097d35c6d8793e3adf2f20ab06
[ "C++" ]
8
C++
Jhuangsp/sync_multi_camera
574bd7200246dfe737daa1b1f207a3bfa076e5e4
62f4262262327e2b1a448a3f8ace5c7b168fb659
refs/heads/master
<file_sep>import React from 'react'; import TodoListContainer from './todos/todo_list_container'; export default class App extends React.Component { render() { return ( <div> <h1>Todo List App</h1> <TodoListContainer /> <footer> <ul> <li> <a href="https://github.com/julielin0812/todo-list-app">Github Project Repo</a> </li> <li> <a href="https://www.linkedin.com/in/julielin0812/">LinkedIn</a> </li> <li> <a href="http://www.julielin.me/">Portfolio</a> </li> </ul> </footer> </div> ); } } <file_sep>import React from 'react'; export default class TodoDetailView extends React.Component { render() { const {todo, removeTodo } = this.props; return ( <div className='todo-detail'> <h4>Details:</h4> <p>{ todo.body }</p> <button className='delete-button' onClick={ removeTodo }>Delete</button> </div> ); } } <file_sep># Todo List App A simple todo list app using Redux/React for the frontend and `localStorage` to persist state. ![todo-list-app-gif][todo-list-app-gif] <!-- ![todo-list-app-gif][todo-list-app-gif-640-hd] --> [Live Site](https://julielin0812.github.io/todo-list-app/) <!-- [todo-list-app-gif-640-hd]: ./docs/todo-app-640-hd.gif --> [todo-list-app-gif]: ./docs/todo-app.gif <file_sep>import { RECEIVE_ALL_TODOS, RECEIVE_TODO, REMOVE_TODO } from '../actions/todo_actions'; import merge from 'lodash/merge'; // let defaultState = {}; // for testing const initialState = { 1: { id: 1, title: 'Buy groceries', body: 'bread, butter, cheese, eggs, soy milk, coffee', done: false }, 2: { id: 2, title: 'Clean apartment', body: 'sweep, vacuum', done: true }, 3: { id: 3, title: 'Take out trash', body: 'on Wednesday', done: false }, 4: { id: 4, title: 'Call Mom', body: 'or else...', done: true }, }; const todosReducer = (state = initialState, action) => { Object.freeze(state); let nextState; switch (action.type) { case RECEIVE_ALL_TODOS: // does not merge the old `todos` with the new `todos` nextState = {}; action.todos.forEach(function(todo) { nextState[todo.id] = todo; }); return nextState; case RECEIVE_TODO: return merge({}, state, {[action.todo.id]: action.todo}); case REMOVE_TODO: nextState = merge({}, state); delete nextState[action.todo.id]; return nextState; default: return state; } }; export default todosReducer;
a25e73aef86e54b2b25fbf58ae5e08a12befab7e
[ "JavaScript", "Markdown" ]
4
JavaScript
jlincodes/todo-list-app
aa5c9f30ff386a6b920c13b22004ec31e3850052
3f5e070e304cfbeea225caf082df38a448902426
refs/heads/master
<repo_name>edpasa23/carrental<file_sep>/src/main/java/com/eparadas/carrental/repository/BookingRepository.java package com.eparadas.carrental.repository; import com.eparadas.carrental.domain.Booking; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface BookingRepository extends JpaRepository<Booking,Long> { List<Booking> findAllByVehicleId(Long id); List<Booking> findAllByUserId(Long id); List<Booking> findAllByRentId(Long id); Booking findByRentId(Long id); } <file_sep>/src/main/java/com/eparadas/carrental/service/UserValidationService.java package com.eparadas.carrental.service; import com.eparadas.carrental.domain.User; public interface UserValidationService { public String validateUser(User user); } <file_sep>/src/main/java/com/eparadas/carrental/web/ControllerUsers.java package com.eparadas.carrental.web; import com.eparadas.carrental.domain.User; import com.eparadas.carrental.service.UserService; import com.eparadas.carrental.service.UserValidationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; import java.util.List; import java.util.Optional; @Controller public class ControllerUsers { @Autowired private UserService userService; @Autowired private UserValidationService userValidationService; @GetMapping("/usersList") public String viewUsers(Model model){ List<User> clientsList = userService.listAll(); model.addAttribute("userList",clientsList); return "user-list"; } @GetMapping("/deleteUser") public String deleteUser(User user){ userService.delete(user); return "redirect:/usersList"; } @GetMapping("/addUser") public String addUser(User user){ return "add-modify-user"; } @PostMapping("/saveUser") public String saveUser(@Valid User user, BindingResult result, Errors error) { String err = userValidationService.validateUser(user); if (!err.isEmpty()) { ObjectError validationError = new ObjectError("globalError", err); result.addError(validationError); } if (error.hasErrors()) { System.out.println(error.toString()); return "add-modify-user"; } userService.save(user); return "redirect:/usersList"; } @GetMapping("/editUser") public String editUser(User user,Model model){ Optional<User> aux = userService.findUserById(user.getUserId()); if(aux.isPresent()){ user = aux.get(); } model.addAttribute("user", user); return "add-modify-user"; } } <file_sep>/src/main/java/com/eparadas/carrental/domain/Role.java package com.eparadas.carrental.domain; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import java.io.Serializable; @Entity @Data @Table(name = "role") public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "role_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long roleId; @NotEmpty @Column(name = "name") private String name; } <file_sep>/src/main/java/com/eparadas/carrental/serviceimpl/BookingValidationServiceImpl.java package com.eparadas.carrental.serviceimpl; import com.eparadas.carrental.domain.Booking; import com.eparadas.carrental.domain.User; import com.eparadas.carrental.service.BookingService; import com.eparadas.carrental.service.BookingValidationService; import com.eparadas.carrental.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.List; @Service public class BookingValidationServiceImpl implements BookingValidationService { @Autowired private UserService userService; @Autowired private BookingService bookingService; @Override public String validateBooking(Booking booking) { String message = ""; LocalDate todaysdate = LocalDate.now(); LocalDate from = booking.getRentFrom(); LocalDate to = booking.getRentTo(); if(todaysdate.isAfter(from)){ message = message + " *\"Rent From\" date has already passed"; } if(todaysdate.isAfter(to)){ message = message + " *\"Rent to\" date has already passed"; } if(to.isBefore(from)){ message = message + " *Not valid rent dates"; } List<Booking> bookings = bookingService.findAllByVehicleId(booking.getVehicleId()); for(Booking x: bookings){ if(from.isAfter(x.getRentFrom()) && from.isBefore(x.getRentTo())){ message = message + " *The vehicule is alredy rented for that date"; break; } if(to.isAfter(x.getRentFrom()) && to.isBefore(x.getRentTo())){ message = message + " *The vehicule is alredy rented for that date"; break; } } return message; } } <file_sep>/src/main/java/com/eparadas/carrental/service/VehicleService.java package com.eparadas.carrental.service; import com.eparadas.carrental.domain.Vehicle; import java.util.List; import java.util.Optional; public interface VehicleService { List<Vehicle> listAll(); void save(Vehicle vehicle); void register(Vehicle vehicle); void delete(Vehicle vehicle); Optional<Vehicle> findVehicleById(Long vehicleId); List<Vehicle> findAllByRentPriceOrderByAsc(); List<Vehicle> findAllByRentPriceOrderByDesc(); List<Vehicle> findAllByBrandOrderByAsc(); List<Vehicle> findAllByBrandOrderByDesc(); List<Vehicle> findAllByModelOrderByAsc(); List<Vehicle> findAllByModelOrderByDesc(); List<Vehicle> findAllByTypeOrderByAsc(); List<Vehicle> findAllByTypeOrderByDesc(); List<Vehicle> findAllByColourOrderByAsc(); List<Vehicle> findAllByColourOrderByDesc(); List<Vehicle> findAllByTransmissionOrderByAsc(); List<Vehicle> findAllByTransmissionOrderByDesc(); } <file_sep>/src/main/java/com/eparadas/carrental/serviceimpl/UserServiceImpl.java package com.eparadas.carrental.serviceimpl; import com.eparadas.carrental.domain.Role; import com.eparadas.carrental.domain.User; import com.eparadas.carrental.repository.RoleRepository; import com.eparadas.carrental.repository.UserRepository; import com.eparadas.carrental.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; @Service("userDetailsService") public class UserServiceImpl implements UserService, UserDetailsService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private RoleRepository roleRepository; //*****************Method for Login********************** @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if(user == null){ throw new UsernameNotFoundException(username); } ArrayList grantedAuthoritySet = new ArrayList<GrantedAuthority>(); for(Role role : user.getRole()){ grantedAuthoritySet.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthoritySet); } //****************************************************** @Override @Transactional(readOnly = true) public List<User> listAll() { return (List<User>) userRepository.findAll(); } @Override @Transactional public void save(User user) { User aux = userRepository.findByUsername(user.getUsername()); user.setRole(aux.getRole()); userRepository.save(user); } @Override @Transactional public void delete(User user) { userRepository.delete(user); } @Override @Transactional public void register(User user) { //Encripta password user.setPassword(<PASSWORD>.encode(user.getPassword())); //Guarda el rol nuevo Role roleAux = new Role(); roleAux.setName("ROLE_USER"); roleRepository.save(roleAux); // ArrayList roles = new ArrayList<GrantedAuthority>(); roles.add(roleAux); user.setRole(roles); userRepository.save(user); } @Override @Transactional(readOnly = true) public Optional<User> findUserById(Long userId) { return userRepository.findById(userId); } @Override @Transactional(readOnly = true) public User findUserByEmail(String email) { User userAux = userRepository.findByEmail(email); return userAux; } @Override @Transactional(readOnly = true) public User findUserByPhone(String phone) { User userAux = userRepository.findByPhone(phone); return userAux; } @Override @Transactional(readOnly = true) public User findUserByUsername(String username) { User userAux = userRepository.findByUsername(username); return userAux; } }<file_sep>/src/main/java/com/eparadas/carrental/repository/UserRepository.java package com.eparadas.carrental.repository; import com.eparadas.carrental.domain.Role; import com.eparadas.carrental.domain.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepository extends JpaRepository<User, Long> { //Login Method User findByUsername(String username); // User findByEmail(String email); User findByPhone(String phone); } <file_sep>/src/main/java/com/eparadas/carrental/service/BookingService.java package com.eparadas.carrental.service; import com.eparadas.carrental.domain.Booking; import java.util.List; public interface BookingService { List<Booking> findAll(); void save(Booking reservation); void delete(Booking reservation); Booking findReservation(Booking booking); List<Booking> findAllByVehicleId(Long vehicleId); List<Booking> findAllByUserId(Long userId); List<Booking> findAllByRentId(Long rentId); Booking findByRentId(Long rentId); } <file_sep>/src/main/java/com/eparadas/carrental/web/ControllerVehicles.java package com.eparadas.carrental.web; import com.eparadas.carrental.domain.Vehicle; import com.eparadas.carrental.service.VehicleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; import java.util.List; import java.util.Optional; @Controller public class ControllerVehicles { @Autowired private VehicleService vehicleService; @GetMapping("/deleteCar") public String deleteCar(Vehicle vehicle){ vehicleService.delete(vehicle); return "redirect:/carsList"; } @GetMapping("/editCar") public String editCar(Vehicle vehicle, Model model){ Optional<Vehicle> aux = vehicleService.findVehicleById(vehicle.getVehicleId()); if(aux.isPresent()){ vehicle = aux.get(); } model.addAttribute("vehicle",vehicle); return "edit-car"; } @PostMapping("/saveCar") public String saveCar(@Valid Vehicle vehicle, BindingResult result, Errors error) { if (error.hasErrors()) { System.out.println(error.toString()); return "edit-car"; } vehicleService.save(vehicle); return "redirect:/carsList"; } @PostMapping("/registerCar") public String registerCar(@Valid Vehicle vehicle, BindingResult result, Errors error) { if (error.hasErrors()) { return "add-car"; } vehicleService.register(vehicle); return "redirect:/cars-list"; } @GetMapping("/addCar") public String addCar(Vehicle vehicle){ return "add-car"; } @GetMapping("/carsList") public String viewCars(Model model){ List<Vehicle> carsList = vehicleService.listAll(); model.addAttribute("carsList",carsList); return "cars-list"; } }
a010f5dc5c4cad960f27869615e00ce96a81f15d
[ "Java" ]
10
Java
edpasa23/carrental
857b91c2b78ed1d53375dbabd20d2d08dff7e6d2
4d9e60a23797248ea18543cbf77869953b21c6ec
refs/heads/master
<repo_name>eltarkan/AnimeNamesFromMyAnimeList<file_sep>/README.md # Anime Names From MyAnimeList I HATE ANIMES </br> How to be WebScraper? </br> I wrote this using NodeJS <file_sep>/pars.js var osmosis = require('osmosis'); var fs = require('fs'); var sql = require('mysql'); var replaceall = require("replaceall"); var animes = []; var test = []; var counter = 0; var con = sql.createConnection({ host: "localhost", database: "top_animes", user: "root", password: "" }); con.connect(function(err){ if (err) throw err; console.log("Connected!!!!"); }); function scrapIt(url) { osmosis .get(url) .find('.ranking-list') .set({ Sira: 'span', Adi: '.detail a', Bilgiler: '.information', Puani: '.score span', Link: '.detail @href' }) .data(function(data){ Display(data); }); } function Display(content){ test = content; test.Adi = replaceall("'", "/", test.Adi); test.Link = replaceall("'", "/", test.Link); var sql = "INSERT INTO animeler (ad) VALUES ('" + test +"')"; var sql = "INSERT INTO animeler (sira, ad, puan, link) VALUES ('" + test.Sira + "', '" + test.Adi + "', '" + test.Puani + "', '" + test.Link + "')"; con.query(sql, function (err, result) { if (err) throw err; console.log("1 record inserted " + counter); }); } function MagicHappensHere() { var dex = 0; while(dex < 15000){ counter = dex; url = 'https://myanimelist.net/topanime.php' + '?limit=' + dex; scrapIt(url); dex = dex + 50; } url = 'https://myanimelist.net/topanime.php'; scrapIt(url); } MagicHappensHere();
7bcc659e536fa7298b0e8b3108de36e5b3e49e49
[ "Markdown", "JavaScript" ]
2
Markdown
eltarkan/AnimeNamesFromMyAnimeList
2717370eb74d080234dae610ba798849ff593b29
319da4260aaf041f272fae11e20fa5ceac34ce3a